diff --git a/Cargo.lock b/Cargo.lock index 85c996f59f..1c42a9049f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8056,6 +8056,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-util", + "toml_edit", "tracing", "uuid", ] @@ -8627,6 +8628,7 @@ dependencies = [ "indexmap 2.14.2", "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", + "toml_writer", "winnow 1.0.4", ] diff --git a/Cargo.toml b/Cargo.toml index 33abb65cd8..93589a4a14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,8 @@ async-trait = "0.1" thiserror = "2" serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["raw_value"] } +# Edits a TOML config file and keeps its comments and layout. +toml_edit = "0.25.15" sqlparser = { version = "0.63", default-features = false, features = ["std"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync", "process"] } tokio-util = { version = "0.7", default-features = false, features = ["codec", "rt"] } diff --git a/apple/.swiftlint.yml b/apple/.swiftlint.yml index 6647ff85a7..18f3dbed90 100644 --- a/apple/.swiftlint.yml +++ b/apple/.swiftlint.yml @@ -485,6 +485,8 @@ custom_rules: - '.*/[^/]*Tests/' - '.*Tests\.swift$' - '.*/(WebPageOpener|DataLinkPolicy|MCPPairingService|NotificationsSettingsView|SyncSettingsView|ConnectionRecoveryPerformer|OpenConnectionIntent)\.swift$' + # An MCP client's install link, built from the bundled catalog, opened only when its scheme has a handler app. + - '.*/MCPClientWorkspace\.swift$' # Open TablePro's own links, and the user's files and URLs, in the TablePro bundle the command ships in. - '.*/(Handshake|CLILiveEnvironment)\.swift$' - '.*/(AppDelegate\+MainMenuActions|WhatsNewWindowController|SupportAskCoordinator|MainContentCoordinator\+Rewind|GoogleSignInService|ChatGPTCodexService)\.swift$' diff --git a/apple/Packages/TableProMacCore/Package.resolved b/apple/Packages/TableProMacCore/Package.resolved index c787a21fdc..5d1eba5006 100644 --- a/apple/Packages/TableProMacCore/Package.resolved +++ b/apple/Packages/TableProMacCore/Package.resolved @@ -1,6 +1,96 @@ { - "originHash" : "8416d6d6bf8d3efe83e2ee5a577c19c0a4be27502e2168e80ca90b420e98f493", + "originHash" : "29b72a8457d74c9a15f782101f6c1a36838ce85add174125f4a5973f800d250f", "pins" : [ + { + "identity" : "openapikit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/mattpolzin/OpenAPIKit", + "state" : { + "revision" : "5b72eb9a6b23b1fec439d9a0bf38f115400421f9", + "version" : "6.4.0" + } + }, + { + "identity" : "swift-algorithms", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-algorithms", + "state" : { + "revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023", + "version" : "1.2.1" + } + }, + { + "identity" : "swift-argument-parser", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-argument-parser", + "state" : { + "revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382", + "version" : "1.8.2" + } + }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections", + "state" : { + "revision" : "88754449ab766a739610b660e117762115fabc9c", + "version" : "1.7.6" + } + }, + { + "identity" : "swift-http-types", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-http-types", + "state" : { + "revision" : "bff4b6903cdc99dda49649dd52f46c11cfd3ed50", + "version" : "1.8.0" + } + }, + { + "identity" : "swift-numerics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-numerics.git", + "state" : { + "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2", + "version" : "1.1.1" + } + }, + { + "identity" : "swift-openapi-generator", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-openapi-generator", + "state" : { + "revision" : "bf578ce357a0d2aa07af9de41b083cc2c986a498", + "version" : "1.14.1" + } + }, + { + "identity" : "swift-openapi-runtime", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-openapi-runtime", + "state" : { + "revision" : "50ad7976f18fec6c09466d2aebf7be3dc9476cfb", + "version" : "1.13.0" + } + }, + { + "identity" : "swift-openapi-urlsession", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-openapi-urlsession", + "state" : { + "revision" : "c97e0f0187d95542b4a254f5bb4dc67f43bf73c9", + "version" : "1.4.0" + } + }, + { + "identity" : "yams", + "kind" : "remoteSourceControl", + "location" : "https://github.com/jpsim/Yams", + "state" : { + "revision" : "a27b21e0c81c5bf42049b897a62aaf387e80f279", + "version" : "6.2.2" + } + }, { "identity" : "zstd", "kind" : "remoteSourceControl", diff --git a/apple/Packages/TableProMacCore/Package.swift b/apple/Packages/TableProMacCore/Package.swift index 143b1afc61..016b422475 100644 --- a/apple/Packages/TableProMacCore/Package.swift +++ b/apple/Packages/TableProMacCore/Package.swift @@ -20,6 +20,7 @@ let package = Package( .library(name: "TableProUtilities", targets: ["TableProUtilities"]), .library(name: "TableProSSHConfig", targets: ["TableProSSHConfig"]), .library(name: "TableProMCP", targets: ["TableProMCP"]), + .library(name: "TableProMCPClients", targets: ["TableProMCPClients"]), // Only the tablepro-cli tool links this; the app never does, so ArgumentParser stays out of it. .library(name: "TableProCommandLine", targets: ["TableProCommandLine"]), .library(name: "TableProMCPTestSupport", targets: ["TableProMCPTestSupport"]), @@ -66,6 +67,11 @@ let package = Package( path: "Sources/TableProMCP", swiftSettings: appModuleSettings ), + .target( + name: "TableProMCPClients", + path: "Sources/TableProMCPClients", + swiftSettings: appModuleSettings + ), .target( name: "TableProCommandLine", dependencies: [ @@ -126,6 +132,12 @@ let package = Package( path: "Tests/TableProMCPTests", swiftSettings: appModuleSettings ), + .testTarget( + name: "TableProMCPClientsTests", + dependencies: ["TableProMCPClients"], + path: "Tests/TableProMCPClientsTests", + swiftSettings: appModuleSettings + ), .testTarget( name: "TableProCommandLineTests", dependencies: [ diff --git a/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLICallbackListener.swift b/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLICallbackListener.swift index 289d8c499a..b7e391044a 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLICallbackListener.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLICallbackListener.swift @@ -144,6 +144,9 @@ public final class CLICallbackListener: @unchecked Sendable { case .denied: status = "200 OK" message = "Pairing was declined. You can close this tab." + case .failed: + status = "200 OK" + message = "TablePro could not finish pairing. You can close this tab." case .ignored: status = "404 Not Found" message = "Nothing here." diff --git a/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLILiveEnvironment.swift b/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLILiveEnvironment.swift index b02cba18ff..0e017cdbfd 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLILiveEnvironment.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProCommandLine/CLILiveEnvironment.swift @@ -39,13 +39,8 @@ enum CLILive { let handshake: MCPHandshakePayload do { handshake = try await MCPHandshakeAcquirer(logger: logger).acquire() - } catch MCPHandshakeAcquisitionError.serverTurnedOff { - throw CLIFailure( - .refused, - "TablePro's MCP server is turned off, and the tablepro command reaches TablePro through it. Turn it on under Settings > MCP." - ) } catch { - throw CLIFailure(.failure, "TablePro did not start its MCP server: \(error.localizedDescription)") + throw failure(acquiring: error) } do { return try await verified(handshake, logger: logger) @@ -54,6 +49,23 @@ enum CLILive { } } + static func failure(acquiring error: Error) -> CLIFailure { + switch error as? MCPHandshakeAcquisitionError { + case .serverTurnedOff?: + return CLIFailure( + .refused, + "TablePro's MCP server is turned off, and the tablepro command reaches TablePro through it. Turn it on under Settings > MCP." + ) + case .serverFailedToStart?: + return CLIFailure( + .failure, + "TablePro's MCP server is on but could not start. Open Settings > MCP in TablePro to see why, then run the command again." + ) + case .launchFailed?, .timeout?, nil: + return CLIFailure(.failure, "TablePro did not start its MCP server: \(error.localizedDescription)") + } + } + // One read of the handshake, no launch and no polling: status must answer at once. static func findServer(app: CLIHostApp) async -> CLIServerProbe { let logger = MCPOSBridgeLogger(category: "CLI") @@ -103,6 +115,8 @@ enum CLILive { return try await CLIServerClient.exchange(code: code, verifier: request.verifier, socketPath: server.socketPath, serverPID: server.serverPID) case .denied: throw CLIFailure(.refused, "Pairing was declined in TablePro.") + case .failed: + throw CLIFailure(.failure, "TablePro could not issue a token for the tablepro command. TablePro shows why; run the command again.") case .ignored, nil: throw CLIFailure(.refused, "Pairing was not approved in time.") } diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Auth/MCPAuthenticator.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Auth/MCPAuthenticator.swift index c09fb3f0a7..a39571e89f 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Auth/MCPAuthenticator.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Auth/MCPAuthenticator.swift @@ -21,6 +21,16 @@ public enum MCPClientAddress: Sendable, Equatable, Hashable { return host } } + + // For the window only: the audit log stores displayValue, so that one stays English. + public var localizedDisplayValue: String { + switch self { + case .localSocket: + return String(localized: "Local socket") + case .loopback, .remote: + return displayValue + } + } } public protocol MCPAuthenticator: Sendable { diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/BridgeProxy.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/BridgeProxy.swift index 6f92183f1f..f980f2428c 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/BridgeProxy.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/BridgeProxy.swift @@ -176,6 +176,7 @@ public actor BridgeProxy { private let hostLines: AsyncStream private let logger: any MCPBridgeLogger private let discovery: BridgeDiscovery + private let instanceId = UUID().uuidString private var clientInfo: JsonValue? @@ -248,12 +249,12 @@ public actor BridgeProxy { private func forward(line: Data, peek: BridgeMessagePeek, method: String) async { var body = line - if !peek.declaresProtocolVersion { - if let stamped = BridgeJson.stampMeta(line, fields: metaFields()) { - body = stamped - } else { - logger.log(.warning, "Could not stamp request metadata onto \(method)") - } + // The instance goes on every message, so a cancellation sent without metadata meets the request it names. + let fields = peek.declaresProtocolVersion ? instanceField() : metaFields() + if let stamped = BridgeJson.stampMeta(line, fields: fields) { + body = stamped + } else { + logger.log(.warning, "Could not stamp request metadata onto \(method)") } do { @@ -312,9 +313,15 @@ public actor BridgeProxy { await stdout.write(data) } + // Two sessions of one client send the same clientInfo and the same request ids; this keeps them apart. + private func instanceField() -> Data { + Data("\"\(MCPMetaKeys.bridgeInstance)\":\"\(instanceId)\"".utf8) + } + private func metaFields() -> Data { var fields = Data("\"\(MCPMetaKeys.protocolVersion)\":\"\(MCPProtocolVersion.latest.rawValue)\"".utf8) - fields.append(Data(",\"\(MCPMetaKeys.clientCapabilities)\":{}".utf8)) + fields.append(Data(",\"\(MCPMetaKeys.clientCapabilities)\":{},".utf8)) + fields.append(instanceField()) guard let clientInfo, let encoded = try? JSONEncoder().encode(clientInfo) else { return fields } fields.append(Data(",\"\(MCPMetaKeys.clientInfo)\":".utf8)) fields.append(encoded) diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/Handshake.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/Handshake.swift index 23daf32939..dd81a1479d 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/Handshake.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Bridge/Handshake.swift @@ -7,6 +7,7 @@ public enum MCPHandshakeAcquisitionError: Error, LocalizedError, Equatable { case launchFailed(String) case timeout(lastFailure: String) case serverTurnedOff + case serverFailedToStart public var errorDescription: String? { switch self { @@ -16,6 +17,8 @@ public enum MCPHandshakeAcquisitionError: Error, LocalizedError, Equatable { return "Timed out waiting for a trusted TablePro MCP handshake (\(lastFailure))" case .serverTurnedOff: return "The TablePro MCP server is turned off. Turn it on in TablePro under Settings > MCP." + case .serverFailedToStart: + return "The TablePro MCP server is turned on but failed to start. Open Settings > MCP in TablePro to see why and try again." } } } @@ -72,12 +75,13 @@ public struct MCPHandshakeAcquirer: Sendable { // A forged refusal can only make the bridge give up, so it is read without the handshake's // ownership checks. - private func refusalAnswers(launchRequestedAt: Date) -> Bool { + private func refusalAnswering(launchRequestedAt: Date) -> MCPStartRefusal? { guard let data = try? Data(contentsOf: refusalUrl), - let refusal = try? MCPHandshakeCoding.decoder().decode(MCPStartRefusal.self, from: data) else { - return false + let refusal = try? MCPHandshakeCoding.decoder().decode(MCPStartRefusal.self, from: data), + refusal.answers(launchRequestedAt: launchRequestedAt) else { + return nil } - return refusal.answers(launchRequestedAt: launchRequestedAt) + return refusal } // The copy this helper ships in, not whichever copy owns `tablepro://`. Substitution stays on, so a @@ -115,9 +119,15 @@ public struct MCPHandshakeAcquirer: Sendable { if let payload = attempt.payload { return payload } - if let launchRequestedAt, refusalAnswers(launchRequestedAt: launchRequestedAt) { - logger.log(.error, "TablePro refused to start the MCP server: it is turned off") - throw MCPHandshakeAcquisitionError.serverTurnedOff + if let launchRequestedAt, let refusal = refusalAnswering(launchRequestedAt: launchRequestedAt) { + switch refusal.reason { + case .turnedOff: + logger.log(.error, "TablePro refused to start the MCP server: it is turned off") + throw MCPHandshakeAcquisitionError.serverTurnedOff + case .failedToStart: + logger.log(.error, "TablePro tried to start the MCP server and failed") + throw MCPHandshakeAcquisitionError.serverFailedToStart + } } lastFailure = attempt.failure try? await Task.sleep(for: Self.pollInterval) diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/CommandLine/CLIPairing.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/CommandLine/CLIPairing.swift index 3d1f2d74e1..d46f8a42c3 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/CommandLine/CLIPairing.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/CommandLine/CLIPairing.swift @@ -58,6 +58,8 @@ public struct CLIPairingRequest: Sendable, Equatable { public enum CLIPairingCallback: Sendable, Equatable { case approved(code: String) case denied + // Approved in TablePro, which then could not issue the token. + case failed // Another path, or a `state` from some other request. case ignored @@ -74,6 +76,13 @@ public enum CLIPairingCallback: Sendable, Equatable { if let code = value("code"), !code.isEmpty { return .approved(code: code) } - return value("error") == nil ? .ignored : .denied + switch value("error") { + case nil: + return .ignored + case "access_denied"?, "denied"?: + return .denied + default: + return .failed + } } } diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientActivityLedger.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientActivityLedger.swift index c88480fa5a..87e2a53438 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientActivityLedger.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientActivityLedger.swift @@ -4,29 +4,35 @@ public actor MCPClientActivityLedger { public struct Entry: Sendable, Identifiable, Equatable { public let id: String public let clientName: String + public let clientInfoName: String? public let clientVersion: String? public let tokenId: UUID? public let tokenName: String? public let address: String + public let transport: MCPClientTransport public let firstSeenAt: Date public let lastSeenAt: Date public init( id: String, clientName: String, + clientInfoName: String? = nil, clientVersion: String?, tokenId: UUID?, tokenName: String?, address: String, + transport: MCPClientTransport = .http, firstSeenAt: Date, lastSeenAt: Date ) { self.id = id self.clientName = clientName + self.clientInfoName = clientInfoName self.clientVersion = clientVersion self.tokenId = tokenId self.tokenName = tokenName self.address = address + self.transport = transport self.firstSeenAt = firstSeenAt self.lastSeenAt = lastSeenAt } @@ -57,10 +63,12 @@ public actor MCPClientActivityLedger { entries[identity.id] = Entry( id: identity.id, clientName: identity.clientName, + clientInfoName: identity.clientInfoName, clientVersion: identity.clientVersion, tokenId: identity.tokenId, tokenName: identity.tokenName, - address: identity.addressDisplayValue, + address: identity.address.localizedDisplayValue, + transport: identity.transport, firstSeenAt: existing?.firstSeenAt ?? timestamp, lastSeenAt: timestamp ) diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientIdentity.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientIdentity.swift index 6859497ac2..2495284642 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientIdentity.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Identity/MCPClientIdentity.swift @@ -1,30 +1,43 @@ import CryptoKit import Foundation +public enum MCPClientTransport: Sendable, Equatable, Hashable { + // The credential every stdio client shares through the tablepro-mcp helper; it rotates on its own. + case stdioBridge + // A credential of its own: a token from Settings or pairing, over TCP or the app's socket. + case http +} + public struct MCPClientIdentity: Sendable, Equatable, Hashable, Identifiable { public static let unknownClientName = String(localized: "Unknown client") public let clientName: String + public let clientInfoName: String? public let clientVersion: String? public let tokenId: UUID? public let tokenName: String? public let principalFingerprint: String public let address: MCPClientAddress + public let transport: MCPClientTransport public init( clientName: String, + clientInfoName: String? = nil, clientVersion: String?, tokenId: UUID?, tokenName: String?, principalFingerprint: String, - address: MCPClientAddress + address: MCPClientAddress, + transport: MCPClientTransport = .http ) { self.clientName = clientName + self.clientInfoName = clientInfoName self.clientVersion = clientVersion self.tokenId = tokenId self.tokenName = tokenName self.principalFingerprint = principalFingerprint self.address = address + self.transport = transport } public init(meta: MCPRequestMeta, principal: MCPPrincipal, address: MCPClientAddress) { @@ -33,11 +46,13 @@ public struct MCPClientIdentity: Sendable, Equatable, Hashable, Identifiable { let resolvedVersion = info?.version.nilIfBlank self.init( clientName: resolvedName, + clientInfoName: info?.name.nilIfBlank, clientVersion: resolvedVersion, tokenId: principal.tokenId, tokenName: principal.metadata.label, principalFingerprint: principal.tokenFingerprint, - address: address + address: address, + transport: principal.metadata.isBridgeCredential ? .stdioBridge : .http ) } @@ -46,13 +61,15 @@ public struct MCPClientIdentity: Sendable, Equatable, Hashable, Identifiable { } public var id: String { - let fields = [ - clientName, - clientVersion ?? "", - tokenId?.uuidString ?? "", - principalFingerprint, - address.displayValue - ] + let credential: [String] + switch transport { + case .stdioBridge: + // The bridge credential rotates every 45 minutes, so a stdio client is the client it says it is. + credential = ["stdio-bridge"] + case .http: + credential = [tokenId?.uuidString ?? "", principalFingerprint] + } + let fields = [clientName, clientInfoName ?? "", clientVersion ?? ""] + credential + [address.displayValue] let joined = fields.joined(separator: "\u{1F}") let digest = SHA256.hash(data: Data(joined.utf8)) return String(digest.map { String(format: "%02x", $0) }.joined().prefix(16)) diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Lifecycle/MCPHandshakeFile.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Lifecycle/MCPHandshakeFile.swift index bc736e293e..50b29284c3 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Lifecycle/MCPHandshakeFile.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Lifecycle/MCPHandshakeFile.swift @@ -37,14 +37,39 @@ public struct MCPHandshakePayload: Codable, Sendable, Equatable { } public struct MCPStartRefusal: Codable, Sendable, Equatable { + // A code, never text: the file is read without the handshake's ownership checks, so whatever it + // says reaches the client only as one of the bridge's own messages. + public enum Reason: String, Codable, Sendable { + case turnedOff + case failedToStart + } + public let pid: Int32 // Seconds since 1970 with the fraction kept: an ISO 8601 date drops it, and a refusal from // earlier in the same second would then answer a launch it never saw. public let refusedAt: TimeInterval + public let reason: Reason + + private enum CodingKeys: String, CodingKey { + case pid + case refusedAt + case reason + } - public init(pid: Int32, refusedAt: Date) { + public init(pid: Int32, refusedAt: Date, reason: Reason = .turnedOff) { self.pid = pid self.refusedAt = refusedAt.timeIntervalSince1970 + self.reason = reason + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + pid = try container.decode(Int32.self, forKey: .pid) + refusedAt = try container.decode(TimeInterval.self, forKey: .refusedAt) + // Builds before the reason wrote a refusal only when MCP was off; a reason this build does not + // know still means the server is not coming up. + let raw = (try? container.decodeIfPresent(String.self, forKey: .reason)) ?? nil + reason = raw.map { Reason(rawValue: $0) ?? .failedToStart } ?? .turnedOff } // Only a refusal written after the launch answers it, so one left from an earlier run cannot diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPMetaKeys.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPMetaKeys.swift index d7ce070179..e1f26bc4ce 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPMetaKeys.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPMetaKeys.swift @@ -8,6 +8,7 @@ public enum MCPMetaKeys { public static let logLevel = "io.modelcontextprotocol/logLevel" public static let subscriptionId = "io.modelcontextprotocol/subscriptionId" public static let serverInfo = "io.modelcontextprotocol/serverInfo" + public static let bridgeInstance = "app.tablepro/bridgeInstance" public static let traceParent = "traceparent" public static let traceState = "tracestate" diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPRequestMeta.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPRequestMeta.swift index 6f3e700044..45e38225fa 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPRequestMeta.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Meta/MCPRequestMeta.swift @@ -29,6 +29,15 @@ public struct MCPRequestMeta: Sendable, Equatable { params?["_meta"] } + // The tablepro-mcp process that forwarded the message. Any local client can write it, so only the + // in-flight key reads it, and only for the bridge credential. + public static func bridgeInstance(in params: JsonValue?) -> String? { + guard let value = metaObject(in: params)?[MCPMetaKeys.bridgeInstance]?.stringValue, !value.isEmpty else { + return nil + } + return value + } + public static func declaresModernProtocol(params: JsonValue?) -> Bool { metaObject(in: params)?[MCPMetaKeys.protocolVersion]?.stringValue != nil } diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCP/Protocol/MCPInflightRegistry.swift b/apple/Packages/TableProMacCore/Sources/TableProMCP/Protocol/MCPInflightRegistry.swift index 026dc332aa..e1a536de4b 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProMCP/Protocol/MCPInflightRegistry.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProMCP/Protocol/MCPInflightRegistry.swift @@ -1,23 +1,52 @@ import Foundation public struct MCPInflightKey: Sendable, Hashable { + // The bridge credential rotates while its requests run, so a cancellation sent with the renewed + // one has to find a request started with the old one. + public static let bridgeCredentialFingerprint = "stdio-bridge" + public let clientFingerprint: String + // Only for stdio without a bridge instance: stdio clients share one credential, so the sender's identity splits them. + public let clientId: String + // The whole stdio sender, since a request may carry clientInfo its cancellation lacks; Disconnect uses the entry's clientId. + public let bridgeInstance: String public let requestId: JsonRpcId - public init(clientFingerprint: String, requestId: JsonRpcId) { + public init(clientFingerprint: String, clientId: String = "", bridgeInstance: String = "", requestId: JsonRpcId) { self.clientFingerprint = clientFingerprint + self.clientId = clientId + self.bridgeInstance = bridgeInstance self.requestId = requestId } public init(principal: MCPPrincipal, requestId: JsonRpcId) { self.init(clientFingerprint: principal.tokenFingerprint, requestId: requestId) } + + public init(bridgeInstance: String, requestId: JsonRpcId) { + self.init(clientFingerprint: Self.bridgeCredentialFingerprint, bridgeInstance: bridgeInstance, requestId: requestId) + } + + // A token one client holds ignores bridgeInstance: the field only splits requests of one stdio client kind. + public init(client: MCPClientIdentity, bridgeInstance: String? = nil, requestId: JsonRpcId) { + switch client.transport { + case .stdioBridge: + if let bridgeInstance, !bridgeInstance.isEmpty { + self.init(bridgeInstance: bridgeInstance, requestId: requestId) + } else { + self.init(clientFingerprint: Self.bridgeCredentialFingerprint, clientId: client.id, requestId: requestId) + } + case .http: + self.init(clientFingerprint: client.principalFingerprint, requestId: requestId) + } + } } public actor MCPInflightRegistry { private struct Entry { let token: MCPCancellationToken let tokenId: UUID? + let clientId: String? let method: String let startedAt: Date } @@ -31,11 +60,12 @@ public actor MCPInflightRegistry { key: MCPInflightKey, token: MCPCancellationToken, tokenId: UUID?, + clientId: String? = nil, method: String, startedAt: Date ) -> Bool { let displaced = entries[key] != nil - entries[key] = Entry(token: token, tokenId: tokenId, method: method, startedAt: startedAt) + entries[key] = Entry(token: token, tokenId: tokenId, clientId: clientId, method: method, startedAt: startedAt) return !displaced } @@ -56,6 +86,11 @@ public actor MCPInflightRegistry { await cancelMatching(reason: reason) { _, entry in entry.tokenId == tokenId } } + @discardableResult + public func cancelAll(matchingClientId clientId: String, reason: MCPCancellationReason) async -> Int { + await cancelMatching(reason: reason) { _, entry in entry.clientId == clientId } + } + @discardableResult public func cancelAll(matchingFingerprint fingerprint: String, reason: MCPCancellationReason) async -> Int { await cancelMatching(reason: reason) { key, _ in key.clientFingerprint == fingerprint } diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONCMemberEditor.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONCMemberEditor.swift new file mode 100644 index 0000000000..da8841f8b2 --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONCMemberEditor.swift @@ -0,0 +1,411 @@ +import Foundation + +// Edits one member of a JSON or JSONC file as text. A JSONSerialization round trip drops comments, reorders keys and +// re-indents the whole file, so nothing here writes through it; it only checks each edit afterwards. +public enum JSONCMemberEditor { + public static func member(_ name: String, at keyPath: [String], in text: String) throws -> JSONValue? { + let bytes = Array(text.utf8) + guard let root = try JSONCParser.parse(bytes) else { return nil } + guard let container = try walk(root, keyPath: keyPath) else { return nil } + return try uniqueMember(name, in: container, path: keyPath)?.value.value + } + + public static func upserting(_ name: String, value: JSONValue, at keyPath: [String], in text: String) throws -> String { + let bytes = Array(text.utf8) + let result: String + if let root = try JSONCParser.parse(bytes) { + let document = Document(bytes: bytes, root: root) + result = try document.upserting(name, value: value, at: keyPath) + } else { + result = startingDocument(name, value: value, at: keyPath, after: text) + } + try verify(old: text, new: result, keyPath: keyPath, name: name, expected: value) + return result + } + + // Update: `entry` is rendered from `template`, which says which members are TablePro's to rewrite (MCPEntryUpdate). + public static func updating( + _ name: String, + entry: JSONValue, + template: JSONValue, + at keyPath: [String], + in text: String + ) throws -> String { + switch MCPEntryUpdate.plan(existing: try member(name, at: keyPath, in: text), entry: entry, template: template) { + case .replace(let value): try upserting(name, value: value, at: keyPath, in: text) + case .merge(let value): try merging(name, value: value, at: keyPath, in: text) + } + } + + // Rewrites only the members `value` names inside an existing object entry, so keys the user added to it stay. + public static func merging(_ name: String, value: JSONValue, at keyPath: [String], in text: String) throws -> String { + guard case .object(let wanted) = value, + let existing = try member(name, at: keyPath, in: text), + existing.objectMembers != nil else { + return try upserting(name, value: value, at: keyPath, in: text) + } + var result = text + for part in wanted where existing[part.key] != part.value { + result = try merging(part.key, value: part.value, at: keyPath + [name], in: result) + } + guard try member(name, at: keyPath, in: result) == existing.merging(value) else { + throw MCPConfigEditError.verificationFailed + } + return result + } + + public static func removing(_ name: String, at keyPath: [String], in text: String) throws -> String { + let bytes = Array(text.utf8) + guard let root = try JSONCParser.parse(bytes) else { return text } + let document = Document(bytes: bytes, root: root) + let result = try document.removing(name, at: keyPath) + guard result != text else { return text } + try verify(old: text, new: result, keyPath: keyPath, name: name, expected: nil) + return result + } + + static func walk(_ root: JSONCNode, keyPath: [String]) throws -> JSONCNode? { + guard root.members != nil else { throw MCPConfigEditError.notAnObject([]) } + var container = root + var walked: [String] = [] + for key in keyPath { + walked.append(key) + guard let member = try uniqueMember(key, in: container, path: Array(walked.dropLast())) else { return nil } + guard member.value.members != nil else { throw MCPConfigEditError.notAnObject(walked) } + container = member.value + } + return container + } + + static func uniqueMember(_ key: String, in container: JSONCNode, path: [String]) throws -> JSONCMember? { + let matches = (container.members ?? []).filter { $0.key == key } + guard matches.count <= 1 else { throw MCPConfigEditError.duplicateKey(path + [key]) } + return matches.first + } + + private static func startingDocument(_ name: String, value: JSONValue, at keyPath: [String], after text: String) -> String { + let newline = text.contains("\r\n") ? "\r\n" : "\n" + let style = JSONTextStyle(indentUnit: " ", newline: newline, multiline: true, spaced: true) + let body = style.render(JSONValue.nested(keyPath + [name], leaf: value), indent: "") + newline + guard !text.allSatisfy(\.isWhitespace) else { return body } + let separator = text.utf8.last == 0x0A ? "" : newline + return text + separator + body + } + + private static func verify(old: String, new: String, keyPath: [String], name: String, expected: JSONValue?) throws { + let before = try foundationObject(old) + let after = try foundationObject(new) + let wanted = replacing(name, in: before, at: keyPath, with: expected?.foundationObject) + guard NSDictionary(dictionary: wanted).isEqual(to: after) else { + throw MCPConfigEditError.verificationFailed + } + } + + private static func foundationObject(_ text: String) throws -> [String: Any] { + let bytes = Array(text.utf8) + guard try JSONCParser.parse(bytes) != nil else { return [:] } + let data = Data(JSONCParser.replacingLoneSurrogateEscapes(bytes)) + let object = try? JSONSerialization.jsonObject(with: data, options: [.json5Allowed]) + guard let dictionary = object as? [String: Any] else { throw MCPConfigEditError.invalidSyntax } + return dictionary + } + + private static func replacing(_ name: String, in dictionary: [String: Any], at keyPath: [String], with value: Any?) -> [String: Any] { + var result = dictionary + guard let key = keyPath.first else { + result[name] = value + return result + } + if let child = dictionary[key] as? [String: Any] { + result[key] = replacing(name, in: child, at: Array(keyPath.dropFirst()), with: value) + } else if value != nil { + result[key] = replacing(name, in: [:], at: Array(keyPath.dropFirst()), with: value) + } + return result + } +} + +private struct Document { + let bytes: [UInt8] + let root: JSONCNode + let newline: String + let indentUnit: String + let spaced: Bool + let isMultiline: Bool + + init(bytes: [UInt8], root: JSONCNode) { + self.bytes = bytes + self.root = root + newline = Self.contains(bytes, [0x0D, 0x0A]) ? "\r\n" : "\n" + // An empty root is a fresh file, so it is laid out like a written one rather than kept on one line. + isMultiline = bytes[root.range].contains(0x0A) || root.members?.isEmpty == true + var unit: String? + var spacedSeparator: Bool? + Self.survey(root, bytes: bytes, unit: &unit, spaced: &spacedSeparator) + indentUnit = unit ?? " " + spaced = spacedSeparator ?? true + } + + func upserting(_ name: String, value: JSONValue, at keyPath: [String]) throws -> String { + guard root.members != nil else { throw MCPConfigEditError.notAnObject([]) } + var container = root + for (position, key) in keyPath.enumerated() { + let walked = Array(keyPath.prefix(position)) + guard let member = try JSONCMemberEditor.uniqueMember(key, in: container, path: walked) else { + let rest = Array(keyPath.dropFirst(position + 1)) + [name] + return apply(inserting(key, value: JSONValue.nested(rest, leaf: value), into: container)) + } + guard member.value.members != nil else { throw MCPConfigEditError.notAnObject(walked + [key]) } + container = member.value + } + guard let existing = try JSONCMemberEditor.uniqueMember(name, in: container, path: keyPath) else { + return apply(inserting(name, value: value, into: container)) + } + let style = textStyle(multiline: spansLines(container)) + let rendered = style.render(value, indent: lineIndent(at: existing.keyRange.lowerBound)) + return apply([Splice(range: existing.value.range, text: rendered)]) + } + + func removing(_ name: String, at keyPath: [String]) throws -> String { + guard let container = try JSONCMemberEditor.walk(root, keyPath: keyPath), + let target = try JSONCMemberEditor.uniqueMember(name, in: container, path: keyPath), + let members = container.members, + let position = members.firstIndex(where: { $0.keyRange == target.keyRange }) else { + return utf8Text(bytes) + } + let previous = position > 0 ? members[position - 1] : nil + var splices: [Splice] = [] + let memberEnd = target.commaOffset.map { $0 + 1 } ?? target.value.range.upperBound + if spansLines(container), isFirstOnLine(target.keyRange.lowerBound), let lineEnd = endOfLine(after: memberEnd) { + splices.append(Splice(range: lineStart(of: target.keyRange.lowerBound).. String { + let edited = Array(text.utf8) + guard let root = try? JSONCParser.parse(edited), + let container = try? JSONCMemberEditor.walk(root, keyPath: keyPath), + container.members?.isEmpty == true else { + return text + } + let interior = (container.range.lowerBound + 1)..<(container.range.upperBound - 1) + guard !interior.isEmpty, edited[interior].allSatisfy(Self.isWhitespace) else { return text } + var result = edited + result.removeSubrange(interior) + return utf8Text(result) + } + + private func inserting(_ name: String, value: JSONValue, into container: JSONCNode) -> [Splice] { + let members = container.members ?? [] + let open = container.range.lowerBound + let close = container.range.upperBound - 1 + let multiline = spansLines(container) || (members.isEmpty && isMultiline) + let style = textStyle(multiline: multiline) + let colon = spaced ? ": " : ":" + + guard let last = members.last else { + guard multiline else { + let text = JSONTextStyle.quoted(name) + colon + style.render(value, indent: "") + return [Splice(range: (open + 1).. lineStart(of: open) { + let start = lineStart(of: close) + return [Splice(range: start.. JSONTextStyle { + JSONTextStyle(indentUnit: indentUnit, newline: newline, multiline: multiline, spaced: spaced) + } + + private struct Splice { + let range: Range + let text: String + } + + private func apply(_ splices: [Splice]) -> String { + var result = bytes + for splice in splices.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { + result.replaceSubrange(splice.range, with: Array(splice.text.utf8)) + } + return utf8Text(result) + } + + private func spansLines(_ node: JSONCNode) -> Bool { + bytes[node.range].contains(0x0A) + } + + private func lineStart(of offset: Int) -> Int { + var index = offset + while index > 0, bytes[index - 1] != 0x0A { + index -= 1 + } + return index + } + + private func lineIndent(at offset: Int) -> String { + let start = lineStart(of: offset) + var end = start + while end < bytes.count, bytes[end] == 0x20 || bytes[end] == 0x09 { + end += 1 + } + return utf8Text(bytes[start.. Bool { + bytes[lineStart(of: offset).. Int { + var index = offset + while index < bytes.count, bytes[index] == 0x20 || bytes[index] == 0x09 { + index += 1 + } + return index + } + + // The offset of the line break after `offset`, past spaces and comments on the same line; nil when a token follows. + private func endOfLine(after offset: Int) -> Int? { + var index = offset + while index < bytes.count { + switch bytes[index] { + case 0x20, 0x09: + index += 1 + case 0x0D where index + 1 < bytes.count && bytes[index + 1] == 0x0A: + return index + case 0x0A: + return index + case UInt8(ascii: "/") where index + 1 < bytes.count && bytes[index + 1] == UInt8(ascii: "/"): + while index < bytes.count, bytes[index] != 0x0A { + index += 1 + } + if index > offset, bytes[index - 1] == 0x0D { + return index - 1 + } + return index + case UInt8(ascii: "/") where index + 1 < bytes.count && bytes[index + 1] == UInt8(ascii: "*"): + var end = index + 2 + while end + 1 < bytes.count, !(bytes[end] == UInt8(ascii: "*") && bytes[end + 1] == UInt8(ascii: "/")) { + if bytes[end] == 0x0A { return nil } + end += 1 + } + index = end + 2 + default: + return nil + } + } + return bytes.count + } + + private func afterNewline(_ offset: Int) -> Int { + if offset < bytes.count, bytes[offset] == 0x0D { + return min(offset + 2, bytes.count) + } + return min(offset + 1, bytes.count) + } + + private static func isWhitespace(_ byte: UInt8) -> Bool { + byte == 0x20 || byte == 0x09 || byte == 0x0A || byte == 0x0D + } + + private static func contains(_ bytes: [UInt8], _ pair: [UInt8]) -> Bool { + zip(bytes, bytes.dropFirst()).contains { $0.0 == pair[0] && $0.1 == pair[1] } + } + + // The indent unit is the step from a container's line to its first member's line, from the first container that has one. + private static func survey(_ node: JSONCNode, bytes: [UInt8], unit: inout String?, spaced: inout Bool?) { + switch node.content { + case .object(let members): + if let first = members.first { + if spaced == nil { + spaced = bytes[first.keyRange.upperBound.. String? { + func indent(_ offset: Int) -> (start: Int, text: [UInt8])? { + var start = offset + while start > 0, bytes[start - 1] != 0x0A { + start -= 1 + } + var end = start + while end < offset, bytes[end] == 0x20 || bytes[end] == 0x09 { + end += 1 + } + guard end == offset else { return nil } + return (start, Array(bytes[start.. 0, bytes[openStart - 1] != 0x0A { + openStart -= 1 + } + guard openStart != childIndent.start else { return nil } + var openEnd = openStart + while openEnd < bytes.count, bytes[openEnd] == 0x20 || bytes[openEnd] == 0x09 { + openEnd += 1 + } + let outer = Array(bytes[openStart.. outer.count, childIndent.text.starts(with: outer) else { return nil } + return utf8Text(childIndent.text[outer.count...]) + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONCSyntax.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONCSyntax.swift new file mode 100644 index 0000000000..4b4bc1c2e8 --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONCSyntax.swift @@ -0,0 +1,347 @@ +import Foundation + +public enum MCPConfigEditError: Error, Sendable, Equatable { + case invalidSyntax + case duplicateKey([String]) + case notAnObject([String]) + case unsupportedShape + case verificationFailed +} + +// The editors splice only at ASCII boundaries of text that arrived as a String, so the bytes stay valid UTF-8. +func utf8Text(_ bytes: Bytes) -> String where Bytes.Element == UInt8 { + String(decoding: bytes, as: UTF8.self) // swiftlint:disable:this optional_data_string_conversion +} + +struct JSONCNode { + enum Content { + case object([JSONCMember]) + case array([JSONCNode]) + case scalar(JSONValue) + } + + let content: Content + let range: Range + + var members: [JSONCMember]? { + guard case .object(let members) = content else { return nil } + return members + } + + var value: JSONValue { + switch content { + case .object(let members): return .object(members.map { (key: $0.key, value: $0.value.value) }) + case .array(let items): return .array(items.map(\.value)) + case .scalar(let scalar): return scalar + } + } +} + +struct JSONCMember { + let key: String + let keyRange: Range + let value: JSONCNode + let commaOffset: Int? +} + +// JSON with `//` and `/* */` comments and trailing commas, the dialect VS Code and Zed write. Offsets are UTF-8. +struct JSONCParser { + private let bytes: [UInt8] + private var index = 0 + private var depth = 0 + private static let maximumDepth = 256 + + static func parse(_ bytes: [UInt8]) throws -> JSONCNode? { + var parser = JSONCParser(bytes: bytes) + try parser.skipTrivia() + guard parser.index < bytes.count else { return nil } + let root = try parser.parseValue() + try parser.skipTrivia() + guard parser.index == bytes.count else { throw MCPConfigEditError.invalidSyntax } + return root + } + + // JSONSerialization refuses an unpaired surrogate escape, which Node writes; this parser reads it as U+FFFD, so the check does too. + static func replacingLoneSurrogateEscapes(_ bytes: [UInt8]) -> [UInt8] { + let backslash = UInt8(ascii: "\\") + let replacement = [backslash] + Array("uFFFD".utf8) + var result: [UInt8] = [] + result.reserveCapacity(bytes.count) + var index = 0 + while index < bytes.count { + guard bytes[index] == backslash, index + 1 < bytes.count else { + result.append(bytes[index]) + index += 1 + continue + } + guard bytes[index + 1] == UInt8(ascii: "u"), let unit = hexUnit(bytes, at: index + 2) else { + result.append(contentsOf: bytes[index...(index + 1)]) + index += 2 + continue + } + if (0xD800..<0xDC00).contains(unit), index + 7 < bytes.count, + bytes[index + 6] == backslash, bytes[index + 7] == UInt8(ascii: "u"), + let low = hexUnit(bytes, at: index + 8), (0xDC00..<0xE000).contains(low) { + result.append(contentsOf: bytes[index..<(index + 12)]) + index += 12 + continue + } + if (0xD800..<0xE000).contains(unit) { + result.append(contentsOf: replacement) + } else { + result.append(contentsOf: bytes[index..<(index + 6)]) + } + index += 6 + } + return result + } + + private static func hexUnit(_ bytes: [UInt8], at offset: Int) -> UInt32? { + guard offset + 4 <= bytes.count else { return nil } + return UInt32(utf8Text(bytes[offset..<(offset + 4)]), radix: 16) + } + + private init(bytes: [UInt8]) { + self.bytes = bytes + if bytes.starts(with: [0xEF, 0xBB, 0xBF]) { + index = 3 + } + } + + private var current: UInt8? { + index < bytes.count ? bytes[index] : nil + } + + private mutating func skipTrivia() throws { + while let byte = current { + switch byte { + case 0x20, 0x09, 0x0A, 0x0D: + index += 1 + case UInt8(ascii: "/"): + guard index + 1 < bytes.count else { throw MCPConfigEditError.invalidSyntax } + if bytes[index + 1] == UInt8(ascii: "/") { + while let next = current, next != 0x0A { + index += 1 + } + } else if bytes[index + 1] == UInt8(ascii: "*") { + index += 2 + while true { + guard index + 1 < bytes.count else { throw MCPConfigEditError.invalidSyntax } + if bytes[index] == UInt8(ascii: "*"), bytes[index + 1] == UInt8(ascii: "/") { + index += 2 + break + } + index += 1 + } + } else { + throw MCPConfigEditError.invalidSyntax + } + default: + return + } + } + } + + private mutating func parseValue() throws -> JSONCNode { + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + let start = index + switch byte { + case UInt8(ascii: "{"): + return try nested { try $0.parseObject() } + case UInt8(ascii: "["): + return try nested { try $0.parseArray() } + case UInt8(ascii: "\""): + let string = try parseString() + return JSONCNode(content: .scalar(.string(string)), range: start.. JSONCNode) throws -> JSONCNode { + depth += 1 + defer { depth -= 1 } + guard depth <= Self.maximumDepth else { throw MCPConfigEditError.invalidSyntax } + return try body(&self) + } + + private mutating func parseObject() throws -> JSONCNode { + let start = index + index += 1 + var members: [JSONCMember] = [] + while true { + try skipTrivia() + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + if byte == UInt8(ascii: "}") { + index += 1 + return JSONCNode(content: .object(members), range: start.. JSONCNode { + let start = index + index += 1 + var items: [JSONCNode] = [] + while true { + try skipTrivia() + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + if byte == UInt8(ascii: "]") { + index += 1 + return JSONCNode(content: .array(items), range: start.. Double { + let start = index + if current == UInt8(ascii: "-") { + index += 1 + } + guard let first = current, Self.isDigit(first) else { throw MCPConfigEditError.invalidSyntax } + if first == UInt8(ascii: "0") { + index += 1 + } else { + skipDigits() + } + if current == UInt8(ascii: ".") { + index += 1 + guard let digit = current, Self.isDigit(digit) else { throw MCPConfigEditError.invalidSyntax } + skipDigits() + } + if current == UInt8(ascii: "e") || current == UInt8(ascii: "E") { + index += 1 + if current == UInt8(ascii: "+") || current == UInt8(ascii: "-") { + index += 1 + } + guard let digit = current, Self.isDigit(digit) else { throw MCPConfigEditError.invalidSyntax } + skipDigits() + } + let text = utf8Text(bytes[start.. Bool { + byte >= UInt8(ascii: "0") && byte <= UInt8(ascii: "9") + } + + private mutating func parseString() throws -> String { + index += 1 + var buffer: [UInt8] = [] + while true { + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + switch byte { + case UInt8(ascii: "\""): + index += 1 + return utf8Text(buffer) + case UInt8(ascii: "\\"): + index += 1 + try appendEscape(to: &buffer) + case 0x00..<0x20: + throw MCPConfigEditError.invalidSyntax + default: + buffer.append(byte) + index += 1 + } + } + } + + private mutating func appendEscape(to buffer: inout [UInt8]) throws { + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + index += 1 + switch byte { + case UInt8(ascii: "\""), UInt8(ascii: "\\"), UInt8(ascii: "/"): buffer.append(byte) + case UInt8(ascii: "b"): buffer.append(0x08) + case UInt8(ascii: "f"): buffer.append(0x0C) + case UInt8(ascii: "n"): buffer.append(0x0A) + case UInt8(ascii: "r"): buffer.append(0x0D) + case UInt8(ascii: "t"): buffer.append(0x09) + case UInt8(ascii: "u"): + var scalarValue = try parseHex4() + if (0xD800..<0xDC00).contains(scalarValue), + index + 1 < bytes.count, bytes[index] == UInt8(ascii: "\\"), bytes[index + 1] == UInt8(ascii: "u") { + let saved = index + index += 2 + let low = try parseHex4() + if (0xDC00..<0xE000).contains(low) { + scalarValue = 0x10000 + ((scalarValue - 0xD800) << 10) + (low - 0xDC00) + } else { + index = saved + } + } + let scalar = Unicode.Scalar(scalarValue) ?? "\u{FFFD}" + buffer.append(contentsOf: Array(String(Character(scalar)).utf8)) + default: + throw MCPConfigEditError.invalidSyntax + } + } + + private mutating func parseHex4() throws -> UInt32 { + guard index + 4 <= bytes.count, + let value = UInt32(utf8Text(bytes[index..<(index + 4)]), radix: 16) else { + throw MCPConfigEditError.invalidSyntax + } + index += 4 + return value + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONValue.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONValue.swift new file mode 100644 index 0000000000..011471818f --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/JSONValue.swift @@ -0,0 +1,207 @@ +import Foundation + +public enum JSONValue: Sendable { + case object([(key: String, value: JSONValue)]) + case array([JSONValue]) + case string(String) + case number(Double) + case bool(Bool) + case null + + public subscript(key: String) -> JSONValue? { + guard case .object(let members) = self else { return nil } + return members.first { $0.key == key }?.value + } + + public var stringValue: String? { + guard case .string(let string) = self else { return nil } + return string + } + + public var arrayValue: [JSONValue]? { + guard case .array(let items) = self else { return nil } + return items + } + + public var objectMembers: [(key: String, value: JSONValue)]? { + guard case .object(let members) = self else { return nil } + return members + } + + public var compactText: String { + JSONTextStyle.compact.render(self, indent: "") + } + + public func prettyText(indentUnit: String = " ") -> String { + JSONTextStyle(indentUnit: indentUnit, newline: "\n", multiline: true, spaced: true).render(self, indent: "") + } + + static func nested(_ path: [String], leaf: JSONValue) -> JSONValue { + path.reversed().reduce(leaf) { inner, key in .object([(key: key, value: inner)]) } + } + + // The overlay wins member by member and an object in both merges again, so what the overlay never names stays. + func merging(_ overlay: JSONValue) -> JSONValue { + guard case .object(var members) = self, case .object(let additions) = overlay else { return overlay } + for addition in additions { + if let position = members.firstIndex(where: { $0.key == addition.key }) { + members[position].value = members[position].value.merging(addition.value) + } else { + members.append(addition) + } + } + return .object(members) + } + + var foundationObject: Any { + switch self { + case .object(let members): + var dictionary: [String: Any] = [:] + for member in members where dictionary[member.key] == nil { + dictionary[member.key] = member.value.foundationObject + } + return dictionary + case .array(let items): return items.map(\.foundationObject) + case .string(let string): return string + case .number(let number): return NSNumber(value: number) + case .bool(let bool): return NSNumber(value: bool) + case .null: return NSNull() + } + } +} + +extension JSONValue: Equatable { + // Object members compare as a set, since JSON gives key order no meaning. + public static func == (lhs: JSONValue, rhs: JSONValue) -> Bool { + switch (lhs, rhs) { + case let (.object(left), .object(right)): + guard left.count == right.count else { return false } + return left.allSatisfy { member in + right.contains { $0.key == member.key && $0.value == member.value } + } + case let (.array(left), .array(right)): + return left == right + case let (.string(left), .string(right)): + return left == right + case let (.number(left), .number(right)): + return left == right + case let (.bool(left), .bool(right)): + return left == right + case (.null, .null): + return true + default: + return false + } + } +} + +extension JSONValue: Decodable { + private struct AnyKey: CodingKey { + let stringValue: String + let intValue: Int? = nil + + init(stringValue: String) { + self.stringValue = stringValue + } + + init?(intValue: Int) { + nil + } + } + + // JSONDecoder hands keys back unordered; MCPClientCatalog.decode(_:) parses the bytes itself to keep them. + public init(from decoder: any Decoder) throws { + if let container = try? decoder.container(keyedBy: AnyKey.self) { + self = .object(try container.allKeys.map { key in + (key: key.stringValue, value: try container.decode(JSONValue.self, forKey: key)) + }) + return + } + if var container = try? decoder.unkeyedContainer() { + var items: [JSONValue] = [] + while !container.isAtEnd { + items.append(try container.decode(JSONValue.self)) + } + self = .array(items) + return + } + let container = try decoder.singleValueContainer() + if container.decodeNil() { + self = .null + } else if let bool = try? container.decode(Bool.self) { + self = .bool(bool) + } else if let number = try? container.decode(Double.self) { + self = .number(number) + } else { + self = .string(try container.decode(String.self)) + } + } +} + +struct JSONTextStyle { + var indentUnit: String + var newline: String + var multiline: Bool + var spaced: Bool + + static let compact = JSONTextStyle(indentUnit: "", newline: "", multiline: false, spaced: false) + + func render(_ value: JSONValue, indent: String) -> String { + let inner = multiline ? indent + indentUnit : indent + switch value { + case .object(let members): + guard !members.isEmpty else { return "{}" } + let colon = spaced ? ": " : ":" + return wrap("{", "}", indent: indent, members.map { Self.quoted($0.key) + colon + render($0.value, indent: inner) }) + case .array(let items): + guard !items.isEmpty else { return "[]" } + return wrap("[", "]", indent: indent, items.map { render($0, indent: inner) }) + case .string(let string): + return Self.quoted(string) + case .number(let number): + return Self.numberText(number) + case .bool(let bool): + return bool ? "true" : "false" + case .null: + return "null" + } + } + + private func wrap(_ open: String, _ close: String, indent: String, _ items: [String]) -> String { + guard multiline else { + return open + items.joined(separator: spaced ? ", " : ",") + close + } + let inner = indent + indentUnit + return open + newline + items.map { inner + $0 }.joined(separator: "," + newline) + newline + indent + close + } + + static func quoted(_ string: String) -> String { + var result = "\"" + for scalar in string.unicodeScalars { + switch scalar { + case "\"": result += "\\\"" + case "\\": result += "\\\\" + case "\n": result += "\\n" + case "\r": result += "\\r" + case "\t": result += "\\t" + case "\u{08}": result += "\\b" + case "\u{0C}": result += "\\f" + default: + if scalar.value < 0x20 { + result += String(format: "\\u%04x", scalar.value) + } else { + result.unicodeScalars.append(scalar) + } + } + } + return result + "\"" + } + + static func numberText(_ number: Double) -> String { + guard number.isFinite else { return "null" } + if number == number.rounded(), abs(number) < 1e15 { + return String(Int64(number)) + } + return "\(number)" + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPClientCatalog.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPClientCatalog.swift new file mode 100644 index 0000000000..3f1e9e679f --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPClientCatalog.swift @@ -0,0 +1,347 @@ +import Foundation + +public enum MCPClientPlatform: String, Sendable, CaseIterable { + case macos + case linux +} + +public enum MCPClientCatalogError: Error, Sendable, Equatable { + case unsupportedSchemaVersion(Int) + case invalidField([String]) +} + +public struct MCPClientCatalog: Decodable, Sendable { + public let schemaVersion: Int + public let serverName: String + public let configs: [String: MCPClientConfigSet] + public let clients: [MCPClientDefinition] + + static let supportedSchemaVersion = 1 + + // Parses the bytes itself: JSONDecoder loses the key order the `json` template filter has to keep. + public static func decode(_ data: Data) throws -> MCPClientCatalog { + guard let root = try JSONCParser.parse(Array(data)) else { throw MCPClientCatalogError.invalidField([]) } + return try MCPClientCatalog(json: root.value) + } + + public init(from decoder: any Decoder) throws { + try self.init(json: try JSONValue(from: decoder)) + } + + init(json: JSONValue) throws { + let reader = FieldReader(value: json, path: []) + schemaVersion = try reader.int("schemaVersion") + guard schemaVersion <= Self.supportedSchemaVersion else { + throw MCPClientCatalogError.unsupportedSchemaVersion(schemaVersion) + } + serverName = try reader.string("serverName") + var configs: [String: MCPClientConfigSet] = [:] + for (id, value) in try reader.objectMembers("configs") { + configs[id] = try MCPClientConfigSet(reader: FieldReader(value: value, path: ["configs", id])) + } + self.configs = configs + clients = try reader.array("clients").enumerated().map { position, value in + try MCPClientDefinition(reader: FieldReader(value: value, path: ["clients", String(position)])) + } + } + + public func client(id: String) -> MCPClientDefinition? { + clients.first { $0.id == id } + } + + public func client(matchingClientInfoName name: String) -> MCPClientDefinition? { + clients(matchingClientInfoName: name).first + } + + // ChatGPT and Codex CLI send one clientInfo name, so a session is one of them only when that one alone is detected. + public func client(matchingClientInfoName name: String, detected: Set) -> MCPClientDefinition? { + let candidates = clients(matchingClientInfoName: name) + guard candidates.count > 1 else { return candidates.first } + let found = candidates.filter { detected.contains($0.id) } + return found.count == 1 ? found.first : nil + } + + // Exact names first, then the longest prefix, so "Visual Studio Code - Insiders" is not taken for VS Code. + public func clients(matchingClientInfoName name: String) -> [MCPClientDefinition] { + let lowered = name.lowercased() + let exact = clients.filter { $0.clientInfoNames.contains { $0.lowercased() == lowered } } + guard exact.isEmpty else { return exact } + let lengths = clients.map { client in + client.clientInfoPrefixes.filter { lowered.hasPrefix($0.lowercased()) }.map(\.count).max() ?? 0 + } + guard let longest = lengths.max(), longest > 0 else { return [] } + return zip(clients, lengths).filter { $0.1 == longest }.map(\.0) + } + + public func location(for client: MCPClientDefinition, platform: MCPClientPlatform) -> MCPConfigLocation? { + guard let configID = client.configID else { return nil } + return configs[configID]?.location(for: platform) + } + + public func httpEntry(for client: MCPClientDefinition) -> JSONValue? { + MCPClientPlatform.allCases.lazy + .compactMap { client.spec(for: $0)?.entry } + .first { Self.containsURLPlaceholder($0) } + } + + private static func containsURLPlaceholder(_ value: JSONValue) -> Bool { + switch value { + case .string(let string): return string.contains("{url}") + case .array(let items): return items.contains(where: containsURLPlaceholder) + case .object(let members): return members.contains { containsURLPlaceholder($0.value) } + case .number, .bool, .null: return false + } + } +} + +public struct MCPClientConfigSet: Sendable, Equatable { + public let macos: MCPConfigLocation? + public let linux: MCPConfigLocation? + + public func location(for platform: MCPClientPlatform) -> MCPConfigLocation? { + switch platform { + case .macos: return macos + case .linux: return linux + } + } + + init(reader: FieldReader) throws { + macos = try reader.optional("macos").map(MCPConfigLocation.init(reader:)) + linux = try reader.optional("linux").map(MCPConfigLocation.init(reader:)) + } +} + +public enum MCPConfigFormat: String, Sendable, CaseIterable { + case json + case jsonc + case toml + case yaml +} + +public struct MCPConfigLocation: Sendable, Equatable { + public let path: String + public let format: MCPConfigFormat + public let keyPath: [String] + public let isWritable: Bool + // An older layout of the same file and scope, such as opencode's V1 `mcp.`; read like keyPath, never written. + public let alternateKeyPaths: [[String]] + public let otherScopes: [[String]] + + public init( + path: String, + format: MCPConfigFormat, + keyPath: [String], + isWritable: Bool = true, + alternateKeyPaths: [[String]] = [], + otherScopes: [[String]] = [] + ) { + self.path = path + self.format = format + self.keyPath = keyPath + self.isWritable = isWritable + self.alternateKeyPaths = alternateKeyPaths + self.otherScopes = otherScopes + } + + init(reader: FieldReader) throws { + path = try reader.string("path") + format = try reader.enumeration("format") + keyPath = try reader.strings("keyPath") + isWritable = try reader.optional("writable").map { try $0.bool() } ?? true + alternateKeyPaths = try Self.keyPaths(reader.optional("alternateKeyPaths")) + otherScopes = try Self.keyPaths(reader.optional("otherScopes")) + } + + private static func keyPaths(_ reader: FieldReader?) throws -> [[String]] { + try reader?.elements().map { try $0.stringArray() } ?? [] + } +} + +public struct MCPClientDefinition: Sendable, Equatable, Identifiable { + public let id: String + public let name: String + public let icon: String + public let configID: String? + public let clientInfoNames: [String] + public let clientInfoPrefixes: [String] + public let macos: MCPClientPlatformSpec? + public let linux: MCPClientPlatformSpec? + + public func spec(for platform: MCPClientPlatform) -> MCPClientPlatformSpec? { + switch platform { + case .macos: return macos + case .linux: return linux + } + } + + init(reader: FieldReader) throws { + id = try reader.string("id") + name = try reader.string("name") + icon = try reader.string("icon") + configID = try reader.optional("config").map { try $0.string() } + let clientInfo = reader.optional("clientInfo") + clientInfoNames = try clientInfo?.optional("names").map { try $0.stringArray() } ?? [] + clientInfoPrefixes = try clientInfo?.optional("prefixes").map { try $0.stringArray() } ?? [] + macos = try reader.optional("macos").map(MCPClientPlatformSpec.init(reader:)) + linux = try reader.optional("linux").map(MCPClientPlatformSpec.init(reader:)) + } +} + +public struct MCPClientPlatformSpec: Sendable, Equatable { + public let detect: [MCPClientDetectRule] + public let entry: JSONValue? + public let install: [MCPInstallMethod] + public let applies: MCPClientApplies? + public let unsupported: MCPClientUnsupportedReason? + + init(reader: FieldReader) throws { + detect = try reader.optional("detect")?.elements().map(MCPClientDetectRule.init(reader:)) ?? [] + entry = reader.optional("entry")?.value + install = try reader.optional("install")?.elements().map(MCPInstallMethod.init(reader:)) ?? [] + applies = try reader.optional("applies").map { try $0.enumeration() } + unsupported = try reader.optional("unsupported").map { try $0.enumeration() } + } +} + +public enum MCPClientDetectRule: Sendable, Equatable { + case bundleID(String) + case binary(name: String, paths: [String]) + case path(String) + + init(reader: FieldReader) throws { + if let bundleID = reader.optional("bundleId") { + self = .bundleID(try bundleID.string()) + } else if let binary = reader.optional("binary") { + self = .binary(name: try binary.string(), paths: try reader.optional("paths")?.stringArray() ?? []) + } else if let path = reader.optional("path") { + self = .path(try path.string()) + } else { + throw MCPClientCatalogError.invalidField(reader.path) + } + } +} + +public enum MCPInstallMethod: Sendable, Equatable { + case deeplink(scheme: String, template: String) + case cli(MCPCLIInstall) + case file + + init(reader: FieldReader) throws { + switch try reader.string("kind") { + case "deeplink": + self = .deeplink(scheme: try reader.string("scheme"), template: try reader.string("url")) + case "cli": + self = .cli(MCPCLIInstall( + binary: try reader.string("binary"), + add: try reader.strings("add"), + remove: try reader.optional("remove")?.stringArray(), + update: try reader.optional("update").map { try $0.enumeration() } ?? .add + )) + case "file": + self = .file + default: + throw MCPClientCatalogError.invalidField(reader.path + ["kind"]) + } + } +} + +public struct MCPCLIInstall: Sendable, Equatable { + public let binary: String + public let add: [String] + public let remove: [String]? + public let update: MCPCLIUpdate + + public init(binary: String, add: [String], remove: [String]?, update: MCPCLIUpdate) { + self.binary = binary + self.add = add + self.remove = remove + self.update = update + } +} + +public enum MCPCLIUpdate: String, Sendable { + case add + case removeThenAdd +} + +public enum MCPClientApplies: String, Sendable { + case live + case newSession + case restartApp + case reload +} + +public enum MCPClientUnsupportedReason: String, Sendable { + case remoteOnly + case stdioOnly +} + +struct FieldReader { + let value: JSONValue + let path: [String] + + func optional(_ key: String) -> FieldReader? { + guard let child = value[key], child != .null else { return nil } + return FieldReader(value: child, path: path + [key]) + } + + func field(_ key: String) throws -> FieldReader { + guard let child = optional(key) else { throw MCPClientCatalogError.invalidField(path + [key]) } + return child + } + + func string(_ key: String) throws -> String { + try field(key).string() + } + + func strings(_ key: String) throws -> [String] { + try field(key).stringArray() + } + + func int(_ key: String) throws -> Int { + guard case .number(let number) = try field(key).value, let integer = Int(exactly: number) else { + throw MCPClientCatalogError.invalidField(path + [key]) + } + return integer + } + + func array(_ key: String) throws -> [JSONValue] { + guard let items = try field(key).value.arrayValue else { throw MCPClientCatalogError.invalidField(path + [key]) } + return items + } + + func objectMembers(_ key: String) throws -> [(key: String, value: JSONValue)] { + guard let members = try field(key).value.objectMembers else { throw MCPClientCatalogError.invalidField(path + [key]) } + return members + } + + func enumeration(_ key: String) throws -> Value where Value.RawValue == String { + try field(key).enumeration() + } + + func string() throws -> String { + guard let string = value.stringValue else { throw MCPClientCatalogError.invalidField(path) } + return string + } + + func bool() throws -> Bool { + guard case .bool(let bool) = value else { throw MCPClientCatalogError.invalidField(path) } + return bool + } + + func stringArray() throws -> [String] { + try elements().map { try $0.string() } + } + + func elements() throws -> [FieldReader] { + guard let items = value.arrayValue else { throw MCPClientCatalogError.invalidField(path) } + return items.enumerated().map { FieldReader(value: $1, path: path + [String($0)]) } + } + + func enumeration() throws -> Value where Value.RawValue == String { + guard let raw = value.stringValue, let result = Value(rawValue: raw) else { + throw MCPClientCatalogError.invalidField(path) + } + return result + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPClientStatusEvaluator.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPClientStatusEvaluator.swift new file mode 100644 index 0000000000..3bf7867979 --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPClientStatusEvaluator.swift @@ -0,0 +1,181 @@ +import Foundation + +public enum MCPClientStaleReason: Sendable, Equatable { + case commandMissing + case otherCommand + case otherURL + case otherToken + // The keyPath entry is current, but another scope's entry points elsewhere and wins there; `scope` is the key `*` matched. + case shadowed(scope: String) +} + +public enum MCPClientConfigStatus: Sendable, Equatable { + case notConfigured + case current + case stale(MCPClientStaleReason) + case otherScope + case disabled + // A stdio target was expected, but the entry reaches TablePro over HTTP with a token the user chose. + case usesToken + case unreadable + case unknown +} + +public enum MCPClientStatusEvaluator { + public static func status( + configText: String?, + location: MCPConfigLocation?, + serverName: String, + expected: MCPServerTarget, + fileExists: (String) -> Bool + ) -> MCPClientConfigStatus { + guard let location, location.format != .yaml else { return .unknown } + guard let configText else { return .notConfigured } + let entry: JSONValue? + do { + entry = try primaryEntry(serverName, location: location, text: configText) + } catch { + return .unreadable + } + let scoped = location.otherScopes.flatMap { scope in + scopedEntries(serverName, in: scope, text: configText, format: location.format, fileExists: fileExists) + } + guard let entry else { + return scoped.isEmpty ? .notConfigured : .otherScope + } + let status = evaluate(entry, expected: expected, fileExists: fileExists) + guard status == .current else { return status } + let shadowing = scoped.first { scopedEntry in + if case .stale = evaluate(scopedEntry.entry, expected: expected, fileExists: fileExists) { return true } + return false + } + return shadowing.map { .stale(.shadowed(scope: $0.scope)) } ?? .current + } + + private static func evaluate(_ entry: JSONValue, expected: MCPServerTarget, fileExists: (String) -> Bool) -> MCPClientConfigStatus { + // Turned off is the user's choice whatever the entry points at, so it is never offered an Update. + guard !isTurnedOff(entry) else { return .disabled } + switch expected { + case .stdio(let command): + guard let configured = commandValue(entry) else { + return urlValue(entry) == nil ? .stale(.otherCommand) : .usesToken + } + guard configured == command else { + return fileExists(configured) ? .stale(.otherCommand) : .stale(.commandMissing) + } + case let .http(url, authorization): + guard let configured = urlValue(entry) else { + return commandValue(entry) == nil ? .stale(.otherURL) : .stale(.otherCommand) + } + guard sameEndpoint(configured, url) else { return .stale(.otherURL) } + guard let header = authorizationValue(entry), + header.trimmingCharacters(in: .whitespaces) == authorization.trimmingCharacters(in: .whitespaces) else { + return .stale(.otherToken) + } + } + return .current + } + + private static func isTurnedOff(_ entry: JSONValue) -> Bool { + entry["disabled"] == .bool(true) || entry["enabled"] == .bool(false) + } + + private static func primaryEntry(_ name: String, location: MCPConfigLocation, text: String) throws -> JSONValue? { + for keyPath in [location.keyPath] + location.alternateKeyPaths { + if let entry = try member(name, at: keyPath, in: text, format: location.format) { + return entry + } + } + return nil + } + + private static func member(_ name: String, at keyPath: [String], in text: String, format: MCPConfigFormat) throws -> JSONValue? { + switch format { + case .json, .jsonc: return try JSONCMemberEditor.member(name, at: keyPath, in: text) + case .toml: return try TOMLTableEditor.member(name, at: keyPath, in: text) + case .yaml: return nil + } + } + + // Another scope is someone else's layout, so an odd shape there is skipped rather than making the file unreadable. + private static func scopedEntries( + _ name: String, + in scope: [String], + text: String, + format: MCPConfigFormat, + fileExists: (String) -> Bool + ) -> [(scope: String, entry: JSONValue)] { + let label = scope.joined(separator: ".") + guard format == .json || format == .jsonc else { + guard !scope.contains("*"), let entry = try? member(name, at: scope, in: text, format: format) else { return [] } + return [(scope: label, entry: entry)] + } + guard let root = try? JSONCParser.parse(Array(text.utf8))?.value else { return [] } + var candidates: [(scope: String, value: JSONValue)] = [(scope: label, value: root)] + for key in scope { + candidates = candidates.flatMap { candidate -> [(scope: String, value: JSONValue)] in + if key == "*" { + return (candidate.value.objectMembers ?? []) + .filter { !isGoneFolder($0.key, fileExists: fileExists) } + .map { (scope: $0.key, value: $0.value) } + } + return candidate.value[key].map { [(scope: candidate.scope, value: $0)] } ?? [] + } + } + return candidates.compactMap { candidate in + candidate.value[name].map { (scope: candidate.scope, entry: $0) } + } + } + + // Claude Code keeps a project for every folder it ever opened, so one deleted since says nothing about today. + private static func isGoneFolder(_ key: String, fileExists: (String) -> Bool) -> Bool { + key.hasPrefix("/") && !fileExists(key) + } + + private static func commandValue(_ entry: JSONValue) -> String? { + for key in MCPEntryUpdate.commandKeys { + switch entry[key] { + case .string(let command)?: return command + case .array(let parts)?: return parts.first?.stringValue + default: continue + } + } + return nil + } + + private static func urlValue(_ entry: JSONValue) -> String? { + MCPEntryUpdate.urlKeys.lazy.compactMap { entry[$0]?.stringValue }.first + } + + private static func authorizationValue(_ entry: JSONValue) -> String? { + for key in ["headers", "http_headers"] { + if let header = entry[key]?.objectMembers?.first(where: { $0.key.lowercased() == "authorization" }) { + return header.value.stringValue + } + } + return nil + } + + private static let loopbackHosts: Set = ["localhost", "127.0.0.1", "::1", "[::1]"] + + private static func sameEndpoint(_ configured: String, _ expected: String) -> Bool { + guard let left = URLComponents(string: configured), let right = URLComponents(string: expected), + let leftScheme = left.scheme?.lowercased(), let rightScheme = right.scheme?.lowercased() else { + return configured == expected + } + let leftHost = left.host?.lowercased() ?? "" + let rightHost = right.host?.lowercased() ?? "" + let sameHost = leftHost == rightHost || (loopbackHosts.contains(leftHost) && loopbackHosts.contains(rightHost)) + return leftScheme == rightScheme && sameHost + && port(left, scheme: leftScheme) == port(right, scheme: rightScheme) + && trimmedPath(left.path) == trimmedPath(right.path) + } + + private static func port(_ components: URLComponents, scheme: String) -> Int? { + components.port ?? (scheme == "https" ? 443 : scheme == "http" ? 80 : nil) + } + + private static func trimmedPath(_ path: String) -> String { + path.hasSuffix("/") ? String(path.dropLast()) : path + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPConfigFileWriter.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPConfigFileWriter.swift new file mode 100644 index 0000000000..33120f0767 --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPConfigFileWriter.swift @@ -0,0 +1,126 @@ +import Foundation + +public struct MCPConfigWriteResult: Sendable, Equatable { + public let backupURL: URL? + public let created: Bool + + public init(backupURL: URL?, created: Bool) { + self.backupURL = backupURL + self.created = created + } +} + +public enum MCPConfigWriteError: Error, Sendable, Equatable { + case changedDuringWrite + case verificationFailed + case io(String) +} + +// FileManager is documented as safe across threads when it has no delegate, and this one never gets one. +public struct MCPConfigFileWriter: @unchecked Sendable { + public static let backupSuffix = ".tablepro-backup" + + private let fileManager: FileManager + + public init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + // `Data.write(.atomic)` would turn a symlinked config into a regular file, so the link is resolved and its + // target replaced; replaceItemAt keeps the target's mode and leaves the previous bytes beside it as the backup. + public func update(_ url: URL, transform: (String?) throws -> String) throws -> MCPConfigWriteResult { + let target = try resolvedTarget(url) + var snapshot = try read(target) + for _ in 0..<2 { + let newData = Data(try transform(try snapshot.map(decoded)).utf8) + if newData == snapshot { + return MCPConfigWriteResult(backupURL: nil, created: false) + } + let latest = try read(target) + guard latest == snapshot else { + snapshot = latest + continue + } + let result = snapshot == nil ? try create(newData, at: target) : try replace(target, with: newData) + guard try read(target) == newData else { throw MCPConfigWriteError.verificationFailed } + return result + } + throw MCPConfigWriteError.changedDuringWrite + } + + private func resolvedTarget(_ url: URL) throws -> URL { + var current = url.standardizedFileURL + for _ in 0..<32 { + guard let destination = try? fileManager.destinationOfSymbolicLink(atPath: current.path) else { + return current + } + let next = destination.hasPrefix("/") + ? URL(fileURLWithPath: destination) + : current.deletingLastPathComponent().appendingPathComponent(destination) + current = next.standardizedFileURL + } + throw MCPConfigWriteError.io("symlinkLoop") + } + + private func read(_ url: URL) throws -> Data? { + do { + return try Data(contentsOf: url) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { + return nil + } catch { + throw Self.ioError(error) + } + } + + private func decoded(_ data: Data) throws -> String { + guard let text = String(data: data, encoding: .utf8) else { throw MCPConfigWriteError.io("notUTF8") } + return text + } + + private func replace(_ target: URL, with data: Data) throws -> MCPConfigWriteResult { + let backupName = target.lastPathComponent + Self.backupSuffix + do { + let directory = try fileManager.url( + for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: target, create: true + ) + defer { try? fileManager.removeItem(at: directory) } + let temporary = directory.appendingPathComponent(target.lastPathComponent) + try data.write(to: temporary) + _ = try fileManager.replaceItemAt( + target, withItemAt: temporary, backupItemName: backupName, options: [.withoutDeletingBackupItem] + ) + } catch { + throw Self.ioError(error) + } + return MCPConfigWriteResult(backupURL: target.deletingLastPathComponent().appendingPathComponent(backupName), created: false) + } + + // Client configs often hold env secrets, so a new one starts at 0600. + private func create(_ data: Data, at target: URL) throws -> MCPConfigWriteResult { + let parent = target.deletingLastPathComponent() + do { + try fileManager.createDirectory(at: parent, withIntermediateDirectories: true) + let directory = try fileManager.url( + for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: parent, create: true + ) + defer { try? fileManager.removeItem(at: directory) } + let temporary = directory.appendingPathComponent(target.lastPathComponent) + guard fileManager.createFile(atPath: temporary.path, contents: data, attributes: [.posixPermissions: 0o600]) else { + throw MCPConfigWriteError.io("createFailed") + } + try fileManager.moveItem(at: temporary, to: target) + } catch let error as CocoaError where error.code == .fileWriteFileExists { + throw MCPConfigWriteError.changedDuringWrite + } catch let error as MCPConfigWriteError { + throw error + } catch { + throw Self.ioError(error) + } + return MCPConfigWriteResult(backupURL: nil, created: true) + } + + private static func ioError(_ error: any Error) -> MCPConfigWriteError { + let nsError = error as NSError + return .io("\(nsError.localizedDescription) (\(nsError.domain) \(nsError.code))") + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPEntryUpdate.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPEntryUpdate.swift new file mode 100644 index 0000000000..505780c841 --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPEntryUpdate.swift @@ -0,0 +1,89 @@ +import Foundation + +// Update rewrites only how an entry reaches TablePro; other catalog members are added only when missing, never widening a user's limit. +enum MCPEntryUpdate { + static let commandKeys = ["command", "cmd"] + static let urlKeys = ["url", "serverUrl", "httpUrl", "uri"] + + private static let alwaysWritten: Set = ["type", "args"] + private static let placeholders: Set = ["command", "url", "authorization", "name"] + + private enum Transport { + case command + case url + } + + enum Plan: Equatable { + case replace(JSONValue) + case merge(JSONValue) + } + + static func plan(existing: JSONValue?, entry: JSONValue, template: JSONValue) -> Plan { + guard let existing, case .object(let current) = existing, case .object(let wanted) = entry else { return .replace(entry) } + if let had = transport(of: existing), let have = transport(of: entry), had != have { + // A merge would leave the old transport's members behind; the user's choices still carry over. + return .replace(.object(wanted.map { part in + guard !alwaysWritten.contains(part.key), !holdsPlaceholder(template[part.key]), + let mine = existing[part.key] else { return part } + return (key: part.key, value: mine) + })) + } + return .merge(.object(overlay(current, with: wanted, template: template, alwaysWritten: alwaysWritten))) + } + + private static func overlay( + _ current: [(key: String, value: JSONValue)], + with wanted: [(key: String, value: JSONValue)], + template: JSONValue?, + alwaysWritten: Set + ) -> [(key: String, value: JSONValue)] { + var members = current + for part in wanted { + guard let position = members.firstIndex(where: { $0.key == part.key }) else { + members.append(part) + continue + } + let partTemplate = template?[part.key] + if alwaysWritten.contains(part.key) { + members[position].value = part.value + } else if holdsPlaceholder(partTemplate) { + if case .object(let inner) = members[position].value, case .object(let innerWanted) = part.value { + members[position].value = .object(overlay(inner, with: innerWanted, template: partTemplate, alwaysWritten: [])) + } else { + members[position].value = part.value + } + } + } + return members + } + + private static func transport(of entry: JSONValue) -> Transport? { + if commandKeys.contains(where: { entry[$0] != nil }) { return .command } + if urlKeys.contains(where: { entry[$0] != nil }) { return .url } + return nil + } + + static func holdsPlaceholder(_ template: JSONValue?) -> Bool { + switch template { + case .string(let text)?: + return placeholderNames(in: text).contains { placeholders.contains($0) } + case .array(let items)?: + return items.contains { holdsPlaceholder($0) } + case .object(let members)?: + return members.contains { holdsPlaceholder($0.value) } + default: + return false + } + } + + private static func placeholderNames(in text: String) -> [String] { + var names: [String] = [] + var rest = Substring(text) + while let open = rest.firstIndex(of: "{"), let close = rest[open...].firstIndex(of: "}") { + let expression = rest[rest.index(after: open).. String { + var result = "" + var rest = Substring(path) + while let open = rest.range(of: "${"), let close = rest[open.upperBound...].firstIndex(of: "}") { + result += rest[.. String { + let trimmedHome = home.count > 1 && home.hasSuffix("/") ? String(home.dropLast()) : home + if path == "~" { + return trimmedHome + } + if path.hasPrefix("~/") { + return trimmedHome + path.dropFirst() + } + return path + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPTemplateRenderer.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPTemplateRenderer.swift new file mode 100644 index 0000000000..5b7530cebe --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/MCPTemplateRenderer.swift @@ -0,0 +1,173 @@ +import Foundation + +public enum MCPServerTarget: Sendable, Equatable { + case stdio(command: String) + case http(url: String, authorization: String) +} + +public enum MCPTemplateError: Error, Sendable, Equatable { + case missingEntry + case unknownPlaceholder(String) + case unavailablePlaceholder(String) + case unknownFilter(String) + case invalidURL +} + +public struct MCPTemplateRenderer: Sendable { + public let serverName: String + public let target: MCPServerTarget + + public init(serverName: String, target: MCPServerTarget) { + self.serverName = serverName + self.target = target + } + + public func entry(_ spec: MCPClientPlatformSpec) throws -> JSONValue { + guard let template = spec.entry else { throw MCPTemplateError.missingEntry } + return try entry(template: template) + } + + public func entry(template: JSONValue) throws -> JSONValue { + switch template { + case .string(let string): + return .string(try render(string, entry: nil)) + case .array(let items): + return .array(try items.map { try entry(template: $0) }) + case .object(let members): + return .object(try members.map { (key: $0.key, value: try entry(template: $0.value)) }) + case .number, .bool, .null: + return template + } + } + + public func arguments(_ template: [String], entry: JSONValue) throws -> [String] { + try template.map { try render($0, entry: entry) } + } + + public func url(_ template: String, entry: JSONValue) throws -> URL { + guard let url = URL(string: try render(template, entry: entry)) else { throw MCPTemplateError.invalidURL } + return url + } + + public func snippet(for location: MCPConfigLocation?, entry: JSONValue) -> String { + let path = (location?.keyPath ?? []) + [serverName] + let json = JSONValue.nested(path, leaf: entry).prettyText() + switch location?.format { + case .toml: + guard let block = try? TOMLTableEditor.renderBlock(header: path, value: entry, newline: "\n") else { return json } + return String(block.dropLast()) + case .yaml: + return Self.yamlLines(key: path[0], value: JSONValue.nested(Array(path.dropFirst()), leaf: entry), indent: "") + .joined(separator: "\n") + case .json, .jsonc, nil: + return json + } + } + + public func commandLine(binary: String, arguments: [String]) -> String { + ([binary] + arguments).map(Self.shellQuoted).joined(separator: " ") + } + + static func shellQuoted(_ word: String) -> String { + guard !word.isEmpty else { return "''" } + if word.unicodeScalars.allSatisfy(Self.shellSafe.contains) { + return word + } + return "'" + word.replacingOccurrences(of: "'", with: "'\\''", options: .literal) + "'" + } + + private static let shellSafe = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@%+=:,./-" + ) + + private static let uriUnreserved = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" + ) + + private enum Rendered { + case text(String) + case json(JSONValue) + } + + private func render(_ template: String, entry: JSONValue?) throws -> String { + var result = "" + var rest = Substring(template) + while let open = rest.firstIndex(of: "{"), let close = rest[open...].firstIndex(of: "}") { + result += rest[.. String { + let parts = expression.split(separator: "|", omittingEmptySubsequences: false).map(String.init) + var value = try source(parts[0], entry: entry) + for filter in parts.dropFirst() { + value = try apply(filter, to: value) + } + switch value { + case .text(let text): return text + case .json(let json): return json.compactText + } + } + + private func source(_ name: String, entry: JSONValue?) throws -> Rendered { + switch (name, target) { + case ("name", _): + return .text(serverName) + case let ("command", .stdio(command)): + return .text(command) + case let ("url", .http(url, _)): + return .text(url) + case let ("authorization", .http(_, authorization)): + return .text(authorization) + case ("command", _), ("url", _), ("authorization", _): + throw MCPTemplateError.unavailablePlaceholder(name) + case ("entry", _): + guard let entry else { throw MCPTemplateError.unavailablePlaceholder(name) } + return .json(entry) + case ("entryWithName", _): + guard let entry else { throw MCPTemplateError.unavailablePlaceholder(name) } + let others = entry.objectMembers?.filter { $0.key != "name" } ?? [] + return .json(.object([(key: "name", value: .string(serverName))] + others)) + default: + throw MCPTemplateError.unknownPlaceholder(name) + } + } + + private func apply(_ filter: String, to value: Rendered) throws -> Rendered { + switch (filter, value) { + case let ("json", .json(json)): + return .text(json.compactText) + case let ("json", .text(text)): + return .text(JSONTextStyle.quoted(text)) + case let ("base64", .text(text)): + return .text(Data(text.utf8).base64EncodedString()) + case let ("uri", .text(text)): + return .text(text.addingPercentEncoding(withAllowedCharacters: Self.uriUnreserved) ?? text) + default: + throw MCPTemplateError.unknownFilter(filter) + } + } + + private static func yamlLines(key: String, value: JSONValue, indent: String) -> [String] { + let label = indent + yamlKey(key) + ":" + switch value { + case .object(let members) where !members.isEmpty: + return [label] + members.flatMap { yamlLines(key: $0.key, value: $0.value, indent: indent + " ") } + case .array(let items) where !items.isEmpty: + return [label] + items.map { indent + " - " + yamlFlow.render($0, indent: "") } + default: + return [label + " " + yamlFlow.render(value, indent: "")] + } + } + + // A JSON scalar or flow collection is also valid YAML. + private static let yamlFlow = JSONTextStyle(indentUnit: "", newline: "", multiline: false, spaced: true) + + private static func yamlKey(_ key: String) -> String { + guard !key.isEmpty, key.utf8.allSatisfy(TOMLParser.isBareKeyByte) else { return JSONTextStyle.quoted(key) } + return key + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/TOMLSyntax.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/TOMLSyntax.swift new file mode 100644 index 0000000000..ff1008e9d8 --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/TOMLSyntax.swift @@ -0,0 +1,461 @@ +import Foundation + +struct TOMLStatement { + enum Kind { + case table(keys: [String], isArray: Bool) + case keyValue(keys: [String], value: JSONValue) + } + + let kind: Kind + let lineStart: Int + // Past the line break that ends the statement, or the end of the text. + let lineEnd: Int +} + +// Enough of TOML 1.0 to find every statement's keys and line range and to read the values a server table holds. +// Dates and times come back as their source text. +struct TOMLParser { + private let bytes: [UInt8] + private var index = 0 + private var depth = 0 + + static func parse(_ bytes: [UInt8]) throws -> [TOMLStatement] { + var parser = TOMLParser(bytes: bytes) + return try parser.statements() + } + + private init(bytes: [UInt8]) { + self.bytes = bytes + if bytes.starts(with: [0xEF, 0xBB, 0xBF]) { + index = 3 + } + } + + private var current: UInt8? { + index < bytes.count ? bytes[index] : nil + } + + private func byte(at offset: Int) -> UInt8? { + offset < bytes.count ? bytes[offset] : nil + } + + private mutating func statements() throws -> [TOMLStatement] { + var result: [TOMLStatement] = [] + while true { + skipBlankLinesAndComments() + guard let byte = current else { return result } + let start = index + var lineStart = start + while lineStart > 0, bytes[lineStart - 1] != 0x0A { + lineStart -= 1 + } + let kind: TOMLStatement.Kind + if byte == UInt8(ascii: "[") { + let isArray = self.byte(at: index + 1) == UInt8(ascii: "[") + index += isArray ? 2 : 1 + skipSpaces() + let keys = try parseKey() + try expect("]") + if isArray { + try expect("]") + } + kind = .table(keys: keys, isArray: isArray) + } else { + let keys = try parseKey() + try expect("=") + skipSpaces() + kind = .keyValue(keys: keys, value: try parseValue()) + } + skipSpaces() + skipComment() + switch current { + case nil: + break + case 0x0A: + index += 1 + case 0x0D where self.byte(at: index + 1) == 0x0A: + index += 2 + default: + throw MCPConfigEditError.invalidSyntax + } + result.append(TOMLStatement(kind: kind, lineStart: lineStart, lineEnd: index)) + } + } + + private mutating func skipSpaces() { + while let byte = current, byte == 0x20 || byte == 0x09 { + index += 1 + } + } + + private mutating func skipComment() { + guard current == UInt8(ascii: "#") else { return } + while let byte = current, byte != 0x0A { + index += 1 + } + if index > 0, bytes[index - 1] == 0x0D { + index -= 1 + } + } + + private mutating func skipBlankLinesAndComments() { + while let byte = current { + switch byte { + case 0x20, 0x09, 0x0A, 0x0D: + index += 1 + case UInt8(ascii: "#"): + while let next = current, next != 0x0A { + index += 1 + } + default: + return + } + } + } + + private mutating func expect(_ character: Character) throws { + skipSpaces() + guard let ascii = character.asciiValue, current == ascii else { throw MCPConfigEditError.invalidSyntax } + index += 1 + } + + private mutating func parseKey() throws -> [String] { + var keys: [String] = [] + while true { + skipSpaces() + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + switch byte { + case UInt8(ascii: "\""): + keys.append(try parseBasicString()) + case UInt8(ascii: "'"): + keys.append(try parseLiteralString()) + default: + let start = index + while let next = current, Self.isBareKeyByte(next) { + index += 1 + } + guard index > start else { throw MCPConfigEditError.invalidSyntax } + keys.append(utf8Text(bytes[start.. Bool { + switch byte { + case UInt8(ascii: "A")...UInt8(ascii: "Z"), UInt8(ascii: "a")...UInt8(ascii: "z"), + UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "_"), UInt8(ascii: "-"): + return true + default: + return false + } + } + + private mutating func parseValue() throws -> JSONValue { + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + switch byte { + case UInt8(ascii: "\""): + if self.byte(at: index + 1) == UInt8(ascii: "\""), self.byte(at: index + 2) == UInt8(ascii: "\"") { + return .string(try parseMultilineBasicString()) + } + return .string(try parseBasicString()) + case UInt8(ascii: "'"): + if self.byte(at: index + 1) == UInt8(ascii: "'"), self.byte(at: index + 2) == UInt8(ascii: "'") { + return .string(try parseMultilineLiteralString()) + } + return .string(try parseLiteralString()) + case UInt8(ascii: "["): + return try nested { try $0.parseArray() } + case UInt8(ascii: "{"): + return try nested { try $0.parseInlineTable() } + default: + return try parseBareValue() + } + } + + private mutating func nested(_ body: (inout TOMLParser) throws -> JSONValue) throws -> JSONValue { + depth += 1 + defer { depth -= 1 } + guard depth <= 128 else { throw MCPConfigEditError.invalidSyntax } + return try body(&self) + } + + private mutating func skipValueTrivia() { + while let byte = current { + switch byte { + case 0x20, 0x09, 0x0A, 0x0D: + index += 1 + case UInt8(ascii: "#"): + while let next = current, next != 0x0A { + index += 1 + } + default: + return + } + } + } + + private mutating func parseArray() throws -> JSONValue { + index += 1 + var items: [JSONValue] = [] + while true { + skipValueTrivia() + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + if byte == UInt8(ascii: "]") { + index += 1 + return .array(items) + } + items.append(try parseValue()) + skipValueTrivia() + switch current { + case UInt8(ascii: ","): + index += 1 + case UInt8(ascii: "]"): + index += 1 + return .array(items) + default: + throw MCPConfigEditError.invalidSyntax + } + } + } + + private mutating func parseInlineTable() throws -> JSONValue { + index += 1 + var members: [(key: String, value: JSONValue)] = [] + while true { + skipValueTrivia() + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + if byte == UInt8(ascii: "}") { + index += 1 + return .object(members) + } + let keys = try parseKey() + try expect("=") + skipSpaces() + let value = try parseValue() + try TOMLTree.insert(value, at: keys, into: &members) + skipValueTrivia() + switch current { + case UInt8(ascii: ","): + index += 1 + case UInt8(ascii: "}"): + index += 1 + return .object(members) + default: + throw MCPConfigEditError.invalidSyntax + } + } + } + + private mutating func parseBareValue() throws -> JSONValue { + let start = index + while let byte = current, !Self.endsBareValue(byte) { + index += 1 + } + // A local date and a time may be separated by one space. + if index - start == 10, current == 0x20, let next = self.byte(at: index + 1), Self.isDigit(next), + bytes[start + 4] == UInt8(ascii: "-") { + index += 1 + while let byte = current, !Self.endsBareValue(byte) { + index += 1 + } + } + let text = utf8Text(bytes[start.. Double? { + let cleaned = text.replacingOccurrences(of: "_", with: "") + guard !cleaned.isEmpty, !text.hasPrefix("_"), !text.hasSuffix("_"), !text.contains("__") else { return nil } + for (prefix, radix) in [("0x", 16), ("0o", 8), ("0b", 2)] where cleaned.hasPrefix(prefix) { + return Int64(cleaned.dropFirst(2), radix: radix).map(Double.init) + } + let allowed = Set("0123456789+-.eE") + guard cleaned.allSatisfy({ allowed.contains($0) }), cleaned.contains(where: \.isNumber) else { return nil } + return Double(cleaned) + } + + private static func endsBareValue(_ byte: UInt8) -> Bool { + switch byte { + case 0x20, 0x09, 0x0A, 0x0D, UInt8(ascii: ","), UInt8(ascii: "]"), UInt8(ascii: "}"), UInt8(ascii: "#"): + return true + default: + return false + } + } + + private static func isDigit(_ byte: UInt8) -> Bool { + byte >= UInt8(ascii: "0") && byte <= UInt8(ascii: "9") + } + + private mutating func parseBasicString() throws -> String { + index += 1 + var buffer: [UInt8] = [] + while true { + guard let byte = current, byte != 0x0A else { throw MCPConfigEditError.invalidSyntax } + switch byte { + case UInt8(ascii: "\""): + index += 1 + return utf8Text(buffer) + case UInt8(ascii: "\\"): + index += 1 + try appendEscape(to: &buffer) + default: + buffer.append(byte) + index += 1 + } + } + } + + private mutating func parseMultilineBasicString() throws -> String { + index += 3 + skipLeadingNewline() + var buffer: [UInt8] = [] + while true { + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + if byte == UInt8(ascii: "\""), closesMultiline(UInt8(ascii: "\"")) { + return finishMultiline(buffer, quote: UInt8(ascii: "\"")) + } + if byte == UInt8(ascii: "\\") { + index += 1 + if let whitespaceEnd = lineEndingBackslashEnd() { + index = whitespaceEnd + } else { + try appendEscape(to: &buffer) + } + continue + } + buffer.append(byte) + index += 1 + } + } + + private mutating func parseLiteralString() throws -> String { + index += 1 + let start = index + while let byte = current, byte != UInt8(ascii: "'") { + guard byte != 0x0A else { throw MCPConfigEditError.invalidSyntax } + index += 1 + } + guard current != nil else { throw MCPConfigEditError.invalidSyntax } + let text = utf8Text(bytes[start.. String { + index += 3 + skipLeadingNewline() + var buffer: [UInt8] = [] + while true { + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + if byte == UInt8(ascii: "'"), closesMultiline(UInt8(ascii: "'")) { + return finishMultiline(buffer, quote: UInt8(ascii: "'")) + } + buffer.append(byte) + index += 1 + } + } + + private mutating func skipLeadingNewline() { + if current == 0x0A { + index += 1 + } else if current == 0x0D, byte(at: index + 1) == 0x0A { + index += 2 + } + } + + private func closesMultiline(_ quote: UInt8) -> Bool { + byte(at: index + 1) == quote && byte(at: index + 2) == quote + } + + // Up to two quotes may sit right before the closing three. + private mutating func finishMultiline(_ buffer: [UInt8], quote: UInt8) -> String { + var run = 0 + while byte(at: index + run) == quote { + run += 1 + } + let extra = min(max(run - 3, 0), 2) + index += extra + 3 + return utf8Text(buffer + Array(repeating: quote, count: extra)) + } + + private func lineEndingBackslashEnd() -> Int? { + var offset = index + while let next = byte(at: offset), next == 0x20 || next == 0x09 { + offset += 1 + } + guard byte(at: offset) == 0x0A || (byte(at: offset) == 0x0D && byte(at: offset + 1) == 0x0A) else { return nil } + while let next = byte(at: offset), next == 0x20 || next == 0x09 || next == 0x0A || next == 0x0D { + offset += 1 + } + return offset + } + + private mutating func appendEscape(to buffer: inout [UInt8]) throws { + guard let byte = current else { throw MCPConfigEditError.invalidSyntax } + index += 1 + switch byte { + case UInt8(ascii: "\""), UInt8(ascii: "\\"): buffer.append(byte) + case UInt8(ascii: "b"): buffer.append(0x08) + case UInt8(ascii: "t"): buffer.append(0x09) + case UInt8(ascii: "n"): buffer.append(0x0A) + case UInt8(ascii: "f"): buffer.append(0x0C) + case UInt8(ascii: "r"): buffer.append(0x0D) + case UInt8(ascii: "e"): buffer.append(0x1B) + case UInt8(ascii: "x"): try appendScalar(hexDigits: 2, to: &buffer) + case UInt8(ascii: "u"): try appendScalar(hexDigits: 4, to: &buffer) + case UInt8(ascii: "U"): try appendScalar(hexDigits: 8, to: &buffer) + default: throw MCPConfigEditError.invalidSyntax + } + } + + private mutating func appendScalar(hexDigits: Int, to buffer: inout [UInt8]) throws { + guard index + hexDigits <= bytes.count, + let value = UInt32(utf8Text(bytes[index..<(index + hexDigits)]), radix: 16), + let scalar = Unicode.Scalar(value) else { + throw MCPConfigEditError.invalidSyntax + } + index += hexDigits + buffer.append(contentsOf: Array(String(Character(scalar)).utf8)) + } +} + +enum TOMLTree { + static func insert(_ value: JSONValue, at keys: [String], into members: inout [(key: String, value: JSONValue)]) throws { + guard let key = keys.first else { throw MCPConfigEditError.invalidSyntax } + let position = members.firstIndex { $0.key == key } + guard keys.count > 1 else { + guard position == nil else { throw MCPConfigEditError.duplicateKey(keys) } + members.append((key: key, value: value)) + return + } + var children: [(key: String, value: JSONValue)] = [] + if let position { + guard case .object(let existing) = members[position].value else { throw MCPConfigEditError.invalidSyntax } + children = existing + } + try insert(value, at: Array(keys.dropFirst()), into: &children) + if let position { + members[position].value = .object(children) + } else { + members.append((key: key, value: .object(children))) + } + } +} diff --git a/apple/Packages/TableProMacCore/Sources/TableProMCPClients/TOMLTableEditor.swift b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/TOMLTableEditor.swift new file mode 100644 index 0000000000..7d1d3f3fc3 --- /dev/null +++ b/apple/Packages/TableProMacCore/Sources/TableProMCPClients/TOMLTableEditor.swift @@ -0,0 +1,347 @@ +import Foundation + +// Reads and splices one `[.]` table (and its subtables) of a TOML file such as Codex's config.toml. +// A server defined any other way is refused, since rewriting it would mean rewriting someone else's layout. +public enum TOMLTableEditor { + public static func member(_ name: String, at keyPath: [String], in text: String) throws -> JSONValue? { + let file = try File(text: text, target: keyPath + [name]) + guard file.layout.table != nil || !file.layout.subtables.isEmpty else { return nil } + return try file.serverValue() + } + + public static func upserting(_ name: String, value: JSONValue, at keyPath: [String], in text: String) throws -> String { + let target = keyPath + [name] + let file = try File(text: text, target: target) + guard !file.layout.containerIsValue else { throw MCPConfigEditError.unsupportedShape } + let block = try renderBlock(header: target, value: value, newline: file.newline) + + var splices: [(range: Range, text: String)] = file.layout.subtables.map { (range: file.removalRange(of: $0), text: "") } + if let table = file.layout.table { + let range = file.blockRange(of: table) + let endsWithoutNewline = range.upperBound == file.bytes.count && file.bytes.last != 0x0A + splices.append((range: range, text: endsWithoutNewline ? String(block.dropLast()) : block)) + } + var result = file.applying(splices) + if file.layout.table == nil { + result = appending(block, to: result, newline: file.newline) + } + guard try member(name, at: keyPath, in: result) == value else { throw MCPConfigEditError.verificationFailed } + return result + } + + // Update: `entry` is rendered from `template`, which says which keys are TablePro's to rewrite (MCPEntryUpdate). + public static func updating( + _ name: String, + entry: JSONValue, + template: JSONValue, + at keyPath: [String], + in text: String + ) throws -> String { + switch MCPEntryUpdate.plan(existing: try member(name, at: keyPath, in: text), entry: entry, template: template) { + case .replace(let value): try upserting(name, value: value, at: keyPath, in: text) + case .merge(let value): try merging(name, value: value, at: keyPath, in: text) + } + } + + // Rewrites only the keys `value` names, so the user's other keys, comments and subtables stay; an unchanged key is untouched. + public static func merging(_ name: String, value: JSONValue, at keyPath: [String], in text: String) throws -> String { + let target = keyPath + [name] + let file = try File(text: text, target: target) + guard !file.layout.containerIsValue else { throw MCPConfigEditError.unsupportedShape } + guard case .object(let wanted) = value, file.layout.table != nil || !file.layout.subtables.isEmpty else { + return try upserting(name, value: value, at: keyPath, in: text) + } + let existing = try file.serverValue() + let merged = existing.merging(value) + + var splices: [(range: Range, text: String)] = [] + var appended: [String] = [] + for part in wanted { + guard let newValue = merged[part.key], existing[part.key] != newValue else { continue } + let line = renderKey(part.key) + " = " + (try renderValue(newValue)) + for subtable in file.subtables(under: part.key) { + splices.append((range: file.removalRange(of: subtable), text: "")) + } + let statements = file.tableStatements(for: part.key) + guard let first = statements.first else { + appended.append(line) + continue + } + splices.append((range: file.lineRange(of: first), text: line + file.lineBreak(endingStatement: first))) + splices += statements.dropFirst().map { (range: file.lineRange(of: $0), text: "") } + } + + if let table = file.layout.table, !appended.isEmpty { + let end = file.blockRange(of: table).upperBound + let lead = end > 0 && file.bytes[end - 1] != 0x0A ? file.newline : "" + splices.append((range: end.. String { + var result = text + if !result.isEmpty, result.utf8.last != 0x0A { + result += newline + } + if !result.isEmpty, !endsWithBlankLine(result) { + result += newline + } + return result + block + } + + public static func removing(_ name: String, at keyPath: [String], in text: String) throws -> String { + let file = try File(text: text, target: keyPath + [name]) + let blocks = (file.layout.table.map { [$0] } ?? []) + file.layout.subtables + guard !blocks.isEmpty else { return text } + let result = file.applying(blocks.map { (range: file.removalRange(of: $0), text: "") }) + guard try member(name, at: keyPath, in: result) == nil else { throw MCPConfigEditError.verificationFailed } + return result + } + + // Compared as bytes: Swift treats "\r\n" as one Character, so hasSuffix("\n") misses it. + private static func endsWithBlankLine(_ text: String) -> Bool { + var bytes = Array(text.utf8) + guard bytes.last == 0x0A else { return false } + bytes.removeLast() + if bytes.last == 0x0D { + bytes.removeLast() + } + return bytes.isEmpty || bytes.last == 0x0A + } + + static func renderBlock(header: [String], value: JSONValue, newline: String) throws -> String { + guard case .object(let members) = value else { throw MCPConfigEditError.unsupportedShape } + var lines = ["[" + header.map(renderKey).joined(separator: ".") + "]"] + for member in members { + lines.append(renderKey(member.key) + " = " + (try renderValue(member.value))) + } + return lines.joined(separator: newline) + newline + } + + static func renderKey(_ key: String) -> String { + guard !key.isEmpty, key.utf8.allSatisfy(TOMLParser.isBareKeyByte) else { return quoted(key) } + return key + } + + static func renderValue(_ value: JSONValue) throws -> String { + switch value { + case .string(let string): + return quoted(string) + case .number(let number): + if number.isNaN { return "nan" } + if number.isInfinite { return number < 0 ? "-inf" : "inf" } + return JSONTextStyle.numberText(number) + case .bool(let bool): + return bool ? "true" : "false" + case .null: + throw MCPConfigEditError.unsupportedShape + case .array(let items): + return "[" + (try items.map(renderValue)).joined(separator: ", ") + "]" + case .object(let members): + guard !members.isEmpty else { return "{}" } + let pairs = try members.map { renderKey($0.key) + " = " + (try renderValue($0.value)) } + return "{ " + pairs.joined(separator: ", ") + " }" + } + } + + static func quoted(_ string: String) -> String { + var result = "\"" + for scalar in string.unicodeScalars { + switch scalar { + case "\"": result += "\\\"" + case "\\": result += "\\\\" + case "\u{08}": result += "\\b" + case "\t": result += "\\t" + case "\n": result += "\\n" + case "\u{0C}": result += "\\f" + case "\r": result += "\\r" + default: + if scalar.value < 0x20 || scalar.value == 0x7F { + result += String(format: "\\u%04X", scalar.value) + } else { + result.unicodeScalars.append(scalar) + } + } + } + return result + "\"" + } +} + +private struct ServerLayout { + var table: Int? + var subtables: [Int] = [] + // A key on the way to the server holds a value (usually an inline table), so no [table] can be added under it. + var containerIsValue = false +} + +private struct File { + let bytes: [UInt8] + let statements: [TOMLStatement] + let target: [String] + let layout: ServerLayout + let newline: String + + init(text: String, target: [String]) throws { + bytes = Array(text.utf8) + statements = try TOMLParser.parse(bytes) + self.target = target + newline = text.contains("\r\n") ? "\r\n" : "\n" + layout = try Self.layout(statements, target: target) + } + + private static func layout(_ statements: [TOMLStatement], target: [String]) throws -> ServerLayout { + var layout = ServerLayout() + var table: [String] = [] + for (position, statement) in statements.enumerated() { + switch statement.kind { + case let .table(keys, isArray): + table = keys + if isArray { + if keys.starts(with: target) || target.starts(with: keys) { + throw MCPConfigEditError.unsupportedShape + } + } else if keys == target { + guard layout.table == nil else { throw MCPConfigEditError.duplicateKey(target) } + layout.table = position + } else if keys.starts(with: target) { + layout.subtables.append(position) + } + case let .keyValue(keys, value): + guard !table.starts(with: target) else { continue } + let full = table + keys + if full.starts(with: target) { + throw MCPConfigEditError.unsupportedShape + } + if target.starts(with: full) { + if Self.lookup(value, path: Array(target.dropFirst(full.count))) { + throw MCPConfigEditError.unsupportedShape + } + layout.containerIsValue = true + } + } + } + return layout + } + + private static func lookup(_ value: JSONValue, path: [String]) -> Bool { + var current = value + for key in path { + guard let next = current[key] else { return false } + current = next + } + return true + } + + func serverValue() throws -> JSONValue { + var members: [(key: String, value: JSONValue)] = [] + let headers = ((layout.table.map { [$0] } ?? []) + layout.subtables).sorted() + for header in headers { + guard case let .table(keys, _) = statements[header].kind else { continue } + let prefix = Array(keys.dropFirst(target.count)) + if !prefix.isEmpty { + try ensureObject(at: prefix, in: &members) + } + for statement in statements[(header + 1)...] { + guard case let .keyValue(keys, value) = statement.kind else { break } + try TOMLTree.insert(value, at: prefix + keys, into: &members) + } + } + return .object(members) + } + + private func ensureObject(at path: [String], in members: inout [(key: String, value: JSONValue)]) throws { + guard let key = path.first else { return } + var children: [(key: String, value: JSONValue)] = [] + let position = members.firstIndex { $0.key == key } + if let position { + guard case .object(let existing) = members[position].value else { throw MCPConfigEditError.invalidSyntax } + children = existing + } + try ensureObject(at: Array(path.dropFirst()), in: &children) + if let position { + members[position].value = .object(children) + } else { + members.append((key: key, value: .object(children))) + } + } + + func tableStatements(for key: String) -> [Int] { + guard let table = layout.table else { return [] } + var result: [Int] = [] + var position = table + 1 + while position < statements.count, case let .keyValue(keys, _) = statements[position].kind { + if keys.first == key { + result.append(position) + } + position += 1 + } + return result + } + + func subtables(under key: String) -> [Int] { + layout.subtables.filter { header in + guard case let .table(keys, _) = statements[header].kind else { return false } + return keys.count > target.count && keys[target.count] == key + } + } + + func lineRange(of statement: Int) -> Range { + statements[statement].lineStart.. String { + let end = statements[statement].lineEnd + guard end > 0, bytes[end - 1] == 0x0A else { return "" } + return end > 1 && bytes[end - 2] == 0x0D ? "\r\n" : "\n" + } + + func blockRange(of header: Int) -> Range { + var last = header + while last + 1 < statements.count, case .keyValue = statements[last + 1].kind { + last += 1 + } + return statements[header].lineStart.. Range { + let range = blockRange(of: header) + guard range.lowerBound > 0 else { return range } + var previousStart = range.lowerBound - 1 + while previousStart > 0, bytes[previousStart - 1] != 0x0A { + previousStart -= 1 + } + guard isBlank(previousStart..) -> Bool { + bytes[range].allSatisfy { $0 == 0x20 || $0 == 0x09 || $0 == 0x0A || $0 == 0x0D } + } + + // At one offset a removal goes before an insertion, or it would take the inserted text with it. + func applying(_ splices: [(range: Range, text: String)]) -> String { + var result = bytes + let ordered = splices.sorted { left, right in + left.range.lowerBound != right.range.lowerBound + ? left.range.lowerBound > right.range.lowerBound + : !left.range.isEmpty && right.range.isEmpty + } + for splice in ordered { + result.replaceSubrange(splice.range, with: Array(splice.text.utf8)) + } + return utf8Text(result) + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLICallbackListenerTests.swift b/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLICallbackListenerTests.swift index 66bbae8c8b..44a6981bb0 100644 --- a/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLICallbackListenerTests.swift +++ b/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLICallbackListenerTests.swift @@ -24,6 +24,21 @@ struct CLICallbackListenerTests { #expect(await listener.waitForCallback(timeout: .seconds(5)) == .approved(code: "c-1")) } + @Test("A pairing TablePro could not finish reaches the command as a failure, not a refusal") + func listenerReportsAFailedPairing() async throws { + let listener = CLICallbackListener(state: "s2") + defer { listener.stop() } + let port = try await listener.start() + + let session = URLSession(configuration: .ephemeral) + let callback = try #require(URL(string: "http://127.0.0.1:\(port)\(CLIPairingRequest.callbackPath)?error=server_error&state=s2")) + let (body, response) = try await session.data(from: callback) + #expect((response as? HTTPURLResponse)?.statusCode == 200) + #expect(String(data: body, encoding: .utf8)?.contains("could not finish pairing") == true) + + #expect(await listener.waitForCallback(timeout: .seconds(5)) == .failed) + } + @Test("A listener nobody calls gives up") func listenerTimeout() async throws { let listener = CLICallbackListener(state: "s1") diff --git a/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLIFailureTests.swift b/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLIFailureTests.swift index 2c42d1c929..90a08a128f 100644 --- a/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLIFailureTests.swift +++ b/apple/Packages/TableProMacCore/Tests/TableProCommandLineTests/CLIFailureTests.swift @@ -34,4 +34,24 @@ struct CLIFailureTests { func rpcErrors(code: Int, expected: CLIExitCode) { #expect(CLIFailure.fromRpcError(code: code, message: "m").exitCode == expected) } + + @Test("A server that is on but failed to start sends the reader to Settings > MCP, said once") + func failedStartNamesSettings() { + let failure = CLILive.failure(acquiring: MCPHandshakeAcquisitionError.serverFailedToStart) + #expect(failure.exitCode == .failure) + #expect(failure.message.contains("Settings > MCP")) + #expect(!failure.message.contains("did not start its MCP server:")) + } + + @Test("A server that is turned off is a refusal") + func turnedOffIsARefusal() { + #expect(CLILive.failure(acquiring: MCPHandshakeAcquisitionError.serverTurnedOff).exitCode == .refused) + } + + @Test("Any other launch failure keeps its own reason") + func otherLaunchFailureKeepsItsReason() { + let failure = CLILive.failure(acquiring: MCPHandshakeAcquisitionError.launchFailed("no app")) + #expect(failure.exitCode == .failure) + #expect(failure.message.contains("no app")) + } } diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/JSONCMemberEditorTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/JSONCMemberEditorTests.swift new file mode 100644 index 0000000000..2821e938cb --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/JSONCMemberEditorTests.swift @@ -0,0 +1,447 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct JSONCMemberEditorTests { + private let entry: JSONValue = .object([(key: "command", value: .string("/b"))]) + + @Test("A member is read through comments and trailing commas") + func readsThroughComments() throws { + let text = """ + // Zed settings + // + // documentation: https://zed.dev/docs/configuring-zed + { + "ui_font_size": 16, + /* servers */ + "context_servers": { + "tablepro": { + "command": "/b", // bridge + "args": [], + }, + }, + } + """ + let member = try JSONCMemberEditor.member("tablepro", at: ["context_servers"], in: text) + #expect(member == .object([(key: "command", value: .string("/b")), (key: "args", value: .array([]))])) + #expect(try JSONCMemberEditor.member("other", at: ["context_servers"], in: text) == nil) + #expect(try JSONCMemberEditor.member("tablepro", at: ["missing"], in: text) == nil) + } + + @Test("Strings that look like comments and escapes are read as strings") + func stringsAndEscapes() throws { + let text = #"{"url": "http://x//y/*z*/", "quote": "a\"b\\cé😀", "mcpServers": {}}"# + #expect(try JSONCMemberEditor.member("url", at: [], in: text) == .string("http://x//y/*z*/")) + #expect(try JSONCMemberEditor.member("quote", at: [], in: text) == .string("a\"b\\c\u{e9}\u{1F600}")) + } + + @Test("Inserting into an existing container keeps comments, order and the file's four-space indent") + func insertKeepsLayout() throws { + let text = """ + { + // Servers I use + "mcpServers": { + "other": { + "command": "/usr/local/bin/other" // keep + } + }, + /* trailing block */ + "theme": "dark" + } + + """ + let result = try JSONCMemberEditor.upserting("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcpServers"], in: text) + #expect(result == """ + { + // Servers I use + "mcpServers": { + "other": { + "command": "/usr/local/bin/other" // keep + }, + "tablepro": { + "command": "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp", + "args": [] + } + }, + /* trailing block */ + "theme": "dark" + } + + """) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: result) == text) + } + + @Test("A missing container is created after the last top-level key") + func createsContainer() throws { + let text = """ + { + "coworkUserFilesPath": "/Users/me/Claude", + "preferences": { + "quickEntry": true + } + } + """ + let result = try JSONCMemberEditor.upserting("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcpServers"], in: text) + #expect(result == """ + { + "coworkUserFilesPath": "/Users/me/Claude", + "preferences": { + "quickEntry": true + }, + "mcpServers": { + "tablepro": { + "command": "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp", + "args": [] + } + } + } + """) + } + + @Test("Every missing object along a longer key path is created") + func createsNestedPath() throws { + let result = try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcp", "servers"], in: "{}\n") + #expect(result == """ + { + "mcp": { + "servers": { + "tablepro": { + "command": "/b" + } + } + } + } + + """) + let partial = try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcp", "servers"], in: #"{"mcp": {"a": 1}}"#) + #expect(partial == #"{"mcp": {"a": 1, "servers": {"tablepro": {"command": "/b"}}}}"#) + } + + @Test("An existing member is replaced where it stands") + func replacesInPlace() throws { + let text = """ + { + "mcpServers": { + "tablepro": { + "command": "/old/path", + "args": ["--x"] + }, + "other": { "command": "o" } + } + } + """ + let result = try JSONCMemberEditor.upserting("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcpServers"], in: text) + #expect(result == """ + { + "mcpServers": { + "tablepro": { + "command": "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp", + "args": [] + }, + "other": { "command": "o" } + } + } + """) + #expect(try JSONCMemberEditor.upserting("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcpServers"], in: result) == result) + } + + @Test("A file with trailing commas and tabs keeps both") + func trailingCommasAndTabs() throws { + let text = [ + "{", + "\t// VS Code MCP", + "\t\"servers\": {", + "\t\t\"other\": {", + "\t\t\t\"type\": \"stdio\",", + "\t\t\t\"command\": \"o\",", + "\t\t},", + "\t},", + "\t\"inputs\": [],", + "}", + ].joined(separator: "\n") + let result = try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["servers"], in: text) + #expect(result == [ + "{", + "\t// VS Code MCP", + "\t\"servers\": {", + "\t\t\"other\": {", + "\t\t\t\"type\": \"stdio\",", + "\t\t\t\"command\": \"o\",", + "\t\t},", + "\t\t\"tablepro\": {", + "\t\t\t\"command\": \"/b\"", + "\t\t},", + "\t},", + "\t\"inputs\": [],", + "}", + ].joined(separator: "\n")) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["servers"], in: result) == text) + } + + @Test("CRLF line breaks are kept") + func crlf() throws { + let result = try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: "{\r\n \"a\": 1\r\n}\r\n") + #expect(result == "{\r\n \"a\": 1,\r\n \"mcpServers\": {\r\n \"tablepro\": {\r\n \"command\": \"/b\"\r\n }\r\n }\r\n}\r\n") + } + + @Test("Empty, blank and comment-only files count as an empty object") + func emptyFiles() throws { + let expected = """ + { + "mcpServers": { + "tablepro": { + "command": "/b" + } + } + } + + """ + #expect(try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: "") == expected) + #expect(try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: " \n") == expected) + #expect(try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: "// my config") == "// my config\n" + expected) + #expect(try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: "/* a */\n") == "/* a */\n" + expected) + #expect(try JSONCMemberEditor.member("tablepro", at: ["mcpServers"], in: "// only a comment") == nil) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: "// only a comment") == "// only a comment") + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: "") == "") + } + + @Test("An empty container opens up at the file's indent, after any comment inside it") + func emptyContainers() throws { + let inline = """ + { + "mcpServers": {}, + "x": 1 + } + """ + #expect(try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: inline) == """ + { + "mcpServers": { + "tablepro": { + "command": "/b" + } + }, + "x": 1 + } + """) + let commented = """ + { + "context_servers": { + // none yet + } + } + """ + #expect(try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["context_servers"], in: commented) == """ + { + "context_servers": { + // none yet + "tablepro": { + "command": "/b" + } + } + } + """) + } + + @Test("A minified file stays on one line") + func minified() throws { + let text = #"{"mcpServers":{"other":{"command":"o"}}}"# + let result = try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: text) + #expect(result == #"{"mcpServers":{"other":{"command":"o"},"tablepro":{"command":"/b"}}}"#) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: result) == text) + } + + @Test("Removing a middle member takes its line, comma and comment") + func removeMiddle() throws { + let text = """ + { + "mcpServers": { + "a": {}, + "tablepro": { + "command": "/b" + }, // ours + "c": {} + } + } + """ + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: text) == """ + { + "mcpServers": { + "a": {}, + "c": {} + } + } + """) + } + + @Test("Removing the only member leaves an empty container") + func removeOnly() throws { + let text = """ + { + "mcpServers": { + "tablepro": { + "command": "/b" + } + }, + "x": 1 + } + """ + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: text) == """ + { + "mcpServers": {}, + "x": 1 + } + """) + } + + @Test("Removing from one line keeps the separators valid") + func removeInline() throws { + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: #"{"mcpServers": {"a": 1, "tablepro": {"command": "/b"}}}"#) + == #"{"mcpServers": {"a": 1}}"#) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: #"{"mcpServers": {"tablepro": {}, "a": 1}}"#) + == #"{"mcpServers": {"a": 1}}"#) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: #"{"mcpServers": { "tablepro": {} }}"#) + == #"{"mcpServers": {}}"#) + } + + @Test("Removing a member that is not there changes nothing") + func removeAbsent() throws { + let text = "{\n // keep\n \"mcpServers\": {\"a\": 1}\n}\n" + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: text) == text) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["missing"], in: text) == text) + } + + @Test("A duplicate key on the walked path is refused") + func duplicateKeys() { + let duplicateContainer = #"{"mcpServers": {}, "mcpServers": {}}"# + #expect(throws: MCPConfigEditError.duplicateKey(["mcpServers"])) { + try JSONCMemberEditor.member("tablepro", at: ["mcpServers"], in: duplicateContainer) + } + #expect(throws: MCPConfigEditError.duplicateKey(["mcpServers"])) { + try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: duplicateContainer) + } + #expect(throws: MCPConfigEditError.duplicateKey(["mcpServers"])) { + try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: duplicateContainer) + } + let duplicateMember = #"{"mcpServers": {"tablepro": {}, "tablepro": {}}}"# + #expect(throws: MCPConfigEditError.duplicateKey(["mcpServers", "tablepro"])) { + try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: duplicateMember) + } + #expect(throws: MCPConfigEditError.duplicateKey(["mcp", "servers"])) { + try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcp", "servers"], in: #"{"mcp": {"servers": {}, "servers": {}}}"#) + } + } + + @Test("A non-object on the path is refused") + func notAnObject() { + #expect(throws: MCPConfigEditError.notAnObject(["mcpServers"])) { + try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: #"{"mcpServers": []}"#) + } + #expect(throws: MCPConfigEditError.notAnObject(["mcp", "servers"])) { + try JSONCMemberEditor.member("tablepro", at: ["mcp", "servers"], in: #"{"mcp": {"servers": "x"}}"#) + } + #expect(throws: MCPConfigEditError.notAnObject([])) { + try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: "[]") + } + } + + @Test("Broken syntax is refused", arguments: [ + #"{"a": }"#, #"{"a": 1 /* open"#, #"{"a" 1}"#, "{,}", #"{"a": 1,,}"#, #"{"a": 'x'}"#, #"{"a": 01}"#, "{} {}", "{\"a\": \"\n\"}", + ]) + func invalidSyntax(text: String) { + #expect(throws: MCPConfigEditError.invalidSyntax) { + try JSONCMemberEditor.upserting("tablepro", value: .object([]), at: ["mcpServers"], in: text) + } + } + + @Test("Escapes and non-ASCII text round trip through an edit") + func escapesRoundTrip() throws { + let value: JSONValue = .object([ + (key: "command", value: .string("/Apps/Tab\"le\\Pro é\n\u{1}/bridge")), + (key: "timeout", value: .number(300)), + (key: "ratio", value: .number(0.5)), + (key: "enabled", value: .bool(false)), + (key: "extra", value: .null), + ]) + let text = "{\n \"név\": \"ő\"\n}\n" + let result = try JSONCMemberEditor.upserting("tablepro", value: value, at: ["mcpServers"], in: text) + #expect(try JSONCMemberEditor.member("tablepro", at: ["mcpServers"], in: result) == value) + #expect(result.hasPrefix("{\n \"név\": \"ő\",\n")) + #expect(result.contains(#""timeout": 300,"#)) + let parsed = try MCPClientsFixtures.parsed(result) + let servers = try #require(parsed["mcpServers"] as? NSDictionary) + let server = try #require(servers["tablepro"] as? NSDictionary) + #expect(server["command"] as? String == "/Apps/Tab\"le\\Pro é\n\u{1}/bridge") + } + + @Test("A duplicate key elsewhere in the file does not block the edit") + func unrelatedDuplicate() throws { + let text = "{\n \"a\": 1,\n \"a\": 2,\n \"mcpServers\": {}\n}" + let result = try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: text) + #expect(try JSONCMemberEditor.member("tablepro", at: ["mcpServers"], in: result) == entry) + } + + @Test("Merging rewrites only the members the entry names and keeps the rest where they stand") + func mergeKeepsUserMembers() throws { + let text = """ + { + "mcpServers": { + "tablepro": { + "command": "/old/path", // moved + "args": ["--x"], + "autoApprove": ["list_connections"], + "env": { "A": "1" }, + "timeout": 30 + } + } + } + """ + let value: JSONValue = .object([ + (key: "command", value: .string("/b")), + (key: "args", value: .array([])), + (key: "env", value: .object([])), + (key: "type", value: .string("stdio")), + ]) + let result = try JSONCMemberEditor.merging("tablepro", value: value, at: ["mcpServers"], in: text) + #expect(result == """ + { + "mcpServers": { + "tablepro": { + "command": "/b", // moved + "args": [], + "autoApprove": ["list_connections"], + "env": { "A": "1" }, + "timeout": 30, + "type": "stdio" + } + } + } + """) + #expect(try JSONCMemberEditor.merging("tablepro", value: value, at: ["mcpServers"], in: result) == result) + } + + @Test("Merging a missing or non-object entry writes the whole value") + func mergeWithoutEntry() throws { + let missing = #"{"mcpServers": {"other": {}}}"# + #expect(try JSONCMemberEditor.merging("tablepro", value: entry, at: ["mcpServers"], in: missing) + == JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: missing)) + #expect(try JSONCMemberEditor.merging("tablepro", value: entry, at: ["mcpServers"], in: #"{"mcpServers": {"tablepro": "x"}}"#) + == #"{"mcpServers": {"tablepro": {"command": "/b"}}}"#) + #expect(try JSONCMemberEditor.merging("tablepro", value: entry, at: ["mcpServers"], in: "") + == JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: "")) + } + + @Test("An unpaired surrogate escape, which Node writes, reads as U+FFFD and survives an edit unchanged") + func loneSurrogates() throws { + func escape(_ hex: String) -> String { "\\" + "u" + hex } + for title in [escape("d83d"), escape("dc00") + "x", escape("d83d") + escape("0041")] { + let text = "{\n \"title\": \"" + title + "\",\n \"mcpServers\": {}\n}\n" + let added = try JSONCMemberEditor.upserting("tablepro", value: entry, at: ["mcpServers"], in: text) + #expect(added.contains("\"title\": \"" + title + "\",")) + #expect(try JSONCMemberEditor.member("tablepro", at: ["mcpServers"], in: added) == entry) + #expect(try JSONCMemberEditor.member("title", at: [], in: added)?.stringValue?.hasPrefix("\u{FFFD}") == true) + #expect(try JSONCMemberEditor.removing("tablepro", at: ["mcpServers"], in: added) == text) + } + let pair = escape("d83d") + escape("de00") + #expect(try JSONCMemberEditor.member("t", at: [], in: "{\"t\": \"" + pair + "\"}") == .string("\u{1F600}")) + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientCatalogTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientCatalogTests.swift new file mode 100644 index 0000000000..40d64110b9 --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientCatalogTests.swift @@ -0,0 +1,208 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct MCPClientCatalogTests { + @Test("The bundled catalog decodes") + func decodesBundledCatalog() throws { + let catalog = try MCPClientsFixtures.catalog() + #expect(catalog.schemaVersion == 1) + #expect(catalog.serverName == "tablepro") + #expect(catalog.clients.first?.id == "claude-desktop") + #expect(catalog.clients.count > 10) + } + + @Test("Client ids are unique") + func clientIDsAreUnique() throws { + let ids = try MCPClientsFixtures.catalog().clients.map(\.id) + #expect(Set(ids).count == ids.count) + } + + @Test("Every config id resolves for each platform the client has") + func everyConfigResolves() throws { + let catalog = try MCPClientsFixtures.catalog() + for client in catalog.clients { + guard let configID = client.configID else { continue } + #expect(catalog.configs[configID] != nil, "\(client.id) names \(configID)") + for platform in MCPClientPlatform.allCases where client.spec(for: platform) != nil { + #expect(catalog.location(for: client, platform: platform) != nil, "\(client.id) on \(platform)") + } + } + } + + @Test("Every client renders its entry, arguments and deeplinks on both platforms") + func everyClientRenders() throws { + let catalog = try MCPClientsFixtures.catalog() + var rendered = 0 + for client in catalog.clients { + for platform in MCPClientPlatform.allCases { + guard let spec = client.spec(for: platform) else { continue } + if spec.unsupported != nil { + #expect(spec.install.isEmpty, "\(client.id) on \(platform) is unsupported but installs") + continue + } + let renderer = MCPClientsFixtures.renderer(for: platform) + let entry = try renderer.entry(spec) + #expect(!MCPClientsFixtures.hasPlaceholder(entry.compactText), "\(client.id) on \(platform): \(entry.compactText)") + for method in spec.install { + switch method { + case let .deeplink(scheme, template): + let url = try renderer.url(template, entry: entry) + #expect(url.scheme == scheme) + case .cli(let cli): + let added = try renderer.arguments(cli.add, entry: entry) + #expect(!added.contains { MCPClientsFixtures.hasPlaceholder($0) }) + if let remove = cli.remove { + #expect(try renderer.arguments(remove, entry: entry).contains("tablepro")) + } + case .file: + let location = try #require(catalog.location(for: client, platform: platform)) + #expect(location.isWritable, "\(client.id) on \(platform) offers a file install on a read-only config") + } + } + _ = renderer.snippet(for: catalog.location(for: client, platform: platform), entry: entry) + rendered += 1 + } + } + #expect(rendered > 20) + } + + @Test("Entries keep the catalog's key order") + func entryKeyOrder() throws { + let catalog = try MCPClientsFixtures.catalog() + let spec = try #require(catalog.client(id: "claude-code")?.spec(for: .macos)) + let entry = try MCPClientsFixtures.renderer(for: .macos).entry(spec) + #expect(entry.objectMembers?.map(\.key) == ["type", "command", "args", "env"]) + } + + @Test("Locations decode their defaults and flags") + func locations() throws { + let catalog = try MCPClientsFixtures.catalog() + let claudeCode = try #require(catalog.client(id: "claude-code")) + let location = try #require(catalog.location(for: claudeCode, platform: .macos)) + #expect(location.format == .json) + #expect(location.keyPath == ["mcpServers"]) + #expect(!location.isWritable) + #expect(location.otherScopes == [["projects", "*", "mcpServers"]]) + + let cursor = try #require(catalog.client(id: "cursor")) + let cursorLocation = try #require(catalog.location(for: cursor, platform: .macos)) + #expect(cursorLocation.isWritable) + #expect(cursorLocation.otherScopes.isEmpty) + #expect(cursorLocation.alternateKeyPaths.isEmpty) + #expect(catalog.location(for: try MCPClientsFixtures.client("raycast"), platform: .macos) == nil) + + let opencode = try MCPClientsFixtures.location("opencode") + #expect(opencode.keyPath == ["mcp", "servers"]) + #expect(opencode.alternateKeyPaths == [["mcp"]]) + #expect(opencode.otherScopes.isEmpty) + } + + @Test("Detect rules and install methods decode") + func detectAndInstall() throws { + let catalog = try MCPClientsFixtures.catalog() + let cursor = try #require(catalog.client(id: "cursor")?.spec(for: .macos)) + #expect(cursor.detect == [.bundleID("com.todesktop.230313mzl4w4u92"), .path("~/.cursor")]) + #expect(cursor.install.last == .file) + #expect(cursor.applies == .live) + + let claudeCode = try #require(catalog.client(id: "claude-code")?.spec(for: .macos)) + guard case .cli(let cli)? = claudeCode.install.first else { + Issue.record("claude-code installs through its CLI") + return + } + #expect(cli.binary == "claude") + #expect(cli.update == .removeThenAdd) + #expect(cli.remove == ["mcp", "remove", "--scope", "user", "{name}"]) + + let opencode = try #require(catalog.client(id: "opencode")?.spec(for: .macos)) + guard case .cli(let opencodeCLI)? = opencode.install.first else { + Issue.record("opencode installs through its CLI") + return + } + #expect(opencodeCLI.remove == nil) + #expect(opencodeCLI.update == .add) + + let classic = try #require(catalog.client(id: "chatgpt-classic")) + #expect(classic.configID == nil) + #expect(classic.spec(for: .macos)?.unsupported == .remoteOnly) + #expect(classic.spec(for: .linux) == nil) + } + + @Test("clientInfo names match exactly first, then by the longest prefix, ignoring case") + func clientInfoMatching() throws { + let catalog = try MCPClientsFixtures.catalog() + #expect(catalog.client(matchingClientInfoName: "claude-code")?.id == "claude-code") + #expect(catalog.client(matchingClientInfoName: "CLAUDE-AI")?.id == "claude-desktop") + #expect(catalog.client(matchingClientInfoName: "Visual Studio Code")?.id == "vscode") + #expect(catalog.client(matchingClientInfoName: "Visual-Studio-Code")?.id == "vscode") + #expect(catalog.client(matchingClientInfoName: "Visual Studio Code - Insiders")?.id == "vscode-insiders") + #expect(catalog.client(matchingClientInfoName: "zed")?.id == "zed") + #expect(catalog.client(matchingClientInfoName: "goose-cli")?.id == "goose") + #expect(catalog.client(matchingClientInfoName: "goose-server")?.id == "goose") + #expect(catalog.client(matchingClientInfoName: "something-else") == nil) + #expect(catalog.client(matchingClientInfoName: "") == nil) + } + + @Test("A clientInfo name two clients send is the one detected here, or neither") + func sharedClientInfoName() throws { + let catalog = try MCPClientsFixtures.catalog() + #expect(catalog.clients(matchingClientInfoName: "codex-mcp-client").map { $0.id } == ["chatgpt", "codex"]) + #expect(catalog.clients(matchingClientInfoName: "Visual Studio Code - Insiders").map { $0.id } == ["vscode-insiders"]) + #expect(catalog.client(matchingClientInfoName: "Codex", detected: ["codex"])?.id == "codex") + #expect(catalog.client(matchingClientInfoName: "codex-mcp-client", detected: ["chatgpt", "cursor"])?.id == "chatgpt") + #expect(catalog.client(matchingClientInfoName: "codex-mcp-client", detected: ["chatgpt", "codex"]) == nil) + #expect(catalog.client(matchingClientInfoName: "codex-mcp-client", detected: []) == nil) + #expect(catalog.client(matchingClientInfoName: "claude-code", detected: [])?.id == "claude-code") + } + + @Test("The HTTP entry is the first platform entry that names {url}") + func httpEntry() throws { + let catalog = try MCPClientsFixtures.catalog() + let claudeCode = try #require(catalog.client(id: "claude-code")) + let entry = try #require(catalog.httpEntry(for: claudeCode)) + #expect(entry["type"] == .string("http")) + #expect(entry["url"] == .string("{url}")) + + let rendered = try MCPClientsFixtures.renderer(for: .linux).entry(template: entry) + #expect(rendered["headers"]?["Authorization"] == .string(MCPClientsFixtures.authorization)) + + #expect(catalog.httpEntry(for: try MCPClientsFixtures.client("claude-desktop")) == nil) + #expect(catalog.httpEntry(for: try MCPClientsFixtures.client("chatgpt-classic")) == nil) + #expect(catalog.httpEntry(for: try MCPClientsFixtures.client("raycast")) == nil) + } + + @Test("A newer schema version is refused") + func newerSchemaRefused() { + let data = Data(#"{"schemaVersion": 2, "serverName": "tablepro", "configs": {}, "clients": []}"#.utf8) + #expect(throws: MCPClientCatalogError.unsupportedSchemaVersion(2)) { + try MCPClientCatalog.decode(data) + } + } + + @Test("A missing field names its path") + func missingFieldPath() { + let data = Data(#"{"schemaVersion": 1, "serverName": "tablepro", "configs": {}, "clients": [{"id": "x", "icon": "x"}]}"#.utf8) + #expect(throws: MCPClientCatalogError.invalidField(["clients", "0", "name"])) { + try MCPClientCatalog.decode(data) + } + } + + @Test("An unknown install kind is refused") + func unknownInstallKind() { + let data = Data(#""" + {"schemaVersion": 1, "serverName": "tablepro", "configs": {}, + "clients": [{"id": "x", "name": "X", "icon": "x", "config": null, "macos": {"install": [{"kind": "magic"}]}}]} + """#.utf8) + #expect(throws: MCPClientCatalogError.invalidField(["clients", "0", "macos", "install", "0", "kind"])) { + try MCPClientCatalog.decode(data) + } + } + + @Test("Decoding through JSONDecoder gives the same clients") + func jsonDecoderConformance() throws { + let data = try Data(contentsOf: MCPClientsFixtures.catalogURL) + let decoded = try JSONDecoder().decode(MCPClientCatalog.self, from: data) + #expect(decoded.clients.map(\.id) == (try MCPClientsFixtures.catalog()).clients.map(\.id)) + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientStatusEvaluatorTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientStatusEvaluatorTests.swift new file mode 100644 index 0000000000..022d840c62 --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientStatusEvaluatorTests.swift @@ -0,0 +1,203 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct MCPClientStatusEvaluatorTests { + private let json = MCPConfigLocation(path: "~/.cursor/mcp.json", format: .json, keyPath: ["mcpServers"]) + private let stdio = MCPServerTarget.stdio(command: MCPClientsFixtures.bridge) + private let http = MCPServerTarget.http(url: MCPClientsFixtures.httpURL, authorization: MCPClientsFixtures.authorization) + + private func status( + _ text: String?, + location: MCPConfigLocation?, + expected: MCPServerTarget, + existing: Set = [] + ) -> MCPClientConfigStatus { + MCPClientStatusEvaluator.status( + configText: text, location: location, serverName: "tablepro", expected: expected, fileExists: { existing.contains($0) } + ) + } + + @Test("No config location is unknown; no file is not configured") + func missingInputs() { + #expect(status("{}", location: nil, expected: stdio) == .unknown) + #expect(status(nil, location: json, expected: stdio) == .notConfigured) + #expect(status("", location: json, expected: stdio) == .notConfigured) + #expect(status(#"{"mcpServers": {"other": {}}}"#, location: json, expected: stdio) == .notConfigured) + } + + @Test("The running bridge's path is current") + func stdioCurrent() { + let text = "{\n // c\n \"mcpServers\": {\"tablepro\": {\"command\": \"\(MCPClientsFixtures.bridge)\", \"args\": []},}\n}" + #expect(status(text, location: json, expected: stdio) == .current) + } + + @Test("An array command is compared by its first element") + func arrayCommand() throws { + let location = try MCPClientsFixtures.location("opencode") + let text = #"{"mcp": {"servers": {"tablepro": {"type": "local", "command": ["\#(MCPClientsFixtures.bridge)", "--x"]}}}}"# + #expect(status(text, location: location, expected: stdio) == .current) + } + + @Test("A command that is gone is stale as missing; another existing one as another command") + func stdioStale() { + let text = #"{"mcpServers": {"tablepro": {"command": "\#(MCPClientsFixtures.betaBridge)"}}}"# + #expect(status(text, location: json, expected: stdio) == .stale(.commandMissing)) + #expect(status(text, location: json, expected: stdio, existing: [MCPClientsFixtures.betaBridge]) == .stale(.otherCommand)) + #expect(status(#"{"mcpServers": {"tablepro": {"type": "stdio"}}}"#, location: json, expected: stdio) == .stale(.otherCommand)) + } + + @Test("An HTTP entry where the bridge is expected is set up with a token, never stale") + func httpEntryUsesToken() throws { + let tokenSheet = #"{"mcpServers": {"tablepro": {"url": "http://127.0.0.1:23508/mcp", "headers": {"Authorization": "Bearer tp_x"}}}}"# + #expect(status(tokenSheet, location: json, expected: stdio) == .usesToken) + let claudeCode = try MCPClientsFixtures.location("claude-code") + let added = #"{"mcpServers": {"tablepro": {"type": "http", "url": "http://localhost:23508/mcp", "headers": {"Authorization": "Bearer tp_x"}}}}"# + #expect(status(added, location: claudeCode, expected: stdio) == .usesToken) + let codex = try MCPClientsFixtures.location("codex") + let table = "[mcp_servers.tablepro]\nurl = \"http://127.0.0.1:23508/mcp\"\nhttp_headers = { Authorization = \"Bearer tp_x\" }\n" + #expect(status(table, location: codex, expected: stdio) == .usesToken) + } + + @Test("A current entry the user turned off reads as disabled") + func disabledEntries() throws { + func entry(_ fields: String) -> String { + #"{"mcpServers": {"tablepro": {"command": "\#(MCPClientsFixtures.bridge)", \#(fields)}}}"# + } + #expect(status(entry(#""disabled": true"#), location: json, expected: stdio) == .disabled) + #expect(status(entry(#""enabled": false"#), location: json, expected: stdio) == .disabled) + #expect(status(entry(#""disabled": false"#), location: json, expected: stdio) == .current) + #expect(status(entry(#""enabled": true"#), location: json, expected: stdio) == .current) + + let codex = try MCPClientsFixtures.location("codex") + let table = "[mcp_servers.tablepro]\ncommand = \"\(MCPClientsFixtures.bridge)\"\nenabled = false\n" + #expect(status(table, location: codex, expected: stdio) == .disabled) + } + + @Test("A turned-off entry reads as disabled whatever it points at, so it is never offered an Update") + func disabledBeforeStale() throws { + let moved = #"{"mcpServers": {"tablepro": {"command": "/gone", "disabled": true}}}"# + #expect(status(moved, location: json, expected: stdio) == .disabled) + let token = #"{"mcpServers": {"tablepro": {"url": "http://127.0.0.1:23508/mcp", "enabled": false}}}"# + #expect(status(token, location: json, expected: stdio) == .disabled) + let codex = try MCPClientsFixtures.location("codex") + let oldToken = "[mcp_servers.tablepro]\nurl = \"\(MCPClientsFixtures.httpURL)\"\n" + + "http_headers = { Authorization = \"Bearer tp_old\" }\nenabled = false\n" + #expect(status(oldToken, location: codex, expected: http) == .disabled) + } + + @Test("A hit only in another scope is otherScope, with * matching any key") + func otherScopes() throws { + let claudeCode = try MCPClientsFixtures.location("claude-code") + let local = #"{"projects": {"/Users/me/app": {"mcpServers": {"tablepro": {"command": "/b"}}}}, "mcpServers": {}}"# + #expect(status(local, location: claudeCode, expected: stdio, existing: ["/Users/me/app"]) == .otherScope) + let bridge = MCPClientsFixtures.bridge + let both = #"{"projects": {"/x": {"mcpServers": {"tablepro": {"command": "\#(bridge)"}}}}, "mcpServers": {"tablepro": {"command": "\#(bridge)"}}}"# + #expect(status(both, location: claudeCode, expected: stdio, existing: ["/x"]) == .current) + #expect(status(#"{"projects": {"/x": {"mcpServers": {}}, "/y": []}}"#, location: claudeCode, expected: stdio) == .notConfigured) + } + + @Test("A project whose folder is gone is not a scope any more") + func goneProjectFolders() throws { + let claudeCode = try MCPClientsFixtures.location("claude-code") + let onlyThere = #"{"projects": {"/Users/me/old": {"mcpServers": {"tablepro": {"command": "/b"}}}}, "mcpServers": {}}"# + #expect(status(onlyThere, location: claudeCode, expected: stdio) == .notConfigured) + let bridge = MCPClientsFixtures.bridge + let shadowedByGone = #"{"projects": {"/Users/me/old": {"mcpServers": {"tablepro": {"command": "/Volumes/Gone/tablepro-mcp"}}}}, "# + + #""mcpServers": {"tablepro": {"command": "\#(bridge)"}}}"# + #expect(status(shadowedByGone, location: claudeCode, expected: stdio) == .current) + #expect(status(shadowedByGone, location: claudeCode, expected: stdio, existing: ["/Users/me/old"]) + == .stale(.shadowed(scope: "/Users/me/old"))) + } + + @Test("A stale entry in another scope shadows a current one there and names it; a token or turned-off one does not") + func shadowingScopes() throws { + let claudeCode = try MCPClientsFixtures.location("claude-code") + func file(project: String) -> String { + #"{"projects": {"/a": {"mcpServers": {}}, "/b": {"mcpServers": {"tablepro": \#(project)}}}, "# + + #""mcpServers": {"tablepro": {"type": "stdio", "command": "\#(MCPClientsFixtures.bridge)"}}}"# + } + let folders: Set = ["/a", "/b"] + #expect(status(file(project: #"{"command": "/Volumes/Gone/tablepro-mcp"}"#), location: claudeCode, expected: stdio, existing: folders) + == .stale(.shadowed(scope: "/b"))) + #expect(status(file(project: #"{"command": "/x"}"#), location: claudeCode, expected: stdio, existing: folders.union(["/x"])) + == .stale(.shadowed(scope: "/b"))) + let token = #"{"type": "http", "url": "http://127.0.0.1:23508/mcp", "headers": {"Authorization": "Bearer tp_x"}}"# + #expect(status(file(project: token), location: claudeCode, expected: stdio, existing: folders) == .current) + let off = #"{"command": "/Volumes/Gone/tablepro-mcp", "disabled": true}"# + #expect(status(file(project: off), location: claudeCode, expected: stdio, existing: folders) == .current) + + let staleUser = #"{"projects": {"/b": {"mcpServers": {"tablepro": {"command": "/x"}}}}, "mcpServers": {"tablepro": {"command": "/y"}}}"# + #expect(status(staleUser, location: claudeCode, expected: stdio, existing: folders) == .stale(.commandMissing)) + } + + @Test("opencode's V1 mcp. reads like its V2 mcp.servers., never as another scope") + func alternateKeyPaths() throws { + let opencode = try MCPClientsFixtures.location("opencode") + let bridge = MCPClientsFixtures.bridge + #expect(status(#"{"mcp": {"tablepro": {"type": "local", "command": ["\#(bridge)"]}}}"#, location: opencode, expected: stdio) == .current) + #expect(status(#"{"mcp": {"tablepro": {"type": "local", "command": ["/gone"]}}}"#, location: opencode, expected: stdio) + == .stale(.commandMissing)) + #expect(status(#"{"mcp": {"servers": {"tablepro": {"command": ["\#(bridge)"]}}}}"#, location: opencode, expected: stdio) == .current) + #expect(status(#"{"mcp": {"servers": {}, "other": {}}}"#, location: opencode, expected: stdio) == .notConfigured) + #expect(status(#"{"mcp": {"tablepro": {"type": "local"}}}"#, location: opencode, expected: stdio) == .stale(.otherCommand)) + } + + @Test("An unpaired surrogate escape, which Node writes, does not make a file unreadable") + func loneSurrogate() { + let escape = "\\" + "ud83d" + let text = #"{"title": ""# + escape + #"", "mcpServers": {"tablepro": {"command": "\#(MCPClientsFixtures.bridge)"}}}"# + #expect(status(text, location: json, expected: stdio) == .current) + } + + @Test("Text that cannot be read safely is unreadable") + func unreadable() { + #expect(status("{", location: json, expected: stdio) == .unreadable) + #expect(status(#"{"mcpServers": {}, "mcpServers": {}}"#, location: json, expected: stdio) == .unreadable) + #expect(status(#"{"mcpServers": []}"#, location: json, expected: stdio) == .unreadable) + let toml = MCPConfigLocation(path: "~/.codex/config.toml", format: .toml, keyPath: ["mcp_servers"]) + #expect(status("[mcp_servers]\ntablepro.command = \"x\"\n", location: toml, expected: stdio) == .unreadable) + } + + @Test("A YAML config is unknown") + func yaml() { + let location = MCPConfigLocation(path: "~/.config/goose/config.yaml", format: .yaml, keyPath: ["extensions"], isWritable: false) + #expect(status("extensions: {}\n", location: location, expected: stdio) == .unknown) + #expect(status(nil, location: location, expected: stdio) == .unknown) + } + + @Test("Codex's TOML table is compared like JSON") + func toml() throws { + let location = try MCPClientsFixtures.location("codex") + #expect(status("[mcp_servers.tablepro]\ncommand = \"\(MCPClientsFixtures.bridge)\"\n", location: location, expected: stdio) == .current) + #expect(status("[mcp_servers.tablepro]\ncommand = \"/gone\"\n", location: location, expected: stdio) == .stale(.commandMissing)) + #expect(status("[mcp_servers.other]\ncommand = \"/o\"\n", location: location, expected: stdio) == .notConfigured) + + let httpTable = """ + [mcp_servers.tablepro] + url = "\(MCPClientsFixtures.httpURL)" + http_headers = { Authorization = "\(MCPClientsFixtures.authorization)" } + """ + #expect(status(httpTable, location: location, expected: http) == .current) + #expect(status(httpTable.replacingOccurrences(of: "tp_test", with: "tp_old"), location: location, expected: http) == .stale(.otherToken)) + #expect(status(httpTable.replacingOccurrences(of: "23508", with: "23509"), location: location, expected: http) == .stale(.otherURL)) + } + + @Test("HTTP entries compare the endpoint and the Authorization header, whatever the key names; a command entry is another command") + func httpEntries() { + func entry(_ fields: String) -> String { + #"{"mcpServers": {"tablepro": {\#(fields)}}}"# + } + let headers = #""headers": {"authorization": "Bearer tp_test"}"# + #expect(status(entry(#""url": "http://127.0.0.1:23508/mcp", \#(headers)"#), location: json, expected: http) == .current) + #expect(status(entry(#""serverUrl": "http://localhost:23508/mcp/", \#(headers)"#), location: json, expected: http) == .current) + #expect(status(entry(#""httpUrl": "http://127.0.0.1:23508/mcp", \#(headers)"#), location: json, expected: http) == .current) + #expect(status(entry(#""url": "https://127.0.0.1:23508/mcp", \#(headers)"#), location: json, expected: http) == .stale(.otherURL)) + #expect(status(entry(#""url": "http://example.com:23508/mcp", \#(headers)"#), location: json, expected: http) == .stale(.otherURL)) + #expect(status(entry(#""command": "/b""#), location: json, expected: http) == .stale(.otherCommand)) + #expect(status(entry(#""type": "http""#), location: json, expected: http) == .stale(.otherURL)) + #expect(status(entry(#""url": "http://127.0.0.1:23508/mcp""#), location: json, expected: http) == .stale(.otherToken)) + #expect(status(entry(#""url": "http://127.0.0.1:23508/mcp", "headers": {"Authorization": "Bearer other"}"#), location: json, expected: http) + == .stale(.otherToken)) + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientsFixtures.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientsFixtures.swift new file mode 100644 index 0000000000..fa0a5e6c1e --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPClientsFixtures.swift @@ -0,0 +1,72 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +enum MCPClientsFixtures { + static let bridge = "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp" + static let betaBridge = "/Applications/TablePro Beta.app/Contents/MacOS/tablepro-mcp" + static let httpURL = "http://127.0.0.1:23508/mcp" + static let authorization = "Bearer tp_test" + + // The catalog both apps read lives in the Rust core, six folders above this file. + static let catalogURL: URL = { + var url = URL(fileURLWithPath: #filePath) + for _ in 0..<6 { + url = url.deletingLastPathComponent() + } + return url.appendingPathComponent("core/crates/mcp/clients.json") + }() + + static func catalog() throws -> MCPClientCatalog { + try MCPClientCatalog.decode(Data(contentsOf: catalogURL)) + } + + struct MissingFixture: Error { + let id: String + } + + static func client(_ id: String) throws -> MCPClientDefinition { + guard let client = try catalog().client(id: id) else { throw MissingFixture(id: id) } + return client + } + + static func location(_ id: String, platform: MCPClientPlatform = .macos) throws -> MCPConfigLocation { + let catalog = try catalog() + guard let client = catalog.client(id: id), let location = catalog.location(for: client, platform: platform) else { + throw MissingFixture(id: id) + } + return location + } + + static func target(for platform: MCPClientPlatform) -> MCPServerTarget { + switch platform { + case .macos: return .stdio(command: bridge) + case .linux: return .http(url: httpURL, authorization: authorization) + } + } + + static func renderer(for platform: MCPClientPlatform) -> MCPTemplateRenderer { + MCPTemplateRenderer(serverName: "tablepro", target: target(for: platform)) + } + + static let stdioEntry: JSONValue = .object([ + (key: "command", value: .string(bridge)), + (key: "args", value: .array([])), + ]) + + static func hasPlaceholder(_ text: String) -> Bool { + text.range(of: #"\{[A-Za-z|]+\}"#, options: .regularExpression) != nil + } + + static func parsed(_ text: String) throws -> NSDictionary { + let object = try JSONSerialization.jsonObject(with: Data(text.utf8), options: [.json5Allowed]) + return try #require(object as? NSDictionary) + } + + static func temporaryDirectory() throws -> URL { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("TableProMCPClientsTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPConfigFileWriterTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPConfigFileWriterTests.swift new file mode 100644 index 0000000000..0958780b95 --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPConfigFileWriterTests.swift @@ -0,0 +1,203 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct MCPConfigFileWriterTests { + private let fileManager = FileManager.default + private let writer = MCPConfigFileWriter() + + private func mode(_ url: URL) throws -> Int { + try #require((try fileManager.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber)?.intValue) + } + + private func contents(_ url: URL) throws -> String { + try String(contentsOf: url, encoding: .utf8) + } + + @Test("A new file is created at 0600 with its folders, and the transform sees nil") + func createsNewFile() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("a/b/mcp.json") + var seen: [String?] = [] + let result = try writer.update(url) { text in + seen.append(text) + return "{}\n" + } + #expect(seen == [nil]) + #expect(result == MCPConfigWriteResult(backupURL: nil, created: true)) + #expect(try contents(url) == "{}\n") + #expect(try mode(url) == 0o600) + } + + @Test("Replacing keeps the file's mode and leaves the old bytes in a sibling backup") + func replacesWithBackup() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("mcp.json") + try "old".write(to: url, atomically: false, encoding: .utf8) + try fileManager.setAttributes([.posixPermissions: 0o640], ofItemAtPath: url.path) + + var seen: [String?] = [] + let result = try writer.update(url) { text in + seen.append(text) + return "new" + } + #expect(seen == ["old"]) + #expect(!result.created) + let backup = try #require(result.backupURL) + #expect(backup.lastPathComponent == "mcp.json.tablepro-backup") + #expect(try contents(url) == "new") + #expect(try contents(backup) == "old") + #expect(try mode(url) == 0o640) + #expect(try fileManager.contentsOfDirectory(atPath: directory.path).sorted() == ["mcp.json", "mcp.json.tablepro-backup"]) + + _ = try writer.update(url) { _ in "newer" } + #expect(try contents(backup) == "new") + } + + @Test("An unchanged result writes nothing") + func unchangedSkipsWrite() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("mcp.json") + try "same".write(to: url, atomically: false, encoding: .utf8) + let result = try writer.update(url) { $0 ?? "" } + #expect(result == MCPConfigWriteResult(backupURL: nil, created: false)) + #expect(try fileManager.contentsOfDirectory(atPath: directory.path) == ["mcp.json"]) + } + + @Test("Writing through a symlink replaces its target and keeps the link") + func keepsSymlink() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let dotfiles = directory.appendingPathComponent("dotfiles", isDirectory: true) + try fileManager.createDirectory(at: dotfiles, withIntermediateDirectories: true) + let real = dotfiles.appendingPathComponent("settings.json") + try "old".write(to: real, atomically: false, encoding: .utf8) + try fileManager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: real.path) + let link = directory.appendingPathComponent("settings.json") + try fileManager.createSymbolicLink(atPath: link.path, withDestinationPath: "dotfiles/settings.json") + + let result = try writer.update(link) { _ in "new" } + #expect(try fileManager.destinationOfSymbolicLink(atPath: link.path) == "dotfiles/settings.json") + #expect(try contents(real) == "new") + #expect(try contents(link) == "new") + #expect(try mode(real) == 0o600) + let backup = try #require(result.backupURL) + #expect(backup.deletingLastPathComponent().lastPathComponent == "dotfiles") + #expect(try contents(dotfiles.appendingPathComponent("settings.json.tablepro-backup")) == "old") + } + + @Test("A change made while the edit was computed is read again and the edit redone once") + func redoesOnce() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("mcp.json") + try "first".write(to: url, atomically: false, encoding: .utf8) + + var seen: [String?] = [] + _ = try writer.update(url) { text in + seen.append(text) + if seen.count == 1 { + try "concurrent".write(to: url, atomically: false, encoding: .utf8) + } + return (text ?? "") + "+edit" + } + #expect(seen == ["first", "concurrent"]) + #expect(try contents(url) == "concurrent+edit") + } + + @Test("A file that keeps changing is refused") + func changingFileRefused() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("mcp.json") + try "0".write(to: url, atomically: false, encoding: .utf8) + var calls = 0 + #expect(throws: MCPConfigWriteError.changedDuringWrite) { + try writer.update(url) { _ in + calls += 1 + try String(calls).write(to: url, atomically: false, encoding: .utf8) + return "edit" + } + } + #expect(try contents(url) == "2") + } + + @Test("A file that appears while a new one is prepared is redone against it") + func appearsDuringCreate() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("mcp.json") + var seen: [String?] = [] + let result = try writer.update(url) { text in + seen.append(text) + if text == nil { + try "theirs".write(to: url, atomically: false, encoding: .utf8) + } + return (text ?? "") + "+ours" + } + #expect(seen == [nil, "theirs"]) + #expect(!result.created) + #expect(try contents(url) == "theirs+ours") + } + + @Test("A transform error leaves the file alone") + func transformError() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("mcp.json") + try "keep".write(to: url, atomically: false, encoding: .utf8) + #expect(throws: MCPConfigEditError.duplicateKey(["mcpServers"])) { + try writer.update(url) { _ in throw MCPConfigEditError.duplicateKey(["mcpServers"]) } + } + #expect(try contents(url) == "keep") + #expect(try fileManager.contentsOfDirectory(atPath: directory.path) == ["mcp.json"]) + } + + @Test("Bytes that are not UTF-8 are refused") + func notUTF8() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("mcp.json") + try Data([0xFF, 0xFE, 0x00]).write(to: url) + #expect(throws: MCPConfigWriteError.io("notUTF8")) { + try writer.update(url) { _ in "x" } + } + } + + @Test("Upserting through the writer keeps a JSONC file's comments") + func endToEnd() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + defer { try? fileManager.removeItem(at: directory) } + let url = directory.appendingPathComponent("settings.json") + try "// Zed\n{\n \"theme\": \"One Dark\"\n}\n".write(to: url, atomically: false, encoding: .utf8) + _ = try writer.update(url) { text in + try JSONCMemberEditor.upserting("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["context_servers"], in: text ?? "") + } + let written = try contents(url) + #expect(written.hasPrefix("// Zed\n{\n \"theme\": \"One Dark\",\n \"context_servers\": {")) + #expect(try JSONCMemberEditor.member("tablepro", at: ["context_servers"], in: written) == MCPClientsFixtures.stdioEntry) + } + + @Test("A write the folder refuses carries the system's reason, not only its code") + func refusedWriteNamesReason() throws { + let directory = try MCPClientsFixtures.temporaryDirectory() + let url = directory.appendingPathComponent("mcp.json") + try "old".write(to: url, atomically: false, encoding: .utf8) + try fileManager.setAttributes([.posixPermissions: 0o500], ofItemAtPath: directory.path) + defer { + try? fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path) + try? fileManager.removeItem(at: directory) + } + do { + _ = try writer.update(url) { _ in "new" } + Issue.record("The write went through a read-only folder") + } catch MCPConfigWriteError.io(let detail) { + #expect(detail.contains("(NSCocoaErrorDomain ")) + #expect(!detail.hasPrefix("NSCocoaErrorDomain")) + } + #expect(try contents(url) == "old") + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPEntryUpdateTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPEntryUpdateTests.swift new file mode 100644 index 0000000000..58d394bd32 --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPEntryUpdateTests.swift @@ -0,0 +1,150 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct MCPEntryUpdateTests { + private struct Rendered { + let entry: JSONValue + let template: JSONValue + } + + private func rendered(_ id: String, platform: MCPClientPlatform = .macos) throws -> Rendered { + let spec = try #require(try MCPClientsFixtures.client(id).spec(for: platform)) + let template = try #require(spec.entry) + return Rendered(entry: try MCPClientsFixtures.renderer(for: platform).entry(spec), template: template) + } + + private func updatedJSON(_ id: String, _ text: String, platform: MCPClientPlatform = .macos) throws -> JSONValue? { + let update = try rendered(id, platform: platform) + let result = try JSONCMemberEditor.updating( + "tablepro", entry: update.entry, template: update.template, at: ["mcpServers"], in: text + ) + return try JSONCMemberEditor.member("tablepro", at: ["mcpServers"], in: result) + } + + private static let old = "/Volumes/Gone/TablePro.app/Contents/MacOS/tablepro-mcp" + + @Test("Update keeps Copilot CLI's tool list and the turned-off flag of Cline and Kiro") + func keepsRestrictions() throws { + let copilot = try #require(try updatedJSON("copilot-cli", """ + {"mcpServers": {"tablepro": {"type": "local", "command": "\(Self.old)", "args": [], "tools": ["list_connections"]}}} + """)) + #expect(copilot["tools"] == .array([.string("list_connections")])) + #expect(copilot["command"] == .string(MCPClientsFixtures.bridge)) + + for id in ["cline", "kiro"] { + let entry = try #require(try updatedJSON(id, """ + {"mcpServers": {"tablepro": {"command": "\(Self.old)", "args": [], "disabled": true}}} + """)) + #expect(entry["disabled"] == .bool(true)) + #expect(entry["command"] == .string(MCPClientsFixtures.bridge)) + } + } + + @Test("A member the catalog sets that the entry lacks is added, and type and args are always rewritten") + func fillsMissingMembers() throws { + let copilot = try #require(try updatedJSON("copilot-cli", """ + {"mcpServers": {"tablepro": {"type": "stdio", "command": "\(Self.old)", "args": ["--old"]}}} + """)) + #expect(copilot == .object([ + (key: "type", value: .string("local")), + (key: "command", value: .string(MCPClientsFixtures.bridge)), + (key: "args", value: .array([])), + (key: "tools", value: .array([.string("*")])), + ])) + } + + @Test("A placeholder at any depth is rewritten, and the user's own headers and keys stay") + func rewritesNestedConnectionMembers() throws { + let entry = try #require(try updatedJSON("cline", """ + {"mcpServers": {"tablepro": {"type": "sse", "url": "http://127.0.0.1:1/mcp", "timeout": 5, "disabled": true, + "headers": {"Authorization": "Bearer tp_old", "X-Trace": "1"}}}} + """, platform: .linux)) + #expect(entry["type"] == .string("streamableHttp")) + #expect(entry["url"] == .string(MCPClientsFixtures.httpURL)) + #expect(entry["headers"] == .object([ + (key: "Authorization", value: .string(MCPClientsFixtures.authorization)), + (key: "X-Trace", value: .string("1")), + ])) + #expect(entry["timeout"] == .number(5)) + #expect(entry["disabled"] == .bool(true)) + } + + @Test("An entry that reaches TablePro the other way is replaced whole, keeping only the user's choices") + func transportChangeReplacesTheEntry() throws { + let toHTTP = try updatedJSON("cursor", """ + {"mcpServers": {"tablepro": {"command": "/x", "args": [], "env": {"A": "1"}}}} + """, platform: .linux) + #expect(toHTTP == (try rendered("cursor", platform: .linux).entry)) + + let toStdio = try updatedJSON("cline", """ + {"mcpServers": {"tablepro": {"url": "http://127.0.0.1:23508/mcp", "headers": {"Authorization": "Bearer tp_x"}}}} + """) + #expect(toStdio == (try rendered("cline").entry)) + + let copilot = try updatedJSON("copilot-cli", """ + {"mcpServers": {"tablepro": {"type": "local", "command": "/x", "args": [], "env": {"A": "1"}, "tools": ["list_connections"]}}} + """, platform: .linux) + #expect(copilot == .object([ + (key: "type", value: .string("http")), + (key: "url", value: .string(MCPClientsFixtures.httpURL)), + (key: "headers", value: .object([(key: "Authorization", value: .string(MCPClientsFixtures.authorization))])), + (key: "tools", value: .array([.string("list_connections")])), + ])) + } + + @Test("A missing entry is added as rendered, and an unchanged one is left byte for byte") + func addsAndLeavesAlone() throws { + let update = try rendered("copilot-cli") + let empty = #"{"mcpServers": {}}"# + let added = try JSONCMemberEditor.updating("tablepro", entry: update.entry, template: update.template, at: ["mcpServers"], in: empty) + #expect(try JSONCMemberEditor.member("tablepro", at: ["mcpServers"], in: added) == update.entry) + #expect(try JSONCMemberEditor.updating("tablepro", entry: update.entry, template: update.template, at: ["mcpServers"], in: added) + == added) + + let current = """ + {"mcpServers": {"tablepro": {"type": "local", "command": "\(MCPClientsFixtures.bridge)", "args": [], "tools": ["a"], + "timeout": 1.0}}} + """ + #expect(try JSONCMemberEditor.updating("tablepro", entry: update.entry, template: update.template, at: ["mcpServers"], in: current) + == current) + } + + @Test("Codex's TOML table keeps a key the catalog only fills in, and its own headers") + func tomlKeepsRestrictions() throws { + let template: JSONValue = .object([ + (key: "command", value: .string("{command}")), + (key: "args", value: .array([])), + (key: "enabled", value: .bool(true)), + ]) + let entry = try MCPClientsFixtures.renderer(for: .macos).entry(template: template) + let text = "[mcp_servers.tablepro]\ncommand = \"\(Self.old)\"\nargs = []\nenabled = false\n" + let updated = try TOMLTableEditor.updating("tablepro", entry: entry, template: template, at: ["mcp_servers"], in: text) + #expect(updated == "[mcp_servers.tablepro]\ncommand = \"\(MCPClientsFixtures.bridge)\"\nargs = []\nenabled = false\n") + + let http = try rendered("codex", platform: .linux) + let table = """ + [mcp_servers.tablepro] + url = "http://127.0.0.1:1/mcp" + http_headers = { Authorization = "Bearer tp_old", X-Trace = "1" } + startup_timeout_sec = 30 + + """ + let merged = try TOMLTableEditor.updating("tablepro", entry: http.entry, template: http.template, at: ["mcp_servers"], in: table) + #expect(merged == """ + [mcp_servers.tablepro] + url = "\(MCPClientsFixtures.httpURL)" + http_headers = { Authorization = "\(MCPClientsFixtures.authorization)", X-Trace = "1" } + startup_timeout_sec = 30 + + """) + } + + @Test("A TOML table that reaches TablePro the other way is replaced with its subtables") + func tomlTransportChangeReplacesTheTable() throws { + let http = try rendered("codex", platform: .linux) + let text = "[mcp_servers.tablepro]\ncommand = \"/x\"\n\n[mcp_servers.tablepro.env]\nA = \"1\"\n" + let replaced = try TOMLTableEditor.updating("tablepro", entry: http.entry, template: http.template, at: ["mcp_servers"], in: text) + #expect(try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: replaced) == http.entry) + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPPathExpanderTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPPathExpanderTests.swift new file mode 100644 index 0000000000..9c77ba4295 --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPPathExpanderTests.swift @@ -0,0 +1,49 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct MCPPathExpanderTests { + private let home = "/Users/me" + + @Test("A leading tilde is the home folder") + func tilde() { + #expect(MCPPathExpander.expand("~/.cursor/mcp.json", home: home, environment: [:]) == "/Users/me/.cursor/mcp.json") + #expect(MCPPathExpander.expand("~", home: home, environment: [:]) == "/Users/me") + #expect(MCPPathExpander.expand("~/x", home: "/Users/me/", environment: [:]) == "/Users/me/x") + #expect(MCPPathExpander.expand("/a/~/b", home: home, environment: [:]) == "/a/~/b") + } + + @Test("A set variable wins over its default") + func variableSet() { + let path = "${XDG_CONFIG_HOME:-~/.config}/zed/settings.json" + #expect(MCPPathExpander.expand(path, home: home, environment: ["XDG_CONFIG_HOME": "/xdg"]) == "/xdg/zed/settings.json") + } + + @Test("An unset or empty variable takes its default, tilde included") + func variableDefault() { + let path = "${XDG_CONFIG_HOME:-~/.config}/zed/settings.json" + #expect(MCPPathExpander.expand(path, home: home, environment: [:]) == "/Users/me/.config/zed/settings.json") + #expect(MCPPathExpander.expand(path, home: home, environment: ["XDG_CONFIG_HOME": ""]) == "/Users/me/.config/zed/settings.json") + #expect(MCPPathExpander.expand("${CLAUDE_CONFIG_DIR:-~}/.claude.json", home: home, environment: [:]) == "/Users/me/.claude.json") + #expect(MCPPathExpander.expand("${CLAUDE_CONFIG_DIR:-~}/.claude.json", home: home, environment: ["CLAUDE_CONFIG_DIR": "/cfg"]) + == "/cfg/.claude.json") + } + + @Test("A variable without a default expands to nothing when unset") + func variableWithoutDefault() { + #expect(MCPPathExpander.expand("/a/${NOPE}/b", home: home, environment: [:]) == "/a//b") + #expect(MCPPathExpander.expand("/a/${HOME}/b", home: home, environment: ["HOME": "/h"]) == "/a//h/b") + } + + @Test("Every catalog path expands to an absolute path") + func catalogPaths() throws { + let catalog = try MCPClientsFixtures.catalog() + for set in catalog.configs.values { + for location in [set.macos, set.linux].compactMap({ $0 }) { + let expanded = MCPPathExpander.expand(location.path, home: home, environment: [:]) + #expect(expanded.hasPrefix("/"), "\(location.path)") + #expect(!expanded.contains("$") && !expanded.contains("~"), "\(location.path)") + } + } + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPTemplateRendererTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPTemplateRendererTests.swift new file mode 100644 index 0000000000..60fc852863 --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/MCPTemplateRendererTests.swift @@ -0,0 +1,179 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct MCPTemplateRendererTests { + private let stdio = MCPTemplateRenderer(serverName: "tablepro", target: .stdio(command: MCPClientsFixtures.betaBridge)) + + @Test("Cursor's config is base64 of the compact entry, percent-encoded") + func cursorDeeplink() throws { + let spec = try #require(try MCPClientsFixtures.catalog().client(id: "cursor")?.spec(for: .macos)) + guard case let .deeplink(_, template)? = spec.install.first else { + Issue.record("Cursor installs through a deeplink first") + return + } + let entry = try stdio.entry(spec) + #expect(entry.compactText == #"{"type":"stdio","command":"/Applications/TablePro Beta.app/Contents/MacOS/tablepro-mcp","args":[]}"#) + let url = try stdio.url(template, entry: entry) + #expect(url.absoluteString == "cursor://anysphere.cursor-deeplink/mcp/install?name=tablepro&config=" + + "eyJ0eXBlIjoic3RkaW8iLCJjb21tYW5kIjoiL0FwcGxpY2F0aW9ucy9UYWJsZVBybyBCZXRhLmFwcC9Db250ZW50cy9NYWNPUy90YWJsZXByby1tY3AiLCJhcmdzIjpbXX0%3D") + + let config = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "config" }?.value) + let decoded = try #require(Data(base64Encoded: config)) + #expect(String(bytes: decoded, encoding: .utf8) == entry.compactText) + } + + @Test("VS Code gets the percent-encoded entry with name first") + func vscodeDeeplink() throws { + let spec = try #require(try MCPClientsFixtures.catalog().client(id: "vscode")?.spec(for: .macos)) + guard case let .deeplink(scheme, template)? = spec.install.first else { + Issue.record("VS Code installs through a deeplink first") + return + } + let renderer = MCPClientsFixtures.renderer(for: .macos) + let url = try renderer.url(template, entry: try renderer.entry(spec)) + #expect(scheme == "vscode") + #expect(url.absoluteString == "vscode:mcp/install?" + + "%7B%22name%22%3A%22tablepro%22%2C%22type%22%3A%22stdio%22%2C%22command%22%3A%22%2FApplications%2FTablePro.app" + + "%2FContents%2FMacOS%2Ftablepro-mcp%22%2C%22args%22%3A%5B%5D%7D") + } + + @Test("entryWithName replaces a name the entry already has") + func entryWithNameReplacesName() throws { + let entry: JSONValue = .object([(key: "type", value: .string("stdio")), (key: "name", value: .string("old"))]) + let url = try stdio.url("x:{entryWithName|json|uri}", entry: entry) + #expect(url.absoluteString == "x:%7B%22name%22%3A%22tablepro%22%2C%22type%22%3A%22stdio%22%7D") + } + + @Test("Goose's deeplink percent-encodes the bridge path") + func gooseDeeplink() throws { + let spec = try #require(try MCPClientsFixtures.catalog().client(id: "goose")?.spec(for: .macos)) + guard case let .deeplink(_, template)? = spec.install.first else { + Issue.record("Goose installs through a deeplink") + return + } + let url = try stdio.url(template, entry: try stdio.entry(spec)) + #expect(url.absoluteString == "goose://extension?cmd=%2FApplications%2FTablePro%20Beta.app%2FContents%2FMacOS%2Ftablepro-mcp" + + "&id=tablepro&name=TablePro&description=TablePro%20databases") + } + + @Test("CLI arguments substitute every placeholder in place") + func cliArguments() throws { + let catalog = try MCPClientsFixtures.catalog() + let client = try #require(catalog.client(id: "claude-code")) + for (platform, expected) in [ + (MCPClientPlatform.macos, ["mcp", "add", "--scope", "user", "tablepro", "--", MCPClientsFixtures.bridge]), + (.linux, ["mcp", "add", "--scope", "user", "--transport", "http", "tablepro", MCPClientsFixtures.httpURL, + "--header", "Authorization: Bearer tp_test"]), + ] { + let spec = try #require(client.spec(for: platform)) + guard case .cli(let cli)? = spec.install.first else { + Issue.record("claude-code installs through its CLI on \(platform)") + continue + } + let renderer = MCPClientsFixtures.renderer(for: platform) + #expect(try renderer.arguments(cli.add, entry: try renderer.entry(spec)) == expected) + } + } + + @Test("Command lines quote only the words that need it") + func commandLineQuoting() { + let line = stdio.commandLine(binary: "claude", arguments: ["mcp", "add", "--scope", "user", "tablepro", "--", MCPClientsFixtures.betaBridge]) + #expect(line == "claude mcp add --scope user tablepro -- '/Applications/TablePro Beta.app/Contents/MacOS/tablepro-mcp'") + #expect(stdio.commandLine(binary: "x", arguments: ["it's", "", "a=b,c:d@e%f+g", "Authorization: Bearer t", "~/x", "$HOME"]) + == #"x 'it'\''s' '' a=b,c:d@e%f+g 'Authorization: Bearer t' '~/x' '$HOME'"#) + } + + @Test("Entries keep numbers as integers and booleans as booleans") + func scalarRendering() throws { + let spec = try #require(try MCPClientsFixtures.catalog().client(id: "goose")?.spec(for: .macos)) + let entry = try stdio.entry(spec) + #expect(entry.compactText.contains(#""enabled":true"#)) + #expect(entry.compactText.contains(#""timeout":300"#)) + #expect(entry["cmd"] == .string(MCPClientsFixtures.betaBridge)) + } + + @Test("A placeholder the target cannot fill throws") + func unavailablePlaceholder() { + let http = MCPTemplateRenderer(serverName: "tablepro", target: .http(url: "u", authorization: "a")) + #expect(throws: MCPTemplateError.unavailablePlaceholder("command")) { + try http.entry(template: .object([(key: "command", value: .string("{command}"))])) + } + #expect(throws: MCPTemplateError.unavailablePlaceholder("url")) { + try stdio.arguments(["{url}"], entry: .null) + } + #expect(throws: MCPTemplateError.unknownPlaceholder("bridge")) { + try stdio.arguments(["{bridge}"], entry: .null) + } + #expect(throws: MCPTemplateError.unknownFilter("hex")) { + try stdio.arguments(["{name|hex}"], entry: .null) + } + #expect(throws: MCPTemplateError.unknownFilter("base64")) { + try stdio.arguments(["{entry|base64}"], entry: .null) + } + } + + @Test("A spec without an entry throws") + func missingEntry() throws { + let spec = try #require(try MCPClientsFixtures.catalog().client(id: "chatgpt-classic")?.spec(for: .macos)) + #expect(throws: MCPTemplateError.missingEntry) { + try stdio.entry(spec) + } + } + + @Test("The JSON snippet nests the entry under the key path, two-space indented") + func jsonSnippet() { + let location = MCPConfigLocation(path: "~/.cursor/mcp.json", format: .json, keyPath: ["mcpServers"]) + #expect(stdio.snippet(for: location, entry: MCPClientsFixtures.stdioEntry) == """ + { + "mcpServers": { + "tablepro": { + "command": "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp", + "args": [] + } + } + } + """) + #expect(stdio.snippet(for: nil, entry: .object([(key: "command", value: .string("/b"))])) == """ + { + "tablepro": { + "command": "/b" + } + } + """) + } + + @Test("The TOML snippet is the server's table") + func tomlSnippet() { + let location = MCPConfigLocation(path: "~/.codex/config.toml", format: .toml, keyPath: ["mcp_servers"]) + let entry: JSONValue = .object([ + (key: "url", value: .string("http://127.0.0.1:23508/mcp")), + (key: "http_headers", value: .object([(key: "Authorization", value: .string("Bearer t"))])), + ]) + #expect(stdio.snippet(for: location, entry: entry) == """ + [mcp_servers.tablepro] + url = "http://127.0.0.1:23508/mcp" + http_headers = { Authorization = "Bearer t" } + """) + } + + @Test("The YAML snippet nests block mappings and quotes strings") + func yamlSnippet() { + let location = MCPConfigLocation(path: "~/.config/goose/config.yaml", format: .yaml, keyPath: ["extensions"], isWritable: false) + let entry: JSONValue = .object([ + (key: "cmd", value: .string("/b c")), + (key: "args", value: .array([])), + (key: "tools", value: .array([.string("*")])), + (key: "timeout", value: .number(300)), + ]) + #expect(stdio.snippet(for: location, entry: entry) == """ + extensions: + tablepro: + cmd: "/b c" + args: [] + tools: + - "*" + timeout: 300 + """) + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/TOMLTableEditorTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/TOMLTableEditorTests.swift new file mode 100644 index 0000000000..76c8194594 --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPClientsTests/TOMLTableEditorTests.swift @@ -0,0 +1,310 @@ +import Foundation +@testable import TableProMCPClients +import Testing + +struct TOMLTableEditorTests { + private let entry: JSONValue = .object([(key: "command", value: .string("/b"))]) + + private let codexConfig = """ + # Codex settings + model = "gpt-5" + approval_policy = "on-request" + + [mcp_servers.node_repl] + command = "/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node_repl" # keep this + args = [] + + [profiles.fast] + model = "gpt-5-mini" + + """ + + @Test("A missing server is appended after a blank line, and removing it restores the file") + func appendAndRemove() throws { + let result = try TOMLTableEditor.upserting("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcp_servers"], in: codexConfig) + #expect(result == codexConfig + """ + + [mcp_servers.tablepro] + command = "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp" + args = [] + + """) + #expect(try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: result) == MCPClientsFixtures.stdioEntry) + #expect(try TOMLTableEditor.removing("tablepro", at: ["mcp_servers"], in: result) == codexConfig) + } + + @Test("An existing table and its subtables are replaced in place; other bytes stay") + func replaceInPlace() throws { + let text = """ + model = "gpt-5" + + [mcp_servers.tablepro] + command = "/old" # old + args = ["--x"] + enabled = false + + [mcp_servers.tablepro.env] + TOKEN = "x" + + [mcp_servers.other] + command = "o" # inline comment survives + + """ + #expect(try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: text) == .object([ + (key: "command", value: .string("/old")), + (key: "args", value: .array([.string("--x")])), + (key: "enabled", value: .bool(false)), + (key: "env", value: .object([(key: "TOKEN", value: .string("x"))])), + ])) + #expect(try TOMLTableEditor.upserting("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcp_servers"], in: text) == """ + model = "gpt-5" + + [mcp_servers.tablepro] + command = "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp" + args = [] + + [mcp_servers.other] + command = "o" # inline comment survives + + """) + #expect(try TOMLTableEditor.removing("tablepro", at: ["mcp_servers"], in: text) == """ + model = "gpt-5" + + [mcp_servers.other] + command = "o" # inline comment survives + + """) + } + + @Test("Inline tables, dotted keys inside the table and numbers are read") + func readsHTTPServer() throws { + let text = """ + [mcp_servers.tablepro] + url = "http://127.0.0.1:23508/mcp" + http_headers = { Authorization = "Bearer t" } + startup_timeout_sec = 1_000 + mask = 0xff + ratio = 0.5 + env.A = '1' + created = 1979-05-27 07:32:00Z + """ + #expect(try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: text) == .object([ + (key: "url", value: .string("http://127.0.0.1:23508/mcp")), + (key: "http_headers", value: .object([(key: "Authorization", value: .string("Bearer t"))])), + (key: "startup_timeout_sec", value: .number(1_000)), + (key: "mask", value: .number(255)), + (key: "ratio", value: .number(0.5)), + (key: "env", value: .object([(key: "A", value: .string("1"))])), + (key: "created", value: .string("1979-05-27 07:32:00Z")), + ])) + } + + @Test("Nested values render as inline tables and arrays") + func rendersHTTPEntry() throws { + let value: JSONValue = .object([ + (key: "url", value: .string("http://127.0.0.1:23508/mcp")), + (key: "http_headers", value: .object([(key: "Authorization", value: .string("Bearer t"))])), + (key: "env", value: .object([])), + (key: "args", value: .array([.string("a b"), .number(2), .bool(true)])), + ]) + let result = try TOMLTableEditor.upserting("tablepro", value: value, at: ["mcp_servers"], in: "") + #expect(result == """ + [mcp_servers.tablepro] + url = "http://127.0.0.1:23508/mcp" + http_headers = { Authorization = "Bearer t" } + env = {} + args = ["a b", 2, true] + + """) + #expect(try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: result) == value) + } + + @Test("Escapes round trip and odd keys are quoted") + func escapes() throws { + let value: JSONValue = .object([ + (key: "command", value: .string("/Apps/Tab\"le\\Pro é\n\u{1}\u{7F}")), + (key: "odd key", value: .string("x")), + ]) + let result = try TOMLTableEditor.upserting("my server", value: value, at: ["mcp_servers"], in: "") + #expect(result.hasPrefix(#"[mcp_servers."my server"]"#)) + #expect(result.contains(#""odd key" = "x""#)) + #expect(try TOMLTableEditor.member("my server", at: ["mcp_servers"], in: result) == value) + } + + @Test("Headers and arrays inside strings are not taken for tables") + func lookalikesInStrings() throws { + let text = """ + notes = \"\"\" + [mcp_servers.tablepro] + not a header + \"\"\" + args = [ + "[x]", # comment + 'y', + ] + literal = ''' + [mcp_servers.tablepro] + ''' + + """ + #expect(try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: text) == nil) + let result = try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: text) + #expect(result == text + "\n[mcp_servers.tablepro]\ncommand = \"/b\"\n") + } + + @Test("Servers defined with dotted keys elsewhere do not stop a table from being added") + func otherDottedServers() throws { + let text = "mcp_servers.other.command = \"o\"\n" + let result = try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: text) + #expect(result == text + "\n[mcp_servers.tablepro]\ncommand = \"/b\"\n") + } + + @Test("A server defined any other way is refused", arguments: [ + "[mcp_servers]\ntablepro.command = \"x\"\n", + "[mcp_servers]\ntablepro = { command = \"x\" }\n", + "[mcp_servers]\n\"tablepro\" = { command = \"x\" }\n", + "mcp_servers.tablepro.command = \"x\"\n", + "mcp_servers = { tablepro = { command = \"x\" } }\n", + "[[mcp_servers.tablepro]]\ncommand = \"x\"\n", + "[[mcp_servers]]\nname = \"x\"\n", + ]) + func unsupportedShapes(text: String) { + #expect(throws: MCPConfigEditError.unsupportedShape) { + try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: text) + } + #expect(throws: MCPConfigEditError.unsupportedShape) { + try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: text) + } + #expect(throws: MCPConfigEditError.unsupportedShape) { + try TOMLTableEditor.removing("tablepro", at: ["mcp_servers"], in: text) + } + } + + @Test("An inline mcp_servers without this server reads as missing but cannot take a table") + func inlineContainer() throws { + let text = "mcp_servers = { other = { command = \"o\" } }\n" + #expect(try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: text) == nil) + #expect(try TOMLTableEditor.removing("tablepro", at: ["mcp_servers"], in: text) == text) + #expect(throws: MCPConfigEditError.unsupportedShape) { + try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: text) + } + } + + @Test("The same table twice is refused") + func duplicateTable() { + let text = "[mcp_servers.tablepro]\ncommand = \"a\"\n[mcp_servers.tablepro]\ncommand = \"b\"\n" + #expect(throws: MCPConfigEditError.duplicateKey(["mcp_servers", "tablepro"])) { + try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: text) + } + } + + @Test("CRLF files and files without a final line break get matching line breaks") + func lineBreaks() throws { + #expect(try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: "model = \"x\"\r\n") + == "model = \"x\"\r\n\r\n[mcp_servers.tablepro]\r\ncommand = \"/b\"\r\n") + #expect(try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: "model = \"x\"") + == "model = \"x\"\n\n[mcp_servers.tablepro]\ncommand = \"/b\"\n") + #expect(try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: "[mcp_servers.tablepro]\ncommand = \"/old\"") + == "[mcp_servers.tablepro]\ncommand = \"/b\"") + #expect(try TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: "") == "[mcp_servers.tablepro]\ncommand = \"/b\"\n") + #expect(try TOMLTableEditor.removing("tablepro", at: ["mcp_servers"], in: "") == "") + } + + @Test("A null value cannot be written") + func nullRefused() { + #expect(throws: MCPConfigEditError.unsupportedShape) { + try TOMLTableEditor.upserting("tablepro", value: .object([(key: "x", value: .null)]), at: ["mcp_servers"], in: "") + } + } + + @Test("Broken syntax is refused", arguments: [ + "model = \n", "[mcp_servers\n", "a = \"unterminated\n", "a = 1 b = 2\n", "a = [1, 2\n", "a = bare\n", + ]) + func invalidSyntax(text: String) { + #expect(throws: MCPConfigEditError.invalidSyntax) { + try TOMLTableEditor.member("tablepro", at: ["mcp_servers"], in: text) + } + } + + @Test("Merging rewrites only the keys the entry names and keeps every other key and subtable") + func mergeKeepsUserKeys() throws { + let text = """ + model = "gpt-5" + + [mcp_servers.tablepro] + command = "/old" # old + args = ["--x"] + enabled_tools = ["list_connections"] + startup_timeout_sec = 30 + + [mcp_servers.tablepro.env] + TOKEN = "x" + + [mcp_servers.other] + command = "o" + + """ + let result = try TOMLTableEditor.merging("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcp_servers"], in: text) + #expect(result == """ + model = "gpt-5" + + [mcp_servers.tablepro] + command = "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp" + args = [] + enabled_tools = ["list_connections"] + startup_timeout_sec = 30 + + [mcp_servers.tablepro.env] + TOKEN = "x" + + [mcp_servers.other] + command = "o" + + """) + #expect(try TOMLTableEditor.merging("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcp_servers"], in: result) == result) + } + + @Test("Merging adds a missing key after the table's last key, keeping CRLF and a missing final line break") + func mergeAddsKeys() throws { + let text = "[mcp_servers.tablepro]\r\ncommand = \"/old\"\r\nenabled = false\r\n\r\n[other]\r\nx = 1\r\n" + #expect(try TOMLTableEditor.merging("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcp_servers"], in: text) + == "[mcp_servers.tablepro]\r\ncommand = \"/Applications/TablePro.app/Contents/MacOS/tablepro-mcp\"\r\nenabled = false\r\n" + + "args = []\r\n\r\n[other]\r\nx = 1\r\n") + #expect(try TOMLTableEditor.merging("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcp_servers"], in: "[mcp_servers.tablepro]\nx = 1") + == "[mcp_servers.tablepro]\nx = 1\ncommand = \"/Applications/TablePro.app/Contents/MacOS/tablepro-mcp\"\nargs = []\n") + } + + @Test("A table the entry names is merged into, and rewritten inline only when its contents change") + func mergeNestedTables() throws { + let text = "[mcp_servers.tablepro]\ncommand = \"/b\"\n\n[mcp_servers.tablepro.env]\nTOKEN = \"x\"\n\n[profiles.fast]\nmodel = \"m\"\n" + let keepsEnv: JSONValue = .object([(key: "command", value: .string("/b")), (key: "env", value: .object([]))]) + #expect(try TOMLTableEditor.merging("tablepro", value: keepsEnv, at: ["mcp_servers"], in: text) == text) + + let addsToEnv: JSONValue = .object([(key: "env", value: .object([(key: "NEW", value: .string("y"))]))]) + let merged = try TOMLTableEditor.merging("tablepro", value: addsToEnv, at: ["mcp_servers"], in: text) + #expect(merged == "[mcp_servers.tablepro]\ncommand = \"/b\"\nenv = { TOKEN = \"x\", NEW = \"y\" }\n\n[profiles.fast]\nmodel = \"m\"\n") + + let dotted = "[mcp_servers.tablepro]\nenv.A = \"1\"\ncommand = \"/b\"\nenv.B = \"2\"\n" + #expect(try TOMLTableEditor.merging("tablepro", value: addsToEnv, at: ["mcp_servers"], in: dotted) + == "[mcp_servers.tablepro]\nenv = { A = \"1\", B = \"2\", NEW = \"y\" }\ncommand = \"/b\"\n") + } + + @Test("Merging into a server that has only subtables adds its table at the end") + func mergeWithoutMainTable() throws { + let text = "[mcp_servers.tablepro.env]\nTOKEN = \"x\"\n" + let result = try TOMLTableEditor.merging("tablepro", value: MCPClientsFixtures.stdioEntry, at: ["mcp_servers"], in: text) + #expect(result == text + "\n[mcp_servers.tablepro]\ncommand = \"/Applications/TablePro.app/Contents/MacOS/tablepro-mcp\"\nargs = []\n") + } + + @Test("Merging a missing server is the same as adding it, and other shapes are still refused") + func mergeFallsBack() throws { + #expect(try TOMLTableEditor.merging("tablepro", value: entry, at: ["mcp_servers"], in: codexConfig) + == TOMLTableEditor.upserting("tablepro", value: entry, at: ["mcp_servers"], in: codexConfig)) + #expect(throws: MCPConfigEditError.unsupportedShape) { + try TOMLTableEditor.merging("tablepro", value: entry, at: ["mcp_servers"], in: "[mcp_servers]\ntablepro = { command = \"x\" }\n") + } + #expect(throws: MCPConfigEditError.unsupportedShape) { + try TOMLTableEditor.merging("tablepro", value: entry, at: ["mcp_servers"], in: "mcp_servers = { other = {} }\n") + } + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Bridge/BridgeProxyStampTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Bridge/BridgeProxyStampTests.swift new file mode 100644 index 0000000000..28f7f2fddc --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Bridge/BridgeProxyStampTests.swift @@ -0,0 +1,97 @@ +import Darwin +import Foundation +@testable import TableProMCP +import TableProMCPTestSupport +import TableProTestSupport +import Testing + +struct BridgeProxyStampTests { + private static let discovery = BridgeDiscovery( + supportedVersions: MCPProtocolVersion.supportedRawValues, + capabilities: .object([:]), + serverInfo: nil, + instructions: nil, + instanceId: "instance-1" + ) + + private static func app() async throws -> MockHttpServer { + let server = MockHttpServer() + await server.setHandler { request in + guard case .request(let rpc)? = try? JsonRpcCodec.decode(request.body) else { + return MockHttpResponse(status: 202, headers: [], body: Data()) + } + let body = try? JsonRpcCodec.encode(.successResponse(JsonRpcSuccessResponse(id: rpc.id, result: .object([:])))) + return MockHttpResponse(status: 200, headers: [("Content-Type", "application/json")], body: body ?? Data()) + } + try await server.start() + return server + } + + private static func forwarded(_ lines: [String]) async throws -> [Data] { + let server = try await app() + let credentials = MCPUpstreamCredentials(socketPath: server.socketPath, serverPID: getpid(), bearerToken: "stamp-token") + let upstream = MCPStreamableHttpClientTransport( + configuration: MCPStreamableHttpClientConfiguration(requestTimeout: .seconds(5)), + credentialsProvider: MCPCachedUpstreamCredentialsProvider(initial: credentials) { credentials }, + errorLogger: nil + ) + let hostToBridge = Pipe() + let bridgeToHost = Pipe() + let proxy = BridgeProxy( + upstream: upstream, + discovery: discovery, + logger: RecordingBridgeLogger(), + stdin: hostToBridge.fileHandleForReading, + stdout: bridgeToHost.fileHandleForWriting + ) + let run = Task { await proxy.run() } + for line in lines { + try hostToBridge.fileHandleForWriting.write(contentsOf: Data((line + "\n").utf8)) + } + var waitFailure: (any Error)? + do { + try await waitUntil { await server.requests.count == lines.count } + } catch { + waitFailure = error + } + try? hostToBridge.fileHandleForWriting.close() + run.cancel() + await run.value + try? bridgeToHost.fileHandleForWriting.close() + let bodies = await server.requests.map(\.body) + await server.stop() + if let waitFailure { throw waitFailure } + return bodies + } + + private static func method(of body: Data) throws -> String? { + try JSONDecoder().decode(JsonValue.self, from: body)["method"]?.stringValue + } + + private static func instance(in body: Data) throws -> String? { + try JSONDecoder().decode(JsonValue.self, from: body)["params"]?["_meta"]?[MCPMetaKeys.bridgeInstance]?.stringValue + } + + @Test("A modern request and a cancellation sent without metadata carry one bridge instance", .timeLimit(.minutes(1))) + func cancellationMeetsItsModernRequest() async throws { + let request = #""" + {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_connections","_meta":\# + {"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},\# + "io.modelcontextprotocol/clientInfo":{"name":"claude-code","version":"2.0.0"}}}} + """# + let cancel = #"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":3}}"# + + let bodies = try await Self.forwarded([request, cancel]) + + // The two posts race, so each body is told apart by its method. + let call = try #require(try bodies.first { try Self.method(of: $0) == "tools/call" }) + let cancelled = try #require(try bodies.first { try Self.method(of: $0) == "notifications/cancelled" }) + let requestInstance = try #require(try Self.instance(in: call)) + #expect(try Self.instance(in: cancelled) == requestInstance) + let stamped = request.replacingOccurrences( + of: #""_meta":{"#, + with: #""_meta":{"\#(MCPMetaKeys.bridgeInstance)":"\#(requestInstance)","# + ) + #expect(String(bytes: call, encoding: .utf8) == stamped, "A modern request gains only the bridge instance") + } +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPTests/CommandLine/CLIPairingTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/CommandLine/CLIPairingTests.swift index 4751d89d9c..879a11987f 100644 --- a/apple/Packages/TableProMacCore/Tests/TableProMCPTests/CommandLine/CLIPairingTests.swift +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/CommandLine/CLIPairingTests.swift @@ -41,6 +41,10 @@ struct CLIPairingTests { requestTarget: "\(path)?error=access_denied&error_description=user_denied&state=s1", state: "s1" ) == .denied) + #expect(CLIPairingCallback.parse( + requestTarget: "\(path)?error=server_error&error_description=token_not_issued&state=s1", + state: "s1" + ) == .failed) #expect(CLIPairingCallback.parse(requestTarget: "\(path)?code=abc&state=other", state: "s1") == .ignored) #expect(CLIPairingCallback.parse(requestTarget: "/favicon.ico", state: "s1") == .ignored) #expect(CLIPairingCallback.parse(requestTarget: "\(path)?state=s1", state: "s1") == .ignored) diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Lifecycle/MCPStartRefusalTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Lifecycle/MCPStartRefusalTests.swift new file mode 100644 index 0000000000..009442cffe --- /dev/null +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Lifecycle/MCPStartRefusalTests.swift @@ -0,0 +1,73 @@ +import Foundation +@testable import TableProMCP +import Testing + +struct MCPStartRefusalTests { + private let directory: URL + + init() throws { + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("mcp-refusal-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path) + } + + @Test("A refusal written before refusals carried a reason reads as turned off") + func refusalWithoutAReasonIsTurnedOff() throws { + let refusal = try MCPHandshakeCoding.decoder().decode( + MCPStartRefusal.self, + from: Data(#"{"pid":1,"refusedAt":1000.5}"#.utf8) + ) + + #expect(refusal.reason == .turnedOff) + } + + @Test("A reason this build does not know still says the server is not coming up") + func unknownReasonIsAFailedStart() throws { + let refusal = try MCPHandshakeCoding.decoder().decode( + MCPStartRefusal.self, + from: Data(#"{"pid":1,"refusedAt":1000.5,"reason":"somethingNewer"}"#.utf8) + ) + + #expect(refusal.reason == .failedToStart) + } + + @Test("A failed start keeps its reason through the file") + func failedStartRoundTrips() throws { + let written = MCPStartRefusal(pid: 7, refusedAt: Date(timeIntervalSince1970: 1_000.25), reason: .failedToStart) + + let read = try MCPHandshakeCoding.decoder().decode( + MCPStartRefusal.self, + from: MCPHandshakeCoding.encoder().encode(written) + ) + + #expect(read == written) + } + + @Test("The bridge names a failed start instead of waiting out the timeout") + func bridgeReportsAFailedStart() async throws { + let directory = directory + let acquirer = MCPHandshakeAcquirer( + logger: SilentLogger(), + supportDirectory: directory, + pollTimeout: .seconds(30), + launchHostApp: { _ in + let refusal = MCPStartRefusal(pid: 1, refusedAt: Date(), reason: .failedToStart) + try MCPHandshakeCoding.encoder().encode(refusal).write(to: MCPHandshakeLocation.refusalFile(in: directory)) + } + ) + + let started = ContinuousClock().now + await #expect(throws: MCPHandshakeAcquisitionError.serverFailedToStart) { + _ = try await acquirer.acquire() + } + #expect(ContinuousClock().now - started < .seconds(5)) + let message = MCPHandshakeAcquisitionError.serverFailedToStart.localizedDescription + #expect(message.contains("Settings > MCP")) + #expect(!message.contains("not running")) + } +} + +private struct SilentLogger: MCPBridgeLogger { + func log(_ level: MCPBridgeLogLevel, _ message: String) {} +} diff --git a/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Protocol/MCPInflightRegistryTests.swift b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Protocol/MCPInflightRegistryTests.swift index 53f45b3391..d217c57f36 100644 --- a/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Protocol/MCPInflightRegistryTests.swift +++ b/apple/Packages/TableProMacCore/Tests/TableProMCPTests/Protocol/MCPInflightRegistryTests.swift @@ -251,4 +251,126 @@ struct MCPInflightRegistryTests { #expect(key.requestId == .string("abc")) #expect(key == MCPInflightKey(clientFingerprint: "alice", requestId: .string("abc"))) } + + @Test("Two stdio clients on the bridge credential keep one request id apart") + func stdioClientsSharingTheBridgeCredentialAreTwoEntries() async { + let registry = MCPInflightRegistry() + let cursorToken = MCPCancellationToken() + let zedToken = MCPCancellationToken() + let cursorKey = MCPInflightKey(client: Self.stdioClient("cursor-vscode"), requestId: .number(1)) + let zedKey = MCPInflightKey(client: Self.stdioClient("Zed"), requestId: .number(1)) + #expect(cursorKey != zedKey) + + #expect(await registry.register(key: cursorKey, token: cursorToken, tokenId: nil, method: "tools/call", startedAt: .now)) + #expect(await registry.register(key: zedKey, token: zedToken, tokenId: nil, method: "tools/call", startedAt: .now)) + #expect(await registry.count() == 2) + + #expect(await registry.cancel(key: zedKey, reason: .clientRequested(nil))) + #expect(await zedToken.isCancelled) + #expect(!(await cursorToken.isCancelled)) + + await registry.remove(key: zedKey, token: zedToken) + #expect(await registry.contains(key: cursorKey)) + } + + @Test("A token one client holds keys its requests by the token alone") + func ownTokenKeysByTheTokenAlone() { + let identity = MCPClientIdentity( + clientName: "Raycast", + clientVersion: "1.0", + tokenId: alice.tokenId, + tokenName: "Raycast", + principalFingerprint: alice.tokenFingerprint, + address: .loopback, + transport: .http + ) + #expect(MCPInflightKey(client: identity, requestId: .number(7)) == MCPInflightKey(principal: alice, requestId: .number(7))) + } + + @Test("A stdio cancellation sent with the renewed bridge credential finds the request the old one started") + func stdioCancellationCrossesACredentialRotation() async { + let registry = MCPInflightRegistry() + let token = MCPCancellationToken() + let started = MCPInflightKey(client: Self.stdioClient("claude-code", fingerprint: "a"), requestId: .number(5)) + let cancelled = MCPInflightKey(client: Self.stdioClient("claude-code", fingerprint: "b"), requestId: .number(5)) + + await registry.register(key: started, token: token, tokenId: nil, method: "tools/call", startedAt: .now) + + #expect(await registry.cancel(key: cancelled, reason: .clientRequested(nil))) + #expect(await token.isCancelled) + } + + @Test("Two sessions of one stdio client keep one request id apart, and ending the client ends every session") + func sessionsOfOneStdioClientAreSeparateEntries() async { + let registry = MCPInflightRegistry() + let client = Self.stdioClient("claude-code") + let tokens = [MCPCancellationToken(), MCPCancellationToken(), MCPCancellationToken()] + let keys = ["one", "two", "three"].map { MCPInflightKey(client: client, bridgeInstance: $0, requestId: .number(1)) } + + for (key, token) in zip(keys, tokens) { + #expect(await registry.register(key: key, token: token, tokenId: nil, clientId: client.id, method: "tools/call", startedAt: .now)) + } + #expect(await registry.count() == 3) + + #expect(await registry.cancel(key: keys[2], reason: .clientRequested(nil))) + #expect(!(await tokens[0].isCancelled)) + #expect(!(await tokens[1].isCancelled)) + + #expect(await registry.cancelAll(matchingClientId: client.id, reason: .clientDisconnected) == 2) + #expect(await tokens[0].isCancelled) + #expect(await tokens[1].isCancelled) + } + + @Test("A stdio cancellation without clientInfo stops the request that had it, by bridge instance and request id") + func stdioCancellationWithoutClientInfo() async { + let registry = MCPInflightRegistry() + let token = MCPCancellationToken() + let named = Self.stdioClient("claude-code") + let unnamed = MCPClientIdentity( + clientName: MCPClientIdentity.unknownClientName, + clientVersion: nil, + tokenId: UUID(), + tokenName: "__stdio_bridge__", + principalFingerprint: "bridge", + address: .localSocket, + transport: .stdioBridge + ) + let started = MCPInflightKey(client: named, bridgeInstance: "one", requestId: .number(3)) + await registry.register(key: started, token: token, tokenId: nil, clientId: named.id, method: "tools/call", startedAt: .now) + + #expect(!(await registry.cancel(key: MCPInflightKey(client: unnamed, bridgeInstance: "two", requestId: .number(3)), reason: .clientRequested(nil)))) + #expect(await registry.cancel(key: MCPInflightKey(client: unnamed, bridgeInstance: "one", requestId: .number(3)), reason: .clientRequested(nil))) + #expect(await token.isCancelled) + #expect(MCPInflightKey(bridgeInstance: "one", requestId: .number(3)) == started) + } + + @Test("A client on a token of its own cannot pick a bridge instance") + func ownTokenIgnoresTheBridgeInstance() { + let identity = MCPClientIdentity( + clientName: "Raycast", + clientVersion: "1.0", + tokenId: alice.tokenId, + tokenName: "Raycast", + principalFingerprint: alice.tokenFingerprint, + address: .loopback, + transport: .http + ) + #expect( + MCPInflightKey(client: identity, bridgeInstance: "forged", requestId: .number(7)) + == MCPInflightKey(principal: alice, requestId: .number(7)) + ) + } + + private static func stdioClient(_ name: String, fingerprint: String = "bridge") -> MCPClientIdentity { + MCPClientIdentity( + clientName: name, + clientInfoName: name, + clientVersion: "1.0", + tokenId: UUID(), + tokenName: "__stdio_bridge__", + principalFingerprint: fingerprint, + address: .localSocket, + transport: .stdioBridge + ) + } } diff --git a/apple/TablePro/Assets.xcassets/claude-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/claude-icon.imageset/Contents.json new file mode 100644 index 0000000000..9eea838495 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/claude-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "claude.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/claude-icon.imageset/claude.svg b/apple/TablePro/Assets.xcassets/claude-icon.imageset/claude.svg new file mode 100644 index 0000000000..1beee86121 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/claude-icon.imageset/claude.svg @@ -0,0 +1 @@ +Claude \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/claudecode-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/claudecode-icon.imageset/Contents.json new file mode 100644 index 0000000000..a339b05512 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/claudecode-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "claudecode.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/claudecode-icon.imageset/claudecode.svg b/apple/TablePro/Assets.xcassets/claudecode-icon.imageset/claudecode.svg new file mode 100644 index 0000000000..9b0061b760 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/claudecode-icon.imageset/claudecode.svg @@ -0,0 +1 @@ +Claude Code \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/cline-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/cline-icon.imageset/Contents.json new file mode 100644 index 0000000000..6ec74c460e --- /dev/null +++ b/apple/TablePro/Assets.xcassets/cline-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "cline.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/cline-icon.imageset/cline.svg b/apple/TablePro/Assets.xcassets/cline-icon.imageset/cline.svg new file mode 100644 index 0000000000..0fe6a51fd8 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/cline-icon.imageset/cline.svg @@ -0,0 +1 @@ +Cline \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/cursor-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/cursor-icon.imageset/Contents.json new file mode 100644 index 0000000000..fe93e63c45 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/cursor-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "cursor.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/cursor-icon.imageset/cursor.svg b/apple/TablePro/Assets.xcassets/cursor-icon.imageset/cursor.svg new file mode 100644 index 0000000000..61303fbcc3 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/cursor-icon.imageset/cursor.svg @@ -0,0 +1 @@ +Cursor \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/githubcopilot-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/githubcopilot-icon.imageset/Contents.json new file mode 100644 index 0000000000..c9eed271be --- /dev/null +++ b/apple/TablePro/Assets.xcassets/githubcopilot-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "githubcopilot.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/githubcopilot-icon.imageset/githubcopilot.svg b/apple/TablePro/Assets.xcassets/githubcopilot-icon.imageset/githubcopilot.svg new file mode 100644 index 0000000000..f064947d1d --- /dev/null +++ b/apple/TablePro/Assets.xcassets/githubcopilot-icon.imageset/githubcopilot.svg @@ -0,0 +1 @@ +GitHub Copilot \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/googlegemini-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/googlegemini-icon.imageset/Contents.json new file mode 100644 index 0000000000..2681885282 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/googlegemini-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "googlegemini.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/googlegemini-icon.imageset/googlegemini.svg b/apple/TablePro/Assets.xcassets/googlegemini-icon.imageset/googlegemini.svg new file mode 100644 index 0000000000..765adb0887 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/googlegemini-icon.imageset/googlegemini.svg @@ -0,0 +1 @@ +Google Gemini \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/goose-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/goose-icon.imageset/Contents.json new file mode 100644 index 0000000000..7b8ae75508 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/goose-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "goose.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/goose-icon.imageset/goose.svg b/apple/TablePro/Assets.xcassets/goose-icon.imageset/goose.svg new file mode 100644 index 0000000000..94152e79d3 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/goose-icon.imageset/goose.svg @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/apple/TablePro/Assets.xcassets/jetbrains-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/jetbrains-icon.imageset/Contents.json new file mode 100644 index 0000000000..039658a592 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/jetbrains-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "jetbrains.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/jetbrains-icon.imageset/jetbrains.svg b/apple/TablePro/Assets.xcassets/jetbrains-icon.imageset/jetbrains.svg new file mode 100644 index 0000000000..2f669ff6a4 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/jetbrains-icon.imageset/jetbrains.svg @@ -0,0 +1 @@ +JetBrains \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/kiro-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/kiro-icon.imageset/Contents.json new file mode 100644 index 0000000000..2a0a6a2951 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/kiro-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "kiro.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/apple/TablePro/Assets.xcassets/kiro-icon.imageset/kiro.svg b/apple/TablePro/Assets.xcassets/kiro-icon.imageset/kiro.svg new file mode 100644 index 0000000000..5fe3cf6847 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/kiro-icon.imageset/kiro.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/apple/TablePro/Assets.xcassets/llamacpp-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/llamacpp-icon.imageset/Contents.json new file mode 100644 index 0000000000..95261ea879 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/llamacpp-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "llamacpp.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/llamacpp-icon.imageset/llamacpp.svg b/apple/TablePro/Assets.xcassets/llamacpp-icon.imageset/llamacpp.svg new file mode 100644 index 0000000000..05424790af --- /dev/null +++ b/apple/TablePro/Assets.xcassets/llamacpp-icon.imageset/llamacpp.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/apple/TablePro/Assets.xcassets/lmstudio-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/lmstudio-icon.imageset/Contents.json new file mode 100644 index 0000000000..12c3071e78 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/lmstudio-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "lmstudio.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/lmstudio-icon.imageset/lmstudio.svg b/apple/TablePro/Assets.xcassets/lmstudio-icon.imageset/lmstudio.svg new file mode 100644 index 0000000000..e324916aaf --- /dev/null +++ b/apple/TablePro/Assets.xcassets/lmstudio-icon.imageset/lmstudio.svg @@ -0,0 +1 @@ +LM Studio \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/meta-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/meta-icon.imageset/Contents.json new file mode 100644 index 0000000000..7eaa0ac309 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/meta-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "meta.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/meta-icon.imageset/meta.svg b/apple/TablePro/Assets.xcassets/meta-icon.imageset/meta.svg new file mode 100644 index 0000000000..d9a1631d1a --- /dev/null +++ b/apple/TablePro/Assets.xcassets/meta-icon.imageset/meta.svg @@ -0,0 +1 @@ +Meta \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/mlx-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/mlx-icon.imageset/Contents.json new file mode 100644 index 0000000000..0bf36eb608 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/mlx-icon.imageset/Contents.json @@ -0,0 +1,26 @@ +{ + "images" : [ + { + "filename" : "mlx.pdf", + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "mlx-dark.pdf", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/apple/TablePro/Assets.xcassets/mlx-icon.imageset/mlx-dark.pdf b/apple/TablePro/Assets.xcassets/mlx-icon.imageset/mlx-dark.pdf new file mode 100644 index 0000000000..3f95f37c12 Binary files /dev/null and b/apple/TablePro/Assets.xcassets/mlx-icon.imageset/mlx-dark.pdf differ diff --git a/apple/TablePro/Assets.xcassets/mlx-icon.imageset/mlx.pdf b/apple/TablePro/Assets.xcassets/mlx-icon.imageset/mlx.pdf new file mode 100644 index 0000000000..c25193d799 Binary files /dev/null and b/apple/TablePro/Assets.xcassets/mlx-icon.imageset/mlx.pdf differ diff --git a/apple/TablePro/Assets.xcassets/ollama-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/ollama-icon.imageset/Contents.json new file mode 100644 index 0000000000..7b3662889b --- /dev/null +++ b/apple/TablePro/Assets.xcassets/ollama-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "ollama.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/ollama-icon.imageset/ollama.svg b/apple/TablePro/Assets.xcassets/ollama-icon.imageset/ollama.svg new file mode 100644 index 0000000000..bc368e99c5 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/ollama-icon.imageset/ollama.svg @@ -0,0 +1 @@ +Ollama \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/openai-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/openai-icon.imageset/Contents.json new file mode 100644 index 0000000000..7f508a44dd --- /dev/null +++ b/apple/TablePro/Assets.xcassets/openai-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "openai.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/openai-icon.imageset/openai.svg b/apple/TablePro/Assets.xcassets/openai-icon.imageset/openai.svg new file mode 100644 index 0000000000..e04db75a5b --- /dev/null +++ b/apple/TablePro/Assets.xcassets/openai-icon.imageset/openai.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/opencode-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/opencode-icon.imageset/Contents.json new file mode 100644 index 0000000000..60dd3911f8 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/opencode-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "opencode.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/opencode-icon.imageset/opencode.svg b/apple/TablePro/Assets.xcassets/opencode-icon.imageset/opencode.svg new file mode 100644 index 0000000000..1e0da06f97 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/opencode-icon.imageset/opencode.svg @@ -0,0 +1 @@ +OpenCode \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/openrouter-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/openrouter-icon.imageset/Contents.json new file mode 100644 index 0000000000..1ba973b6a6 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/openrouter-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "openrouter.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/openrouter-icon.imageset/openrouter.svg b/apple/TablePro/Assets.xcassets/openrouter-icon.imageset/openrouter.svg new file mode 100644 index 0000000000..83ec807bc9 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/openrouter-icon.imageset/openrouter.svg @@ -0,0 +1 @@ +OpenRouter \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/raycast-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/raycast-icon.imageset/Contents.json new file mode 100644 index 0000000000..630a8ef983 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/raycast-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "raycast.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/raycast-icon.imageset/raycast.svg b/apple/TablePro/Assets.xcassets/raycast-icon.imageset/raycast.svg new file mode 100644 index 0000000000..9e69b8d9bf --- /dev/null +++ b/apple/TablePro/Assets.xcassets/raycast-icon.imageset/raycast.svg @@ -0,0 +1 @@ +Raycast \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/requesty-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/requesty-icon.imageset/Contents.json new file mode 100644 index 0000000000..373d859eb1 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/requesty-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "requesty.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/apple/TablePro/Assets.xcassets/requesty-icon.imageset/requesty.svg b/apple/TablePro/Assets.xcassets/requesty-icon.imageset/requesty.svg new file mode 100644 index 0000000000..d6f1a1073a --- /dev/null +++ b/apple/TablePro/Assets.xcassets/requesty-icon.imageset/requesty.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/apple/TablePro/Assets.xcassets/vscode-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/vscode-icon.imageset/Contents.json new file mode 100644 index 0000000000..803aa273d9 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/vscode-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "vscode.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/apple/TablePro/Assets.xcassets/vscode-icon.imageset/vscode.svg b/apple/TablePro/Assets.xcassets/vscode-icon.imageset/vscode.svg new file mode 100644 index 0000000000..c453e633f3 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/vscode-icon.imageset/vscode.svg @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apple/TablePro/Assets.xcassets/warp-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/warp-icon.imageset/Contents.json new file mode 100644 index 0000000000..1d4bbf3f3e --- /dev/null +++ b/apple/TablePro/Assets.xcassets/warp-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "warp.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/warp-icon.imageset/warp.svg b/apple/TablePro/Assets.xcassets/warp-icon.imageset/warp.svg new file mode 100644 index 0000000000..b825120839 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/warp-icon.imageset/warp.svg @@ -0,0 +1 @@ +Warp \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/windsurf-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/windsurf-icon.imageset/Contents.json new file mode 100644 index 0000000000..87899b36f6 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/windsurf-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "windsurf.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/windsurf-icon.imageset/windsurf.svg b/apple/TablePro/Assets.xcassets/windsurf-icon.imageset/windsurf.svg new file mode 100644 index 0000000000..bb77fc9348 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/windsurf-icon.imageset/windsurf.svg @@ -0,0 +1 @@ +Windsurf \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/xai-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/xai-icon.imageset/Contents.json new file mode 100644 index 0000000000..a0cd740ec8 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/xai-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "xai.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/xai-icon.imageset/xai.svg b/apple/TablePro/Assets.xcassets/xai-icon.imageset/xai.svg new file mode 100644 index 0000000000..b08ffff656 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/xai-icon.imageset/xai.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apple/TablePro/Assets.xcassets/zed-icon.imageset/Contents.json b/apple/TablePro/Assets.xcassets/zed-icon.imageset/Contents.json new file mode 100644 index 0000000000..37797c2e01 --- /dev/null +++ b/apple/TablePro/Assets.xcassets/zed-icon.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "zed.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "template" + } +} diff --git a/apple/TablePro/Assets.xcassets/zed-icon.imageset/zed.svg b/apple/TablePro/Assets.xcassets/zed-icon.imageset/zed.svg new file mode 100644 index 0000000000..02327fd13b --- /dev/null +++ b/apple/TablePro/Assets.xcassets/zed-icon.imageset/zed.svg @@ -0,0 +1 @@ +Zed Industries \ No newline at end of file diff --git a/apple/TablePro/CLI/BridgeMain.swift b/apple/TablePro/CLI/BridgeMain.swift index 103abd4794..5fc45ac04a 100644 --- a/apple/TablePro/CLI/BridgeMain.swift +++ b/apple/TablePro/CLI/BridgeMain.swift @@ -40,7 +40,7 @@ struct TableProMcpBridge { return "The local MCP endpoint did not prove it belongs to TablePro. Restart TablePro and try again." case MCPBridgeStartupError.unsupportedUpstreamVersion: return "This TablePro build does not speak \(MCPProtocolVersion.latest.rawValue). Update TablePro." - case MCPHandshakeAcquisitionError.serverTurnedOff: + case MCPHandshakeAcquisitionError.serverTurnedOff, MCPHandshakeAcquisitionError.serverFailedToStart: return error.localizedDescription default: return "TablePro is not running. Launch the app and enable the MCP server." diff --git a/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentMCPBridge.swift b/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentMCPBridge.swift index 3450ce5425..6321d68b44 100644 --- a/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentMCPBridge.swift +++ b/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentMCPBridge.swift @@ -1,8 +1,3 @@ -// -// ClaudeAgentMCPBridge.swift -// TablePro -// - import Foundation import os import TableProMCP @@ -12,20 +7,45 @@ struct ClaudeAgentToolGrant: Sendable, Equatable { let tokenId: UUID } +// A turn that was asked to use a connection stops with one of these rather than run without its tools. +enum ClaudeAgentToolGrantError: Error, LocalizedError, Equatable { + case tokenNotSaved + case tokenNotCreated + case configNotWritten + + var errorDescription: String? { + switch self { + case .tokenNotSaved: + String(localized: "Claude Agent can't use this connection: TablePro couldn't save its access token to the Keychain. Try again.") + case .tokenNotCreated: + String(localized: "Claude Agent can't use this connection: TablePro couldn't create its access token. Try again.") + case .configNotWritten: + String(localized: "Claude Agent can't use this connection: TablePro couldn't write its MCP settings file. Try again.") + } + } +} + protocol ClaudeAgentMCPBridging: Sendable { - func makeGrant(connectionId: UUID?) async -> ClaudeAgentToolGrant? + func makeGrant(connectionId: UUID?) async throws -> ClaudeAgentToolGrant? func release(_ grant: ClaudeAgentToolGrant?) async } struct ClaudeAgentMCPBridge: ClaudeAgentMCPBridging { private static let logger = Logger(subsystem: "com.TablePro", category: "ClaudeAgentMCPBridge") - private static let tokenName = "__claude_agent__" private static let tokenLifetime: TimeInterval = 15 * 60 private let permissions: TokenPermissions + private let endpoint: @Sendable () async -> URL? + private let tokenStore: @Sendable () async -> MCPTokenStore? - init(permissions: TokenPermissions = .readOnly) { + init( + permissions: TokenPermissions = .readOnly, + endpoint: (@Sendable () async -> URL?)? = nil, + tokenStore: (@Sendable () async -> MCPTokenStore?)? = nil + ) { self.permissions = permissions + self.endpoint = endpoint ?? { await ClaudeAgentMCPBridge.resolveEndpoint() } + self.tokenStore = tokenStore ?? { await MCPServerManager.shared.tokenStore } } static func connectionAccess(for connectionId: UUID?) -> ConnectionAccess? { @@ -33,27 +53,38 @@ struct ClaudeAgentMCPBridge: ClaudeAgentMCPBridging { return .limited([connectionId]) } - func makeGrant(connectionId: UUID?) async -> ClaudeAgentToolGrant? { + func makeGrant(connectionId: UUID?) async throws -> ClaudeAgentToolGrant? { guard let connectionAccess = Self.connectionAccess(for: connectionId) else { Self.logger.info("No connection attached; Claude Agent runs without database tools") return nil } - guard let endpoint = await Self.resolveEndpoint() else { return nil } - guard let tokenStore = await MCPServerManager.shared.tokenStore else { return nil } - - guard let generated = try? await tokenStore.generate( - name: Self.tokenName, - permissions: permissions, - connectionAccess: connectionAccess, - expiresAt: Date.now.addingTimeInterval(Self.tokenLifetime), - isBridgeCredential: false, - isClaudeAgentCredential: true, - extraScopes: [] - ) else { return nil } + guard let endpoint = await self.endpoint() else { return nil } + guard let tokenStore = await self.tokenStore() else { return nil } + + let generated: (token: MCPAuthToken, plaintext: String) + do { + generated = try await tokenStore.generate( + name: MCPTokenStore.claudeAgentTokenName, + permissions: permissions, + connectionAccess: connectionAccess, + expiresAt: Date.now.addingTimeInterval(Self.tokenLifetime), + isBridgeCredential: false, + isClaudeAgentCredential: true, + extraScopes: [] + ) + } catch { + Self.logger.error("Claude Agent token was not issued: \(error.publicLogShape, privacy: .public)") + switch error as? MCPTokenStoreError { + case .notSaved?, .keychainUnavailable?: + throw ClaudeAgentToolGrantError.tokenNotSaved + case .storedTokensUnreadable?, .randomGenerationFailed?, nil: + throw ClaudeAgentToolGrantError.tokenNotCreated + } + } guard let configPath = Self.writeConfig(endpoint: endpoint, token: generated.plaintext) else { await tokenStore.retire(tokenId: generated.token.id) - return nil + throw ClaudeAgentToolGrantError.configNotWritten } Self.logger.debug("Issued Claude Agent MCP grant") @@ -63,7 +94,7 @@ struct ClaudeAgentMCPBridge: ClaudeAgentMCPBridging { func release(_ grant: ClaudeAgentToolGrant?) async { guard let grant else { return } try? FileManager.default.removeItem(atPath: grant.configPath) - guard let tokenStore = await MCPServerManager.shared.tokenStore else { return } + guard let tokenStore = await self.tokenStore() else { return } await tokenStore.retire(tokenId: grant.tokenId) Self.logger.debug("Released Claude Agent MCP grant") } diff --git a/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentProvider.swift b/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentProvider.swift index cdf25b831a..d6153c74c5 100644 --- a/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentProvider.swift +++ b/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentProvider.swift @@ -1,8 +1,3 @@ -// -// ClaudeAgentProvider.swift -// TablePro -// - import Foundation import os @@ -31,7 +26,7 @@ final class ClaudeAgentProvider: ChatTransport { let task = Task { var grant: ClaudeAgentToolGrant? do { - grant = await toolBridge.makeGrant(connectionId: options.connectionId) + grant = try await toolBridge.makeGrant(connectionId: options.connectionId) let prompt = AgentPromptRenderer.renderPrompt(turns: turns, includingSystemPrompt: nil) let lines = try cli.streamLines( arguments: Self.inferenceArguments( diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientCatalogBundle.swift b/apple/TablePro/Core/MCP/Clients/MCPClientCatalogBundle.swift new file mode 100644 index 0000000000..e6539dd60f --- /dev/null +++ b/apple/TablePro/Core/MCP/Clients/MCPClientCatalogBundle.swift @@ -0,0 +1,91 @@ +import Foundation +import os +import TableProMCPClients + +enum MCPClientCatalogBundle { + private static let logger = Logger(subsystem: "com.TablePro", category: "MCPClientCatalog") + + static let shared: MCPClientCatalog? = load(from: .main) + + static func load(from bundle: Bundle) -> MCPClientCatalog? { + guard let url = bundle.url(forResource: "clients", withExtension: "json") else { + logger.error("The app bundle has no clients.json") + return nil + } + do { + return try MCPClientCatalog.decode(Data(contentsOf: url)) + } catch { + logger.error("clients.json could not be read: \(error.publicLogShape, privacy: .public)") + return nil + } + } +} + +struct MCPClientSessionSighting: Equatable, Sendable { + let id: String + let clientInfoName: String + // The client's clientInfo title when it sent one, such as "Codex", else its name. + let displayName: String + let tokenName: String? + + init(id: String, clientInfoName: String, displayName: String? = nil, tokenName: String?) { + self.id = id + self.clientInfoName = clientInfoName + self.displayName = displayName ?? clientInfoName + self.tokenName = tokenName + } +} + +extension MCPClientSessionSighting { + init(_ snapshot: MCPServerManager.SessionSnapshot) { + self.init( + id: snapshot.id, + clientInfoName: snapshot.clientInfoName ?? snapshot.clientName, + displayName: snapshot.clientName, + tokenName: snapshot.tokenName + ) + } +} + +extension MCPClientCatalog { + // The in-app Claude Agent runs the claude CLI, which names itself Claude Code; that session is TablePro's own. + func clients(forSessionNamed clientInfoName: String, tokenName: String?) -> [MCPClientDefinition] { + guard tokenName != MCPTokenStore.claudeAgentTokenName else { return [] } + return clients(matchingClientInfoName: clientInfoName) + } + + // ChatGPT and Codex CLI send one clientInfo name: the session is the one of them found on this Mac, else neither. + func client(forSessionNamed clientInfoName: String, tokenName: String?, detected: Set) -> MCPClientDefinition? { + guard tokenName != MCPTokenStore.claudeAgentTokenName else { return nil } + return client(matchingClientInfoName: clientInfoName, detected: detected) + } + + // The rows a session lights: its own client, or every row it could be when the Mac cannot tell them apart. + func clientIDs(forSessionNamed clientInfoName: String, tokenName: String?, detected: Set) -> Set { + if let client = client(forSessionNamed: clientInfoName, tokenName: tokenName, detected: detected) { + return [client.id] + } + return Set(clients(forSessionNamed: clientInfoName, tokenName: tokenName).map(\.id)) + } + + // An icon is still right when every client the session could be shares it, as ChatGPT and Codex CLI do. + func iconSlug(forSessionNamed clientInfoName: String, tokenName: String?, detected: Set) -> String? { + if let client = client(forSessionNamed: clientInfoName, tokenName: tokenName, detected: detected) { + return client.icon + } + let icons = Set(clients(forSessionNamed: clientInfoName, tokenName: tokenName).map(\.icon)) + return icons.count == 1 ? icons.first : nil + } + + // The clients whose sessions only detection can tell apart. + func ambiguousClientIDs(forSessionsNamed sessions: [(clientInfoName: String, tokenName: String?)]) -> Set { + var ids: Set = [] + for session in sessions { + let candidates = clients(forSessionNamed: session.clientInfoName, tokenName: session.tokenName) + if candidates.count > 1 { + ids.formUnion(candidates.map(\.id)) + } + } + return ids + } +} diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientRow.swift b/apple/TablePro/Core/MCP/Clients/MCPClientRow.swift new file mode 100644 index 0000000000..df84a8ac57 --- /dev/null +++ b/apple/TablePro/Core/MCP/Clients/MCPClientRow.swift @@ -0,0 +1,304 @@ +import Foundation +import TableProMCPClients + +enum MCPClientConfigState: Equatable, Sendable { + case notConfigured + case current + case moved + case otherCopy + case outdated + // `project` is the folder whose own setup wins there, as the detail text shows it. + case shadowed(project: String) + case otherScope + case disabled + case usesToken + case unreadable + case unknown + + init(_ status: MCPClientConfigStatus, displayPath: (String) -> String = { $0 }) { + switch status { + case .notConfigured: + self = .notConfigured + case .current: + self = .current + case .stale(let reason): + switch reason { + case .commandMissing: + self = .moved + case .otherCommand: + self = .otherCopy + case .otherURL, .otherToken: + self = .outdated + case .shadowed(let scope): + self = .shadowed(project: displayPath(scope)) + } + case .otherScope: + self = .otherScope + case .disabled: + self = .disabled + case .usesToken: + self = .usesToken + case .unreadable: + self = .unreadable + case .unknown: + self = .unknown + } + } + + var hasEntry: Bool { + switch self { + case .current, .moved, .otherCopy, .outdated, .shadowed, .disabled, .usesToken: true + case .notConfigured, .otherScope, .unreadable, .unknown: false + } + } + + var needsUpdate: Bool { + switch self { + case .moved, .otherCopy, .outdated: true + case .current, .shadowed, .notConfigured, .otherScope, .disabled, .usesToken, .unreadable, .unknown: false + } + } + + // The user's own choice: a token they scoped, or TablePro turned off in the client. Install or Update would undo it. + var isUserChoice: Bool { + self == .usesToken || self == .disabled + } + + var isShadowed: Bool { + if case .shadowed = self { return true } + return false + } +} + +enum MCPClientRoute: Equatable, Sendable { + case deeplink(scheme: String) + case cli(binary: String) + case file + case copy + + var handsOff: Bool { + if case .deeplink = self { return true } + return false + } +} + +enum MCPClientUnsupported: Equatable, Sendable { + case remoteOnly + case stdioOnly +} + +enum MCPClientApplyMoment: Equatable, Sendable { + case live + case newSession + case restartApp + case reload +} + +struct MCPClientRow: Identifiable, Equatable, Sendable { + let id: String + let name: String + let iconSlug: String + let isDetected: Bool + let isInstalled: Bool + let config: MCPClientConfigState + let installRoute: MCPClientRoute + let updateRoute: MCPClientRoute + let removeRoute: MCPClientRoute? + let unsupported: MCPClientUnsupported? + let applies: MCPClientApplyMoment? + let configPath: String? + let displayConfigPath: String? + let configFileExists: Bool + let isConfigWritable: Bool + let snippet: String? + let commandLine: String? + + // A file only the client may write (Claude Code's .claude.json) is set up through its command, not pasted into. + var copyText: String? { + if let commandLine, !isConfigWritable { return commandLine } + return snippet ?? commandLine + } + + var configFileName: String? { + configPath.map { ($0 as NSString).lastPathComponent } + } +} + +struct MCPClientScanner: Sendable { + let catalog: MCPClientCatalog + let context: MCPClientSetupContext + + func scan() -> [MCPClientRow] { + catalog.clients.compactMap(row(for:)) + } + + func row(for client: MCPClientDefinition) -> MCPClientRow? { + guard let spec = client.spec(for: .macos) else { return nil } + let location = catalog.location(for: client, platform: .macos) + let configPath = location.map { context.expand($0.path) } + let fileExists = configPath.map { FileManager.default.fileExists(atPath: $0) } ?? false + let config = configState(location: location, path: configPath, fileExists: fileExists) + let detected = spec.detect.contains(where: isDetected) + let isInstalled = detected || config.hasEntry || config == .otherScope + let isWritable = location.map { $0.isWritable && $0.format != .yaml } ?? false + + let renderer = MCPTemplateRenderer(serverName: catalog.serverName, target: .stdio(command: context.bridgePath)) + let unsupported = spec.unsupported.map(Self.unsupported) + let entry = unsupported == nil ? try? renderer.entry(spec) : nil + + let available = unsupported == nil ? availableRoutes(spec, isWritable: isWritable) : [] + let installRoute = isInstalled ? (available.first ?? .copy) : .copy + // Update merges into the file and keeps the user's own keys; a client's add command replaces the whole entry. + let updateRoute = isInstalled + ? (available.first { $0 == .file } ?? available.first { !$0.handsOff } ?? available.first ?? .copy) + : .copy + // A shadowed row's user entry works; Remove would take it out and leave the project's old one in charge. + let removeRoute = config.hasEntry && !config.isShadowed && unsupported == nil + ? removalRoute(spec, isWritable: isWritable, fileExists: fileExists) + : nil + + return MCPClientRow( + id: client.id, + name: client.name, + iconSlug: client.icon, + isDetected: detected, + isInstalled: isInstalled, + config: config, + installRoute: installRoute, + updateRoute: updateRoute, + removeRoute: removeRoute, + unsupported: unsupported, + applies: spec.applies.map(Self.applyMoment), + configPath: configPath, + displayConfigPath: configPath.map(context.displayPath), + configFileExists: fileExists, + isConfigWritable: isWritable, + snippet: entry.map { renderer.snippet(for: location, entry: $0) }, + commandLine: entry.flatMap { commandLine(spec, renderer: renderer, entry: $0) } + ) + } + + func executable(named binary: String) -> URL? { + context.executable(named: binary, catalogPaths: catalogPaths(forBinary: binary)) + } + + func detectedIDs(among ids: Set) -> Set { + let found = catalog.clients.filter { client in + ids.contains(client.id) && client.spec(for: .macos)?.detect.contains(where: isDetected) == true + } + return Set(found.map(\.id)) + } + + private func configState(location: MCPConfigLocation?, path: String?, fileExists: Bool) -> MCPClientConfigState { + guard let location, let path else { return .unknown } + var text: String? + if fileExists { + guard let read = try? String(contentsOfFile: path, encoding: .utf8) else { return .unreadable } + text = read + } + let status = MCPClientStatusEvaluator.status( + configText: text, + location: location, + serverName: catalog.serverName, + expected: .stdio(command: context.bridgePath), + fileExists: { FileManager.default.fileExists(atPath: $0) } + ) + return MCPClientConfigState(status, displayPath: context.displayPath) + } + + private func isDetected(_ rule: MCPClientDetectRule) -> Bool { + switch rule { + case .bundleID(let identifier): + context.workspace.applicationURL(forBundleIdentifier: identifier) != nil + case .binary(let name, _): + executable(named: name) != nil + case .path(let path): + FileManager.default.fileExists(atPath: context.expand(path)) + } + } + + private func availableRoutes(_ spec: MCPClientPlatformSpec, isWritable: Bool) -> [MCPClientRoute] { + spec.install.compactMap { method -> MCPClientRoute? in + switch method { + case .deeplink(let scheme, _): + hasHandler(forScheme: scheme) ? .deeplink(scheme: scheme) : nil + case .cli(let cli): + executable(named: cli.binary) != nil ? .cli(binary: cli.binary) : nil + case .file: + isWritable ? .file : nil + } + } + } + + private func removalRoute(_ spec: MCPClientPlatformSpec, isWritable: Bool, fileExists: Bool) -> MCPClientRoute? { + for method in spec.install { + switch method { + case .cli(let cli) where cli.remove != nil && executable(named: cli.binary) != nil: + return .cli(binary: cli.binary) + case .file where isWritable && fileExists: + return .file + default: + continue + } + } + return nil + } + + private func hasHandler(forScheme scheme: String) -> Bool { + guard let probe = URL(string: "\(scheme)://") else { return false } + return context.workspace.applicationURL(toOpen: probe) != nil + } + + private func commandLine(_ spec: MCPClientPlatformSpec, renderer: MCPTemplateRenderer, entry: JSONValue) -> String? { + guard let cli = spec.cliInstall, let arguments = try? renderer.arguments(cli.add, entry: entry) else { return nil } + return renderer.commandLine(binary: cli.binary, arguments: arguments) + } + + private func catalogPaths(forBinary binary: String) -> [String] { + catalog.clients + .flatMap { $0.spec(for: .macos)?.detect ?? [] } + .flatMap { rule -> [String] in + if case let .binary(name, paths) = rule, name == binary { return paths } + return [] + } + } + + private static func unsupported(_ reason: MCPClientUnsupportedReason) -> MCPClientUnsupported { + switch reason { + case .remoteOnly: .remoteOnly + case .stdioOnly: .stdioOnly + } + } + + private static func applyMoment(_ applies: MCPClientApplies) -> MCPClientApplyMoment { + switch applies { + case .live: .live + case .newSession: .newSession + case .restartApp: .restartApp + case .reload: .reload + } + } +} + +extension MCPClientPlatformSpec { + var cliInstall: MCPCLIInstall? { + for method in install { + if case .cli(let cli) = method { return cli } + } + return nil + } + + func cliInstall(binary: String) -> MCPCLIInstall? { + for method in install { + if case .cli(let cli) = method, cli.binary == binary { return cli } + } + return nil + } + + func deeplinkTemplate(scheme: String) -> String? { + for method in install { + if case let .deeplink(candidate, template) = method, candidate == scheme { return template } + } + return nil + } +} diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift b/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift new file mode 100644 index 0000000000..21a1f29426 --- /dev/null +++ b/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift @@ -0,0 +1,244 @@ +import Foundation + +enum MCPClientActionKind: Equatable, Sendable { + case install + case update + case remove +} + +enum MCPClientActivity: Equatable, Sendable { + case running(MCPClientActionKind) + case handedOff + case failed(MCPClientActionKind, message: String, output: String?) +} + +enum MCPClientConnection: Equatable, Sendable { + case notConnected + case connected + case justConnected +} + +enum MCPClientRowAction: Equatable, Sendable { + case install(handsOff: Bool) + case update(handsOff: Bool) + case copy + + var title: String { + switch self { + case .install(let handsOff): + if handsOff { String(localized: "Install…") } else { String(localized: "Install") } + case .update(let handsOff): + if handsOff { String(localized: "Update…") } else { String(localized: "Update") } + case .copy: + String(localized: "Copy") + } + } + + // Every row's button reads the same verb, so VoiceOver needs the client's name to tell them apart. + func accessibilityLabel(clientName: String) -> String { + switch self { + case .install: + String(format: String(localized: "Install in %@"), clientName) + case .update: + String(format: String(localized: "Update in %@"), clientName) + case .copy: + String(format: String(localized: "Copy Setup for %@"), clientName) + } + } +} + +struct MCPClientRowPresentation: Equatable, Sendable { + let title: String + let subtitle: String + let status: String? + let action: MCPClientRowAction? + let isBusy: Bool + + init(row: MCPClientRow, activity: MCPClientActivity?, connection: MCPClientConnection) { + title = row.name + if case .running = activity { + isBusy = true + } else { + isBusy = false + } + if let unsupported = row.unsupported { + subtitle = Self.unsupportedSubtitle(unsupported) + status = nil + action = nil + return + } + var route = row.config.needsUpdate ? row.updateRoute : row.installRoute + if row.config == .unreadable, route == .file { + route = .copy + } + subtitle = Self.subtitle(route: route, row: row) + status = Self.status(row: row, activity: activity, connection: connection) + action = isBusy ? nil : Self.action(row: row) + } + + static func action(row: MCPClientRow) -> MCPClientRowAction? { + guard row.unsupported == nil else { return nil } + switch row.config { + case .current, .shadowed, .disabled, .usesToken: + return nil + case .moved, .otherCopy, .outdated: + return row.updateRoute == .copy ? .copy : .update(handsOff: row.updateRoute.handsOff) + case .notConfigured, .otherScope, .unreadable, .unknown: + if row.installRoute == .copy || (row.config == .unreadable && row.installRoute == .file) { + return row.copyText == nil ? nil : .copy + } + return .install(handsOff: row.installRoute.handsOff) + } + } + + private static func status( + row: MCPClientRow, + activity: MCPClientActivity?, + connection: MCPClientConnection + ) -> String? { + switch activity { + case .running(let kind): + return runningStatus(kind) + case .failed(let kind, _, _): + return failedStatus(kind) + case .handedOff where !row.config.hasEntry && connection == .notConnected: + return String(format: String(localized: "Finish in %@"), row.name) + case .handedOff, .none: + break + } + switch connection { + case .justConnected: + return String(localized: "Connected just now") + case .connected: + return String(localized: "Connected") + case .notConnected: + break + } + switch row.config { + case .current: + return String(localized: "Set up") + case .moved: + return String(localized: "TablePro moved") + case .otherCopy: + return String(localized: "Uses another copy") + case .outdated: + return String(localized: "Out of date") + case .shadowed: + return String(localized: "Old setup in a project") + case .otherScope: + return String(localized: "One project only") + case .disabled: + return String(localized: "Turned off") + case .usesToken: + return String(localized: "Set up with a token") + case .unreadable: + return String(localized: "Can't read settings") + case .notConfigured, .unknown: + return row.isInstalled ? nil : String(localized: "Not found") + } + } + + private static func runningStatus(_ kind: MCPClientActionKind) -> String { + switch kind { + case .install: String(localized: "Installing…") + case .update: String(localized: "Updating…") + case .remove: String(localized: "Removing…") + } + } + + private static func failedStatus(_ kind: MCPClientActionKind) -> String { + switch kind { + case .install: String(localized: "Couldn't install") + case .update: String(localized: "Couldn't update") + case .remove: String(localized: "Couldn't remove") + } + } + + private static func subtitle(route: MCPClientRoute, row: MCPClientRow) -> String { + switch route { + case .deeplink: + return String(format: String(localized: "Opens %@ to confirm"), row.name) + case .cli(let binary): + return String(format: String(localized: "Adds through the %@ command"), binary) + case .file: + return String(format: String(localized: "Edits %@"), row.displayConfigPath ?? row.name) + case .copy: + if let path = row.displayConfigPath, row.isConfigWritable { + return String(format: String(localized: "Copy the setup into %@"), path) + } + if row.commandLine != nil { + return String(localized: "Copy the command and run it in Terminal") + } + return String(format: String(localized: "Add it in %@'s settings"), row.name) + } + } + + private static func unsupportedSubtitle(_ reason: MCPClientUnsupported) -> String { + switch reason { + case .remoteOnly: + String(localized: "Reaches only servers on the internet") + case .stdioOnly: + String(localized: "Starts only local command servers") + } + } +} + +enum MCPClientDetailText { + static func applies(_ moment: MCPClientApplyMoment, name: String) -> String { + switch moment { + case .live: + String(format: String(localized: "%@ picks up the change right away."), name) + case .newSession: + String(format: String(localized: "Start a new %@ session to load it."), name) + case .restartApp: + String(format: String(localized: "Quit and reopen %@ to load it."), name) + case .reload: + String(format: String(localized: "Reload %@ to load it."), name) + } + } + + static func unsupported(_ reason: MCPClientUnsupported, name: String) -> String { + switch reason { + case .remoteOnly: + String( + format: String(localized: "%@ reaches MCP servers only from its maker's cloud, so it cannot reach TablePro on this Mac."), + name + ) + case .stdioOnly: + String( + format: String(localized: "%@ starts MCP servers only as local commands, so it cannot reach TablePro's HTTP server."), + name + ) + } + } + + static func configState(_ state: MCPClientConfigState, name: String) -> String? { + switch state { + case .moved: + String(format: String(localized: "%@ is set up for a copy of TablePro that is no longer there."), name) + case .otherCopy: + String(format: String(localized: "%@ is set up for a different copy of TablePro. Update points it to this one."), name) + case .outdated: + String(format: String(localized: "%@ is set up with an address or token that no longer works."), name) + case .shadowed(let project): + String( + format: String(localized: "%1$@ is set up, but the project %2$@ has its own older TablePro setup that wins there. Remove TablePro from that project's settings."), + name, + project + ) + case .otherScope: + String(format: String(localized: "%@ has TablePro in one project only. Install adds it for every project."), name) + case .disabled: + String(format: String(localized: "TablePro is turned off in %1$@. Turn it on in %1$@'s MCP settings to use it."), name) + case .usesToken: + String( + format: String(localized: "%@ connects with a token from Settings > MCP > Authentication, which can limit what it reaches. TablePro leaves it as is."), + name + ) + case .unreadable: + String(format: String(localized: "TablePro could not read %@'s settings file, so it leaves the file alone. Copy the setup and add it by hand."), name) + case .current, .notConfigured, .unknown: + nil + } + } +} diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientSetupContext.swift b/apple/TablePro/Core/MCP/Clients/MCPClientSetupContext.swift new file mode 100644 index 0000000000..4367ae3228 --- /dev/null +++ b/apple/TablePro/Core/MCP/Clients/MCPClientSetupContext.swift @@ -0,0 +1,83 @@ +import Foundation +import TableProMCPClients + +struct MCPClientSetupContext: Sendable { + let home: String + let environment: [String: String] + let bridgePath: String + let workspace: any MCPClientWorkspace + let isExecutable: @Sendable (String) -> Bool + + init( + home: String, + environment: [String: String], + bridgePath: String, + workspace: any MCPClientWorkspace = SystemMCPClientWorkspace(), + isExecutable: @escaping @Sendable (String) -> Bool = { FileManager.default.isExecutableFile(atPath: $0) } + ) { + self.home = home + self.environment = environment + self.bridgePath = bridgePath + self.workspace = workspace + self.isExecutable = isExecutable + } + + // A sandboxed run reads and writes client settings in a home inside the sandbox, never the real one. + static func live(storage: AppStorageEnvironment = .shared, bundle: Bundle = .main) -> MCPClientSetupContext { + let processEnvironment = ProcessInfo.processInfo.environment + let bridgePath = bundle.bundleURL.appendingPathComponent("Contents/MacOS/tablepro-mcp").path + guard storage.isIsolated else { + return MCPClientSetupContext( + home: NSHomeDirectory(), + environment: processEnvironment, + bridgePath: bridgePath + ) + } + return MCPClientSetupContext( + home: storage.supportDirectory.appendingPathComponent("ClientHome", isDirectory: true).path, + environment: processEnvironment["PATH"].map { ["PATH": $0] } ?? [:], + bridgePath: bridgePath + ) + } + + var searchDirectories: [String] { + [ + "\(home)/.local/bin", + "\(home)/.claude/local", + "/opt/homebrew/bin", + "/usr/local/bin", + "\(home)/.npm-global/bin", + "\(home)/.bun/bin", + "\(home)/.volta/bin", + "\(home)/.opencode/bin", + "/usr/bin", + "/bin" + ] + AgentCLIDiscovery.nodeVersionManagerDirectories(home: home) + } + + func expand(_ path: String) -> String { + MCPPathExpander.expand(path, home: home, environment: environment) + } + + func displayPath(_ path: String) -> String { + guard path.hasPrefix(home + "/") else { return path } + return "~" + path.dropFirst(home.count) + } + + // A GUI app gets launchd's PATH, and a node-based CLI needs node on it. + func processEnvironment() -> [String: String] { + AgentCLIDiscovery(candidatePaths: [], preferredPathDirectories: searchDirectories) + .makeEnvironment(base: environment, adding: ["HOME": home]) + } + + func executable(named name: String, catalogPaths: [String]) -> URL? { + var seen = Set() + let candidates = (catalogPaths.map(expand) + searchDirectories.map { "\($0)/\(name)" }) + .filter { seen.insert($0).inserted } + return AgentCLIDiscovery( + candidatePaths: candidates, + preferredPathDirectories: searchDirectories, + isExecutable: isExecutable + ).resolveExecutable(override: nil) + } +} diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientSetupService.swift b/apple/TablePro/Core/MCP/Clients/MCPClientSetupService.swift new file mode 100644 index 0000000000..5798fbc180 --- /dev/null +++ b/apple/TablePro/Core/MCP/Clients/MCPClientSetupService.swift @@ -0,0 +1,405 @@ +import AppKit +import Combine +import Foundation +import os +import TableProMCPClients + +enum MCPClientActionOutcome: Equatable, Sendable { + case done(backupPath: String?) + case handedOff + case refusedReadOnlyVolume + case failed(message: String, output: String?) + case unavailable +} + +private struct MCPClientActionFailure: Error { + let message: String + let output: String? +} + +@MainActor +final class MCPClientSetupService: ObservableObject { + private static let logger = Logger(subsystem: "com.TablePro", category: "MCPClientSetup") + private static let justConnectedDuration: Duration = .seconds(60) + + @Published private(set) var rows: [MCPClientRow] = [] + @Published private(set) var hasLoaded = false + @Published private(set) var activities: [String: MCPClientActivity] = [:] + @Published private(set) var connectedClientIDs: Set = [] + @Published private(set) var justConnectedClientIDs: Set = [] + + let isAppOnReadOnlyVolume: Bool + var isCatalogAvailable: Bool { catalog != nil } + + private let catalog: MCPClientCatalog? + private let context: MCPClientSetupContext + private let runner: any MCPClientCommandRunning + private let announce: @MainActor (String) -> Void + private var knownSessionIDs: Set? + private var sightings: [MCPClientSessionSighting] = [] + private var refreshGeneration = 0 + private var settleTasks: [String: Task] = [:] + private var subscriptions: Set = [] + + init( + catalog: MCPClientCatalog? = MCPClientCatalogBundle.shared, + context: MCPClientSetupContext = .live(), + runner: any MCPClientCommandRunning = AgentCLICommandRunner(), + isAppOnReadOnlyVolume: Bool = CommandLineShim.isOnReadOnlyVolume(Bundle.main.bundleURL), + sessions: AnyPublisher<[MCPClientSessionSighting], Never> = MCPClientSetupService.liveSessions(), + activations: AnyPublisher = MCPClientSetupService.liveActivations(), + announce: @escaping @MainActor (String) -> Void = { AccessibilityAnnouncement.post($0) } + ) { + self.catalog = catalog + self.context = context + self.runner = runner + self.isAppOnReadOnlyVolume = isAppOnReadOnlyVolume + self.announce = announce + + sessions + .sink { [weak self] sightings in self?.sessionsChanged(sightings) } + .store(in: &subscriptions) + activations + .sink { [weak self] in + guard let self else { return } + Task { await self.returnedToTablePro() } + } + .store(in: &subscriptions) + } + + deinit { + for task in settleTasks.values { + task.cancel() + } + } + + static func liveSessions() -> AnyPublisher<[MCPClientSessionSighting], Never> { + MCPServerManager.shared.$connectedClients + .map { snapshots in snapshots.map(MCPClientSessionSighting.init) } + .eraseToAnyPublisher() + } + + static func liveActivations() -> AnyPublisher { + NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification) + .map { _ in () } + .eraseToAnyPublisher() + } + + func row(id: String) -> MCPClientRow? { + rows.first { $0.id == id } + } + + func presentation(for row: MCPClientRow) -> MCPClientRowPresentation { + MCPClientRowPresentation(row: row, activity: activities[row.id], connection: connection(for: row.id)) + } + + func connection(for id: String) -> MCPClientConnection { + if justConnectedClientIDs.contains(id) { return .justConnected } + if connectedClientIDs.contains(id) { return .connected } + return .notConnected + } + + func refresh() async { + guard let catalog else { + hasLoaded = true + return + } + refreshGeneration += 1 + let generation = refreshGeneration + let scanned = await Self.scan(MCPClientScanner(catalog: catalog, context: context)) + guard generation == refreshGeneration else { return } + rows = scanned + hasLoaded = true + // Which of two rows sharing a session is on this Mac is known only once the rows are scanned. + connectedClientIDs = connectedIDs(for: sightings, catalog: catalog) + justConnectedClientIDs.formIntersection(connectedClientIDs) + for row in scanned where row.config.hasEntry && activities[row.id] == .handedOff { + activities[row.id] = nil + } + } + + // A client with no settings file to read gives no sign the hand-off finished; coming back is the best one. + func returnedToTablePro() async { + await refresh() + for row in rows where row.config == .unknown && activities[row.id] == .handedOff { + activities[row.id] = nil + } + } + + @concurrent + nonisolated private static func scan(_ scanner: MCPClientScanner) async -> [MCPClientRow] { + scanner.scan() + } + + @discardableResult + func install(_ id: String) async -> MCPClientActionOutcome { + await perform(.install, on: id) + } + + @discardableResult + func update(_ id: String) async -> MCPClientActionOutcome { + await perform(.update, on: id) + } + + @discardableResult + func remove(_ id: String) async -> MCPClientActionOutcome { + await perform(.remove, on: id) + } + + func sessionsChanged(_ sightings: [MCPClientSessionSighting]) { + guard let catalog else { return } + self.sightings = sightings + let previouslyConnected = connectedClientIDs + let connected = connectedIDs(for: sightings, catalog: catalog) + connectedClientIDs = connected + justConnectedClientIDs.formIntersection(connected) + + let ids = Set(sightings.map(\.id)) + guard let known = knownSessionIDs else { + // Sessions already open when the sheet appears read Connected, not just connected. + knownSessionIDs = ids + return + } + knownSessionIDs = ids + let arrivals = sightings.filter { !known.contains($0.id) } + guard !arrivals.isEmpty else { return } + + let detected = detectedClientIDs + for sighting in arrivals { + let clientIDs = catalog.clientIDs(forSessionNamed: sighting.clientInfoName, tokenName: sighting.tokenName, detected: detected) + let fresh = clientIDs.subtracting(previouslyConnected).subtracting(justConnectedClientIDs) + guard !fresh.isEmpty else { continue } + for id in fresh { + markJustConnected(id) + } + let client = catalog.client(forSessionNamed: sighting.clientInfoName, tokenName: sighting.tokenName, detected: detected) + announce(String(format: String(localized: "%@ connected"), client?.name ?? sighting.displayName)) + } + Task { await self.refresh() } + } + + private var detectedClientIDs: Set { + Set(rows.filter { $0.isDetected }.map(\.id)) + } + + private func connectedIDs(for sightings: [MCPClientSessionSighting], catalog: MCPClientCatalog) -> Set { + let detected = detectedClientIDs + return sightings.reduce(into: Set()) { ids, sighting in + ids.formUnion(catalog.clientIDs(forSessionNamed: sighting.clientInfoName, tokenName: sighting.tokenName, detected: detected)) + } + } + + private func markJustConnected(_ id: String) { + justConnectedClientIDs.insert(id) + settleTasks[id]?.cancel() + settleTasks[id] = Task { [weak self] in + try? await Task.sleep(for: Self.justConnectedDuration) + guard !Task.isCancelled else { return } + self?.justConnectedClientIDs.remove(id) + self?.settleTasks[id] = nil + } + } + + private func perform(_ kind: MCPClientActionKind, on id: String) async -> MCPClientActionOutcome { + guard let catalog, + let row = row(id: id), + let client = catalog.client(id: id), + let spec = client.spec(for: .macos), + spec.unsupported == nil + else { return .unavailable } + if case .running? = activities[id] { return .unavailable } + if kind != .remove, row.config.isUserChoice { return .unavailable } + // A disk image or a translocated copy is gone after eject or relaunch, so a client set up for it breaks. + if kind != .remove, isAppOnReadOnlyVolume { return .refusedReadOnlyVolume } + + let route: MCPClientRoute? = switch kind { + case .install: row.installRoute + case .update: row.updateRoute + case .remove: row.removeRoute + } + guard let route, route != .copy else { return .unavailable } + + activities[id] = .running(kind) + let outcome: MCPClientActionOutcome + do { + outcome = try await run(kind, route: route, client: client, spec: spec, catalog: catalog) + } catch let failure as MCPClientActionFailure { + outcome = .failed(message: failure.message, output: failure.output) + } catch { + outcome = .failed( + message: Self.message(for: error, fileName: row.configFileName ?? row.name), + output: Self.technicalDetail(for: error) + ) + } + + switch outcome { + case let .failed(message, output): + activities[id] = .failed(kind, message: message, output: output) + Self.logger.error("A client setup action failed for \(id, privacy: .public)") + case .handedOff: + activities[id] = .handedOff + case .done, .refusedReadOnlyVolume, .unavailable: + activities[id] = nil + } + await refresh() + return outcome + } + + private func run( + _ kind: MCPClientActionKind, + route: MCPClientRoute, + client: MCPClientDefinition, + spec: MCPClientPlatformSpec, + catalog: MCPClientCatalog + ) async throws -> MCPClientActionOutcome { + let renderer = MCPTemplateRenderer(serverName: catalog.serverName, target: .stdio(command: context.bridgePath)) + switch route { + case .deeplink(let scheme): + guard let template = spec.deeplinkTemplate(scheme: scheme) else { return .unavailable } + let url = try renderer.url(template, entry: try renderer.entry(spec)) + guard url.scheme?.caseInsensitiveCompare(scheme) == .orderedSame else { return .unavailable } + try await context.workspace.open(url) + return .handedOff + + case .cli(let binary): + guard let cli = spec.cliInstall(binary: binary) else { return .unavailable } + let scanner = MCPClientScanner(catalog: catalog, context: context) + guard let executable = scanner.executable(named: binary) else { + throw MCPClientActionFailure( + message: String(format: String(localized: "The %@ command is no longer installed."), binary), + output: nil + ) + } + let entry = try renderer.entry(spec) + switch kind { + case .install: + try await runCommand(executable, try renderer.arguments(cli.add, entry: entry), isRemoval: false) + case .update: + if cli.update == .removeThenAdd, let remove = cli.remove { + try await runCommand(executable, try renderer.arguments(remove, entry: entry), isRemoval: true) + } + try await runCommand(executable, try renderer.arguments(cli.add, entry: entry), isRemoval: false) + case .remove: + guard let remove = cli.remove else { return .unavailable } + try await runCommand(executable, try renderer.arguments(remove, entry: entry), isRemoval: true) + } + return .done(backupPath: nil) + + case .file: + guard let location = catalog.location(for: client, platform: .macos), + location.isWritable, + location.format != .yaml + else { return .unavailable } + let url = URL(fileURLWithPath: context.expand(location.path)) + let name = catalog.serverName + let writer = MCPConfigFileWriter() + switch kind { + case .install, .update: + guard let template = spec.entry else { return .unavailable } + let entry = try renderer.entry(spec) + let result = try writer.update(url) { text in + try Self.updating(name, entry: entry, template: template, at: location, in: text ?? "") + } + return .done(backupPath: result.backupURL?.path) + case .remove: + guard FileManager.default.fileExists(atPath: url.path) else { return .done(backupPath: nil) } + let result = try writer.update(url) { text in + try Self.removing(name, at: location, in: text ?? "") + } + return .done(backupPath: result.backupURL?.path) + } + + case .copy: + return .unavailable + } + } + + private func runCommand(_ executable: URL, _ arguments: [String], isRemoval: Bool) async throws { + let result = try await runner.run( + executable: executable, + arguments: arguments, + environment: context.processEnvironment() + ) + guard result.exitCode != 0 else { return } + // claude exits 1 for a server it does not have; for a removal that is the goal already reached. + if isRemoval, Self.reportsMissingEntry(result.output) { return } + let output = result.output.trimmingCharacters(in: .whitespacesAndNewlines) + throw MCPClientActionFailure( + message: String( + format: String(localized: "The %@ command stopped with exit code %d."), + executable.lastPathComponent, + Int(result.exitCode) + ), + output: output.isEmpty ? nil : output + ) + } + + nonisolated static func reportsMissingEntry(_ output: String) -> Bool { + let text = output.lowercased() + return ["no mcp server", "not found", "does not exist", "no such server"].contains { text.contains($0) } + } + + nonisolated private static func updating( + _ name: String, + entry: JSONValue, + template: JSONValue, + at location: MCPConfigLocation, + in text: String + ) throws -> String { + switch location.format { + case .toml: + try TOMLTableEditor.updating(name, entry: entry, template: template, at: location.keyPath, in: text) + case .json, .jsonc, .yaml: + try JSONCMemberEditor.updating(name, entry: entry, template: template, at: location.keyPath, in: text) + } + } + + nonisolated private static func removing(_ name: String, at location: MCPConfigLocation, in text: String) throws -> String { + switch location.format { + case .toml: + try TOMLTableEditor.removing(name, at: location.keyPath, in: text) + case .json, .jsonc, .yaml: + try JSONCMemberEditor.removing(name, at: location.keyPath, in: text) + } + } + + nonisolated static func message(for error: Error, fileName: String) -> String { + if let edit = error as? MCPConfigEditError { + switch edit { + case .invalidSyntax: + return String(format: String(localized: "%@ could not be read as valid settings, so TablePro left it unchanged."), fileName) + case .duplicateKey: + return String(format: String(localized: "%@ names the same key twice, so TablePro left it unchanged."), fileName) + case .notAnObject: + return String(format: String(localized: "%@ has an unexpected shape where TablePro would add itself, so TablePro left it unchanged."), fileName) + case .unsupportedShape: + return String(format: String(localized: "%@ defines TablePro in a form TablePro cannot edit safely, so it left the file unchanged."), fileName) + case .verificationFailed: + return verificationFailedMessage(fileName) + } + } + if let write = error as? MCPConfigWriteError { + switch write { + case .changedDuringWrite: + return String(format: String(localized: "%@ kept changing while TablePro wrote it. Try again."), fileName) + case .verificationFailed: + return verificationFailedMessage(fileName) + case .io: + return String(format: String(localized: "TablePro could not write %@."), fileName) + } + } + if error is MCPTemplateError { + return String(localized: "TablePro's client list has a setup for this client that it cannot fill in.") + } + return error.localizedDescription + } + + nonisolated static func technicalDetail(for error: Error) -> String? { + guard case .io(let detail)? = error as? MCPConfigWriteError else { return nil } + return detail + } + + nonisolated private static func verificationFailedMessage(_ fileName: String) -> String { + String(format: String(localized: "TablePro could not confirm its change to %@. Check the file before you try again."), fileName) + } +} diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientWorkspace.swift b/apple/TablePro/Core/MCP/Clients/MCPClientWorkspace.swift new file mode 100644 index 0000000000..b573eca560 --- /dev/null +++ b/apple/TablePro/Core/MCP/Clients/MCPClientWorkspace.swift @@ -0,0 +1,76 @@ +import AppKit +import Foundation + +protocol MCPClientWorkspace: Sendable { + func applicationURL(forBundleIdentifier identifier: String) -> URL? + func applicationURL(toOpen url: URL) -> URL? + func open(_ url: URL) async throws +} + +struct SystemMCPClientWorkspace: MCPClientWorkspace { + func applicationURL(forBundleIdentifier identifier: String) -> URL? { + NSWorkspace.shared.urlForApplication(withBundleIdentifier: identifier) + } + + func applicationURL(toOpen url: URL) -> URL? { + NSWorkspace.shared.urlForApplication(toOpen: url) + } + + // Only a catalog deeplink reaches here, and only after a handler app was found for its scheme. + func open(_ url: URL) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + NSWorkspace.shared.open(url, configuration: NSWorkspace.OpenConfiguration()) { _, error in + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume() + } + } + } + } +} + +struct MCPClientCommandResult: Equatable, Sendable { + let exitCode: Int32 + let output: String +} + +protocol MCPClientCommandRunning: Sendable { + func run(executable: URL, arguments: [String], environment: [String: String]) async throws -> MCPClientCommandResult +} + +enum MCPClientCommandError: Error, LocalizedError, Equatable { + case timedOut(command: String, seconds: Int) + + var errorDescription: String? { + switch self { + case let .timedOut(command, seconds): + String(format: String(localized: "The %@ command did not finish within %d seconds."), command, seconds) + } + } +} + +struct AgentCLICommandRunner: MCPClientCommandRunning { + var timeoutSeconds = 60 + + func run(executable: URL, arguments: [String], environment: [String: String]) async throws -> MCPClientCommandResult { + let process = AgentCLIProcess(label: executable.lastPathComponent) + let launch = AgentCLILaunch(executable: executable, arguments: arguments, environment: environment) + let limit = timeoutSeconds + return try await withThrowingTaskGroup(of: MCPClientCommandResult?.self) { group in + group.addTask { + let finished = try await process.run(launch) + return MCPClientCommandResult(exitCode: finished.code, output: finished.output) + } + group.addTask { + try await Task.sleep(for: .seconds(limit)) + return nil + } + defer { group.cancelAll() } + guard let first = try await group.next(), let result = first else { + throw MCPClientCommandError.timedOut(command: executable.lastPathComponent, seconds: limit) + } + return result + } + } +} diff --git a/apple/TablePro/Core/MCP/Clients/MCPHTTPClientSetup.swift b/apple/TablePro/Core/MCP/Clients/MCPHTTPClientSetup.swift new file mode 100644 index 0000000000..5cb0252fee --- /dev/null +++ b/apple/TablePro/Core/MCP/Clients/MCPHTTPClientSetup.swift @@ -0,0 +1,69 @@ +import Foundation +import TableProMCPClients + +struct MCPHTTPClientChoice: Identifiable, Hashable, Sendable { + let id: String + let name: String +} + +struct MCPHTTPClientSnippet: Equatable, Sendable { + let displayConfigPath: String? + let commandLine: String? + let snippet: String? +} + +struct MCPHTTPClientSetup: Sendable { + static let otherClientID = "__other__" + + let catalog: MCPClientCatalog? + let context: MCPClientSetupContext + let url: String + + init(catalog: MCPClientCatalog? = MCPClientCatalogBundle.shared, context: MCPClientSetupContext = .live(), port: Int) { + self.catalog = catalog + self.context = context + self.url = "http://127.0.0.1:\(port)/mcp" + } + + var choices: [MCPHTTPClientChoice] { + let catalogChoices = (catalog?.clients ?? []) + .filter { $0.spec(for: .macos) != nil && catalog?.httpEntry(for: $0) != nil } + .map { MCPHTTPClientChoice(id: $0.id, name: $0.name) } + return catalogChoices + [MCPHTTPClientChoice(id: Self.otherClientID, name: String(localized: "Other Client"))] + } + + static func authorization(token: String) -> String { + "Bearer \(token)" + } + + func render(clientID: String, token: String) -> MCPHTTPClientSnippet? { + guard let catalog, + let client = catalog.client(id: clientID), + let template = catalog.httpEntry(for: client), + let spec = Self.platformSpec(of: client, holding: template) + else { return nil } + let renderer = MCPTemplateRenderer( + serverName: catalog.serverName, + target: .http(url: url, authorization: Self.authorization(token: token)) + ) + guard let entry = try? renderer.entry(spec) else { return nil } + let location = catalog.location(for: client, platform: .macos) ?? catalog.location(for: client, platform: .linux) + let commandLine = spec.cliInstall.flatMap { cli in + (try? renderer.arguments(cli.add, entry: entry)).map { renderer.commandLine(binary: cli.binary, arguments: $0) } + } + let isWritable = location?.isWritable ?? true + return MCPHTTPClientSnippet( + displayConfigPath: location.map { context.displayPath(context.expand($0.path)) }, + commandLine: commandLine, + snippet: commandLine != nil && !isWritable ? nil : renderer.snippet(for: location, entry: entry) + ) + } + + // The HTTP entry is written for whichever platform serves TablePro over HTTP; its spec carries the matching CLI. + private static func platformSpec(of client: MCPClientDefinition, holding entry: JSONValue) -> MCPClientPlatformSpec? { + [MCPClientPlatform.macos, .linux] + .lazy + .compactMap { client.spec(for: $0) } + .first { $0.entry == entry } + } +} diff --git a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift index 85a95d0096..ea8ab78310 100644 --- a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift +++ b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift @@ -32,13 +32,23 @@ internal enum MCPServerStartError: Error, LocalizedError, Equatable { @MainActor internal final class MCPServerManager: ObservableObject { internal struct SessionSnapshot: Sendable, Identifiable, Equatable { + internal enum Transport: Sendable, Equatable { + // Shares the bridge credential with every other stdio client, so Disconnect cannot lock it out. + case stdioBridge + // Holds a token of its own, which Disconnect revokes. + case http + } + internal let id: String internal let clientName: String + // What the client sent as clientInfo.name; clientName prefers its title. + internal let clientInfoName: String? internal let clientVersion: String? internal let connectedSince: Date internal let lastActivityAt: Date internal let tokenName: String? internal let remoteAddress: String? + internal let transport: Transport } private struct BridgeCredential { @@ -62,10 +72,8 @@ internal final class MCPServerManager: ObservableObject { private let handshake: MCPHandshakeFile private let isEnabled: @MainActor () -> Bool - @Published private var composition: MCPServerComposition? + @Published private(set) var composition: MCPServerComposition? @Published private var bridgeCredential: BridgeCredential? - private var supersededBridgeCredentials: [BridgeCredential] = [] - private var bridgeDisconnects = 0 @Published private var instanceId = "" @Published private var generation = 0 @Published private var revocationObserverId: UUID? @@ -151,59 +159,40 @@ internal final class MCPServerManager: ObservableObject { composition?.authPolicy ?? MCPAuthPolicy() } - // False when the Keychain write failed: the token works again after a restart. + // False when nothing was revoked: no server is running, or the Keychain write failed and the token + // works again after a restart. @discardableResult internal func revokeToken(id: UUID) async -> Bool { - guard let tokenStore else { return true } + guard let tokenStore else { return false } return await tokenStore.revoke(tokenId: id) } + // False when the token revocation did not reach the Keychain. A stdio row revokes nothing: every + // stdio client shares the bridge credential, and a revoked one would lock all of them out. @discardableResult internal func disconnectClient(_ clientId: String) async -> Bool { guard let composition else { return true } let entries = await composition.activityLedger.snapshot(now: Date()) - - guard let tokenId = entries.first(where: { $0.id == clientId })?.tokenId else { + guard let entry = entries.first(where: { $0.id == clientId }) else { await composition.activityLedger.forget(id: clientId) await refreshClients() return true } - let stored = await tokenStore?.token(id: tokenId) - // Read after the await: a rotation that ran meanwhile may have moved this token to the superseded list. - let endsTheBridge = stored?.isBridgeCredential == true - || bridgeCredential?.tokenId == tokenId - || supersededBridgeCredentials.contains { $0.tokenId == tokenId } - - let persisted: Bool - if endsTheBridge { - // Every bridge credential is the same client, so the live one is revoked and all their requests end now. - bridgeDisconnects += 1 - var revoked = [tokenId] - if let live = bridgeCredential?.tokenId, live != tokenId { - revoked.append(live) - } - let ended = Set(revoked + supersededBridgeCredentials.map { $0.tokenId }) - var allPersisted = true - for id in revoked { - let saved = await revokeToken(id: id) - allPersisted = allPersisted && saved - } - for id in ended { - await composition.dispatcher.cancelInflight(matchingTokenId: id) - await composition.activityLedger.forget(tokenId: id) - } - persisted = allPersisted - } else { - var withdrawn: MCPGrantSubject? = .token(tokenId) - if let stored { - withdrawn = stored.subjectWithdrawnWhenEnded - } - persisted = await revokeToken(id: tokenId) - if let withdrawn { - await composition.authPolicy.clearApprovals(subject: withdrawn) - } + var stored: MCPAuthToken? + if let tokenId = entry.tokenId { + stored = await tokenStore?.token(id: tokenId) } + guard entry.transport == .http, stored?.isBridgeCredential != true, let tokenId = entry.tokenId else { + await composition.dispatcher.cancelInflight(matchingClientId: clientId) + await composition.activityLedger.forget(id: clientId) + await refreshClients() + return true + } + + let withdrawn = stored?.subjectWithdrawnWhenEnded ?? .token(tokenId) + let persisted = await revokeToken(id: tokenId) + await composition.authPolicy.clearApprovals(subject: withdrawn) await composition.activityLedger.forget(tokenId: tokenId) await refreshClients() return persisted @@ -214,9 +203,7 @@ internal final class MCPServerManager: ObservableObject { private func performStart(port: UInt16) async -> MCPServerStartError? { guard isEnabled() else { await performStop() - handshake.writeRefusal( - MCPStartRefusal(pid: ProcessInfo.processInfo.processIdentifier, refusedAt: Date()) - ) + writeRefusal(.turnedOff) Self.logger.info("Refused to start the MCP server: it is turned off") return .turnedOff } @@ -240,8 +227,7 @@ internal final class MCPServerManager: ObservableObject { socketPath = try handshake.prepareSocketPath() } catch { Self.logger.error("MCP socket folder is not usable: \(error.publicLogShape, privacy: .public)") - state = .failed(.socketFolderUnusable) - tokenStore = nil + failStart(.socketFolderUnusable) return nil } @@ -265,23 +251,33 @@ internal final class MCPServerManager: ObservableObject { } Self.logger.error("MCP server failed to start: \(lastFailure, privacy: .private)") - state = .failed(.listenerUnavailable(detail: lastFailure)) - tokenStore = nil + failStart(.listenerUnavailable(detail: lastFailure)) return nil } + // The bridge that launched TablePro reads the refusal and names the failure instead of timing out. + private func failStart(_ failure: MCPServerFailure) { + state = .failed(failure) + tokenStore = nil + writeRefusal(.failedToStart) + } + + private func writeRefusal(_ reason: MCPStartRefusal.Reason) { + handshake.writeRefusal( + MCPStartRefusal(pid: ProcessInfo.processInfo.processIdentifier, refusedAt: Date(), reason: reason) + ) + } + private func activate(_ built: MCPServerComposition, generation: Int, store: MCPTokenStore) async { guard let boundPort = await built.transport.listeningPort else { await built.transport.stop() - state = .failed(.noBoundPort) - tokenStore = nil + failStart(.noBoundPort) return } guard let credential = await mintBridgeCredential(store: store) else { await built.transport.stop() - state = .failed(.credentialUnavailable) - tokenStore = nil + failStart(.credentialUnavailable) return } @@ -321,7 +317,6 @@ internal final class MCPServerManager: ObservableObject { stateTask = nil tokenRenewalTask?.cancel() tokenRenewalTask = nil - supersededBridgeCredentials = [] handshake.removeIfWrittenByThisProcess(instanceId: instanceId) MCPServerInstanceIdentity.shared.end() @@ -388,11 +383,9 @@ internal final class MCPServerManager: ObservableObject { case .running = state else { return } let previous = bridgeCredential - let disconnects = bridgeDisconnects guard let credential = await mintBridgeCredential(store: store) else { return } - // A bridge disconnect during the mint keeps the bridge off until the next rotation. - guard self.generation == generation, bridgeDisconnects == disconnects else { + guard self.generation == generation else { await store.delete(tokenId: credential.tokenId) return } @@ -401,9 +394,6 @@ internal final class MCPServerManager: ObservableObject { writeHandshake(socketPath: composition.socketPath, credential: credential) if let previous { - // Listed before the await, so a disconnect from here on ends its requests too. - let now = Date() - supersededBridgeCredentials = supersededBridgeCredentials.filter { $0.expiresAt > now } + [previous] // Not a revocation: the old credential opens nothing new, but what it started may finish until it expires. await store.dropSupersededBridgeCredential(tokenId: previous.tokenId) guard self.generation == generation else { return } @@ -519,15 +509,18 @@ internal final class MCPServerManager: ObservableObject { SessionSnapshot( id: entry.id, clientName: entry.clientName, + clientInfoName: entry.clientInfoName, clientVersion: entry.clientVersion, connectedSince: entry.firstSeenAt, lastActivityAt: entry.lastSeenAt, tokenName: entry.tokenName, - remoteAddress: entry.address + remoteAddress: entry.address, + transport: entry.transport == .stdioBridge ? .stdioBridge : .http ) }) } + // Every observer of the manager re-renders on an assignment, equal or not. private func publishClients(_ clients: [SessionSnapshot]) { guard clients != connectedClients else { return } connectedClients = clients diff --git a/apple/TablePro/Core/MCP/MCPAuditLogStorage.swift b/apple/TablePro/Core/MCP/MCPAuditLogStorage.swift index 461c36c22b..6ded8af32a 100644 --- a/apple/TablePro/Core/MCP/MCPAuditLogStorage.swift +++ b/apple/TablePro/Core/MCP/MCPAuditLogStorage.swift @@ -28,10 +28,11 @@ struct MCPAuditChainLink: Sendable, Equatable { entry.connectionId?.uuidString ?? "", entry.action, entry.outcome, - entry.details ?? "", - previousHash + entry.details ?? "" ] - let joined = fields.joined(separator: "\u{1F}") + // Only a row with a client hashes it, so every row written before the column keeps its digest. + let client = entry.clientName.map { [$0] } ?? [] + let joined = (fields + client + [previousHash]).joined(separator: "\u{1F}") return SHA256.hash(data: Data(joined.utf8)).hexEncoded } } @@ -45,6 +46,9 @@ actor MCPAuditLogStorage { private static let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self) + private static let entryColumns = + "id, timestamp, category, token_id, token_name, connection_id, action, outcome, details, client_name" + private struct DatabaseHandle: @unchecked Sendable { var pointer: OpaquePointer? } @@ -160,21 +164,24 @@ actor MCPAuditLogStorage { details TEXT, sequence INTEGER, previous_hash TEXT, - entry_hash TEXT + entry_hash TEXT, + client_name TEXT ); """) - addMissingChainColumns() + addMissingColumns() execute("CREATE INDEX IF NOT EXISTS idx_audit_timestamp ON audit_entries(timestamp DESC);") execute("CREATE INDEX IF NOT EXISTS idx_audit_token ON audit_entries(token_id, timestamp DESC);") execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_audit_sequence ON audit_entries(sequence);") } - private func addMissingChainColumns() { + // Older builds read and write only the columns they name, so an added column keeps the log theirs too. + private func addMissingColumns() { let existing = columnNames(ofTable: "audit_entries") let required: [(String, String)] = [ ("sequence", "INTEGER"), ("previous_hash", "TEXT"), - ("entry_hash", "TEXT") + ("entry_hash", "TEXT"), + ("client_name", "TEXT") ] for (name, type) in required where !existing.contains(name) { execute("ALTER TABLE audit_entries ADD COLUMN \(name) \(type);") @@ -201,7 +208,7 @@ actor MCPAuditLogStorage { guard unchainedRowCount() > 0 else { return } let sql = """ - SELECT id, timestamp, category, token_id, token_name, connection_id, action, outcome, details + SELECT \(Self.entryColumns) FROM audit_entries ORDER BY timestamp ASC, id ASC; """ @@ -280,8 +287,8 @@ actor MCPAuditLogStorage { let sql = """ INSERT INTO audit_entries (id, timestamp, category, token_id, token_name, connection_id, action, outcome, details, - sequence, previous_hash, entry_hash) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + sequence, previous_hash, entry_hash, client_name) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); """ var statement: OpaquePointer? @@ -303,6 +310,7 @@ actor MCPAuditLogStorage { sqlite3_bind_int64(statement, 10, Int64(sequence)) sqlite3_bind_text(statement, 11, previousHash, -1, Self.SQLITE_TRANSIENT) sqlite3_bind_text(statement, 12, hash, -1, Self.SQLITE_TRANSIENT) + bindOptionalText(statement, index: 13, value: entry.clientName) guard sqlite3_step(statement) == SQLITE_DONE else { Self.logger.warning("Failed to append audit entry \(entry.action, privacy: .public)") @@ -328,16 +336,20 @@ actor MCPAuditLogStorage { func query( category: AuditCategory? = nil, tokenId: UUID? = nil, + tokenName: String? = nil, + clientName: String? = nil, since: Date? = nil, limit: Int = 500 ) -> [AuditEntry] { var conditions: [String] = [] if category != nil { conditions.append("category = ?") } if tokenId != nil { conditions.append("token_id = ?") } + if tokenName != nil { conditions.append("token_name = ?") } + if clientName != nil { conditions.append("client_name = ?") } if since != nil { conditions.append("timestamp >= ?") } var sql = """ - SELECT id, timestamp, category, token_id, token_name, connection_id, action, outcome, details + SELECT \(Self.entryColumns) FROM audit_entries """ if !conditions.isEmpty { @@ -361,6 +373,10 @@ actor MCPAuditLogStorage { sqlite3_bind_text(statement, bindIndex, tokenId.uuidString, -1, Self.SQLITE_TRANSIENT) bindIndex += 1 } + for value in [tokenName, clientName].compactMap({ $0 }) { + sqlite3_bind_text(statement, bindIndex, value, -1, Self.SQLITE_TRANSIENT) + bindIndex += 1 + } if let since { sqlite3_bind_double(statement, bindIndex, since.timeIntervalSince1970) bindIndex += 1 @@ -376,10 +392,28 @@ actor MCPAuditLogStorage { return entries } + func clientNames() -> [String] { + let sql = """ + SELECT DISTINCT client_name FROM audit_entries + WHERE client_name IS NOT NULL + ORDER BY client_name COLLATE NOCASE; + """ + var statement: OpaquePointer? + guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else { return [] } + defer { sqlite3_finalize(statement) } + + var names: [String] = [] + while sqlite3_step(statement) == SQLITE_ROW { + if let raw = sqlite3_column_text(statement, 0) { + names.append(String(cString: raw)) + } + } + return names + } + func verify() -> MCPAuditVerification { let sql = """ - SELECT id, timestamp, category, token_id, token_name, connection_id, action, outcome, details, - sequence, previous_hash, entry_hash + SELECT \(Self.entryColumns), sequence, previous_hash, entry_hash FROM audit_entries ORDER BY sequence ASC; """ @@ -397,11 +431,11 @@ actor MCPAuditLogStorage { while sqlite3_step(statement) == SQLITE_ROW { guard let entry = parseEntry(statement) else { - return .broken(atSequence: Int(sqlite3_column_int64(statement, 9))) + return .broken(atSequence: Int(sqlite3_column_int64(statement, 10))) } - let sequence = Int(sqlite3_column_int64(statement, 9)) - let previousHash = sqlite3_column_text(statement, 10).map { String(cString: $0) } ?? "" - let storedHash = sqlite3_column_text(statement, 11).map { String(cString: $0) } ?? "" + let sequence = Int(sqlite3_column_int64(statement, 10)) + let previousHash = sqlite3_column_text(statement, 11).map { String(cString: $0) } ?? "" + let storedHash = sqlite3_column_text(statement, 12).map { String(cString: $0) } ?? "" let recomputed = MCPAuditChainLink.digest( entry: entry, @@ -485,6 +519,7 @@ actor MCPAuditLogStorage { let action = String(cString: actionCString) let outcome = String(cString: outcomeCString) let details = sqlite3_column_text(statement, 8).map { String(cString: $0) } + let clientName = sqlite3_column_text(statement, 9).map { String(cString: $0) } return AuditEntry( id: id, @@ -495,7 +530,8 @@ actor MCPAuditLogStorage { connectionId: connectionId, action: action, outcome: outcome, - details: details + details: details, + clientName: clientName ) } } diff --git a/apple/TablePro/Core/MCP/MCPAuditLogger.swift b/apple/TablePro/Core/MCP/MCPAuditLogger.swift index 56c75a47aa..e5e8dfbf96 100644 --- a/apple/TablePro/Core/MCP/MCPAuditLogger.swift +++ b/apple/TablePro/Core/MCP/MCPAuditLogger.swift @@ -34,6 +34,7 @@ enum MCPAuditLogger { private static let serverResource = Logger(subsystem: "com.TablePro", category: "MCPResource") private static let messageExcerptLimit = 256 + private static let clientNameLimit = 128 static func flush() async { await MCPAuditWriteQueue.shared.flush() @@ -166,6 +167,7 @@ enum MCPAuditLogger { static func logQueryExecuted( principal: MCPPrincipal, + client: String? = nil, connectionId: UUID, sql: String, durationMs: Int, @@ -201,12 +203,14 @@ enum MCPAuditLogger { connectionId: connectionId, action: "query.executed", outcome: outcome, - details: detailParts.joined(separator: " ") + details: detailParts.joined(separator: " "), + client: client ) } static func logToolCalled( principal: MCPPrincipal, + client: String? = nil, toolName: String, connectionId: UUID? = nil, outcome: AuditOutcome, @@ -233,22 +237,13 @@ enum MCPAuditLogger { connectionId: connectionId, action: "tool.\(toolName)", outcome: outcome, - details: detailParts.joined(separator: " ") + details: detailParts.joined(separator: " "), + client: client ) } - /// A call TablePro made to an MCP server somebody else runs. - /// - /// Every other entry in this log records something an outside client asked of TablePro. This one - /// records the opposite direction, which is the direction that can take the user's schema and - /// their query results off the machine, so it is the one worth keeping. It is written before the - /// request leaves rather than when it returns: a server that never answers has still been sent - /// the arguments. - /// - /// The payload is recorded as its size and its SHA-256, not its text. The arguments of a tool - /// call carry table names, filter values and anything the model copied out of a result, and an - /// audit log that stored them would be a second copy of the data the log exists to watch. The - /// digest still answers "was this the same call as that one". + // A call TablePro made to someone else's MCP server, written before it leaves: a server that never + // answers was still sent the arguments. The payload is kept as size and digest, never as text. static func logOutboundToolCall( serverId: UUID, serverName: String, @@ -258,9 +253,7 @@ enum MCPAuditLogger { payload: Data ) { let digest = SHA256.hash(data: payload).compactMap { String(format: "%02x", $0) }.joined() - /// Named for what it digests. In this surface a fingerprint means a pairing token's, which - /// no log line may carry, and the `mcp_log_token_material` SwiftLint rule reads that - /// vocabulary rather than the value. + // Not "fingerprint": the mcp_log_token_material SwiftLint rule reserves that word for token material. let payloadDigest = String(digest.prefix(16)) serverTool.info( """ @@ -289,6 +282,7 @@ enum MCPAuditLogger { static func logResourceRead( principal: MCPPrincipal, + client: String? = nil, uri: String, outcome: AuditOutcome, errorMessage: String? = nil @@ -312,7 +306,8 @@ enum MCPAuditLogger { tokenName: principal.auditLabel, action: "resource.read", outcome: outcome, - details: detailParts.joined(separator: " ") + details: detailParts.joined(separator: " "), + client: client ) } @@ -320,6 +315,18 @@ enum MCPAuditLogger { SHA256.hash(data: Data(sql.utf8)).hexEncoded } + // The name Connected Clients lists, before any catalog lookup, so a row reads the same in every build. + // English like the rest of the row; nil when the client sent no clientInfo. + static func clientName(for meta: MCPRequestMeta) -> String? { + guard let info = meta.clientInfo else { return nil } + if info.name == CLIClientIdentity.name { + return CLIClientIdentity.pairingName + } + return [info.title, info.name] + .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } + .first { !$0.isEmpty } + } + private static func composeDetails(ip: String, extra: String?) -> String { guard let extra, !extra.isEmpty else { return "ip=\(ip)" } return "ip=\(ip) \(extra)" @@ -332,7 +339,8 @@ enum MCPAuditLogger { connectionId: UUID? = nil, action: String, outcome: AuditOutcome, - details: String? = nil + details: String? = nil, + client: String? = nil ) { let entry = AuditEntry( category: category, @@ -341,7 +349,8 @@ enum MCPAuditLogger { connectionId: connectionId, action: action, outcome: outcome, - details: details + details: details, + clientName: client.map { truncate($0, to: clientNameLimit) } ) MCPAuditWriteQueue.shared.enqueue(entry, into: MCPAuditLogStorage.shared) } diff --git a/apple/TablePro/Core/MCP/MCPPairingService.swift b/apple/TablePro/Core/MCP/MCPPairingService.swift index 23a1e369fe..2f234aa67f 100644 --- a/apple/TablePro/Core/MCP/MCPPairingService.swift +++ b/apple/TablePro/Core/MCP/MCPPairingService.swift @@ -12,9 +12,7 @@ struct PairingExchangeRecord: Sendable, Equatable { let expiresAt: Date } -/// A failed verification burns the code. PKCE protects the exchange only while each code allows one -/// attempt; leaving a code alive after a mismatch turns the five-minute window into an offline -/// guessing game against a value the caller can retry without limit. +// A failed verification burns the code: PKCE holds only while each code allows one attempt. actor PairingExchangeStore { static let exchangeWindow: TimeInterval = 300 static let maxPendingCodes = 50 @@ -96,6 +94,30 @@ actor PairingExchangeStore { } } +// The approval sheet has closed by the time a token is minted, so this is what the user reads. +enum MCPPairingError: Error, LocalizedError, Equatable { + case tokenNotSaved + case tokenNotCreated + + init(issuing error: Error) { + switch error as? MCPTokenStoreError { + case .notSaved?, .keychainUnavailable?: + self = .tokenNotSaved + case .storedTokensUnreadable?, .randomGenerationFailed?, nil: + self = .tokenNotCreated + } + } + + var errorDescription: String? { + switch self { + case .tokenNotSaved: + String(localized: "TablePro couldn't save a token for this client to the Keychain, so the client wasn't paired. Try pairing again.") + case .tokenNotCreated: + String(localized: "TablePro couldn't create a token for this client, so the client wasn't paired. Try pairing again.") + } + } +} + @MainActor final class MCPPairingService { static let shared = MCPPairingService() @@ -168,20 +190,57 @@ final class MCPPairingService { throw error } + let redirect: URL + do { + redirect = try await issueCode(for: request, target: target, approval: approval, tokenStore: tokenStore) + } catch { + // The requesting app waits on its redirect, so a failure after approval still answers it. + if let failed = PairingRedirectBuilder.failed( + base: target.url, + state: request.state, + mode: request.responseMode + ) { + NSWorkspace.shared.open(failed) + } + throw error + } + + Self.logger.info( + """ + Pairing approved for client '\(request.clientName, privacy: .private(mask: .hash))' \ + redirect=\(target.displayValue, privacy: .private(mask: .hash)) + """ + ) + NSWorkspace.shared.open(redirect) + } + + // Mints the token and parks it behind a one-time code; nothing is left behind when it throws. + func issueCode( + for request: PairingRequest, + target: PairingRedirectTarget, + approval: PairingApproval, + tokenStore: MCPTokenStore + ) async throws -> URL { let connectionAccess: ConnectionAccess = approval.allowedConnectionIds.map { .limited($0) } ?? .all let extraScopes = request.scopeRequest.grantedOptionalScopes( approved: approval.extraScopes, allowsHiddenConnectionListing: AppSettingsManager.shared.mcp.allowsHiddenConnectionListing ) - let result = try await tokenStore.generate( - name: request.clientName, - permissions: approval.grantedPermissions, - connectionAccess: connectionAccess, - expiresAt: approval.expiresAt, - isBridgeCredential: false, - isClaudeAgentCredential: false, - extraScopes: extraScopes - ) + let result: (token: MCPAuthToken, plaintext: String) + do { + result = try await tokenStore.generate( + name: request.clientName, + permissions: approval.grantedPermissions, + connectionAccess: connectionAccess, + expiresAt: approval.expiresAt, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: extraScopes + ) + } catch { + Self.logger.error("Pairing token was not issued: \(error.publicLogShape, privacy: .public)") + throw MCPPairingError(issuing: error) + } let code = UUID().uuidString do { @@ -211,14 +270,7 @@ final class MCPPairingService { await tokenStore.delete(tokenId: result.token.id) throw DatabaseAccessError.invalidArgument("redirect URL") } - - Self.logger.info( - """ - Pairing approved for client '\(request.clientName, privacy: .private(mask: .hash))' \ - redirect=\(target.displayValue, privacy: .private(mask: .hash)) - """ - ) - NSWorkspace.shared.open(redirect) + return redirect } func exchange( diff --git a/apple/TablePro/Core/MCP/MCPTokenStore.swift b/apple/TablePro/Core/MCP/MCPTokenStore.swift index d75cd00d7f..97d5fa6608 100644 --- a/apple/TablePro/Core/MCP/MCPTokenStore.swift +++ b/apple/TablePro/Core/MCP/MCPTokenStore.swift @@ -9,6 +9,7 @@ enum MCPTokenStoreError: Error, Sendable, Equatable { case randomGenerationFailed(OSStatus) case keychainUnavailable(OSStatus) case storedTokensUnreadable + case notSaved var message: String { switch self { @@ -18,6 +19,8 @@ enum MCPTokenStoreError: Error, Sendable, Equatable { return "Keychain unavailable (OSStatus \(status))" case .storedTokensUnreadable: return "The saved MCP tokens could not be read, so a new token cannot be saved" + case .notSaved: + return "The new MCP token could not be saved to the Keychain" } } } @@ -51,6 +54,25 @@ struct MCPAuthToken: Codable, Identifiable, Sendable { var isEffectivelyActive: Bool { isActive && !isExpired } + func renamed(_ name: String) -> MCPAuthToken { + MCPAuthToken( + id: id, + name: name, + prefix: prefix, + tokenHash: tokenHash, + salt: salt, + permissions: permissions, + connectionAccess: connectionAccess, + createdAt: createdAt, + lastUsedAt: lastUsedAt, + expiresAt: expiresAt, + isActive: isActive, + isBridgeCredential: isBridgeCredential, + isClaudeAgentCredential: isClaudeAgentCredential, + extraScopes: extraScopes + ) + } + var grantSubject: MCPGrantSubject { MCPGrantSubject(tokenId: id, isBridgeCredential: isBridgeCredential, isClaudeAgentCredential: isClaudeAgentCredential) } @@ -185,6 +207,7 @@ enum TokenPermissions: String, Codable, Sendable, CaseIterable, Identifiable { actor MCPTokenStore { static let stdioBridgeTokenName = "__stdio_bridge__" + static let claudeAgentTokenName = "__claude_agent__" static let bridgeTokenPermissions: TokenPermissions = .readWrite static let defaultTokenLifetime: TimeInterval = 90 * 24 * 60 * 60 @@ -220,7 +243,8 @@ actor MCPTokenStore { revocationObservers.removeValue(forKey: id) } - // Only the bridge's own mint may take its name: a pairing client could otherwise claim the bridge's grants. + // Only the bridge's and the agent's own mints may take their names: a pairing client picks its name, + // and the window labels both names as TablePro's own. loadFromDisk enforces the same for older tokens. func generate( name: String, permissions: TokenPermissions, @@ -230,9 +254,10 @@ actor MCPTokenStore { isClaudeAgentCredential: Bool, extraScopes: Set ) throws -> (token: MCPAuthToken, plaintext: String) { - let name = (!isBridgeCredential && name == Self.stdioBridgeTokenName) - ? name + " (client)" - : name + let isAgentMint = isClaudeAgentCredential && !isBridgeCredential + let claimsReservedName = (!isBridgeCredential && name == Self.stdioBridgeTokenName) + || (!isAgentMint && name == Self.claudeAgentTokenName) + let name = claimsReservedName ? Self.clientName(claiming: name) : name // The bridge credential is dropped at every load, so it alone may live in memory only. if !isBridgeCredential, !adoptStoredTokensIfUnread() { Self.logger.error("Refused to mint an MCP token: the stored list is still unreadable") @@ -255,12 +280,17 @@ actor MCPTokenStore { expiresAt: expiresAt, isActive: true, isBridgeCredential: isBridgeCredential, - isClaudeAgentCredential: isClaudeAgentCredential && !isBridgeCredential, + isClaudeAgentCredential: isAgentMint, extraScopes: isBridgeCredential ? [] : extraScopes ) tokens.append(token) - save() + // A token the Keychain did not take would vanish at the next launch while the client still holds it. + if !save(), !isBridgeCredential { + tokens.removeAll { $0.id == token.id } + Self.logger.error("Refused to hand out an MCP token the Keychain did not save") + throw MCPTokenStoreError.notSaved + } Self.logger.info("Generated MCP token '\(name, privacy: .private(mask: .hash))'") MCPAuditLogger.logTokenCreated(tokenId: token.id, tokenName: name) @@ -312,12 +342,16 @@ actor MCPTokenStore { return revoke(tokenId: token.id) ? .revoked : .notPersisted } - func delete(tokenId: UUID) { + // False when the Keychain write failed: the token stops working now, but until a later save lands a + // restart brings it back. + @discardableResult + func delete(tokenId: UUID) -> Bool { remove(tokenId: tokenId, withdrawsApprovals: true) } // A Claude Agent turn ends its own token this way: the approvals belong to the agent, not to one turn. - func retire(tokenId: UUID) { + @discardableResult + func retire(tokenId: UUID) -> Bool { remove(tokenId: tokenId, withdrawsApprovals: false) } @@ -332,19 +366,21 @@ actor MCPTokenStore { Self.logger.info("Dropped the superseded bridge credential") } - private func remove(tokenId: UUID, withdrawsApprovals: Bool) { + @discardableResult + private func remove(tokenId: UUID, withdrawsApprovals: Bool) -> Bool { guard let index = tokens.firstIndex(where: { $0.id == tokenId }) else { Self.logger.warning("Attempted to delete non-existent token \(tokenId.uuidString, privacy: .public)") - return + return true } let name = tokens[index].name let withdrawn = withdrawsApprovals ? tokens[index].subjectWithdrawnWhenEnded : nil tokens.remove(at: index) - save() + let persisted = save() notifyRevocationObservers(tokenId: tokenId, withdrawing: withdrawn) Self.logger.info("Deleted MCP token '\(name, privacy: .private(mask: .hash))'") + return persisted } private func notifyRevocationObservers(tokenId: UUID, withdrawing subject: MCPGrantSubject?) { @@ -394,16 +430,31 @@ actor MCPTokenStore { } let staleCount = tokens.filter(Self.isStaleBridge).count - guard staleCount > 0 else { return } tokens.removeAll(where: Self.isStaleBridge) + let renamedCount = tokens.filter(Self.claimsAgentName).count + tokens = tokens.map(Self.releasingAgentName) + guard staleCount > 0 || renamedCount > 0 else { return } save() - Self.logger.info("Cleaned up \(staleCount) stale bridge token(s)") + Self.logger.info("Cleaned up \(staleCount) stale bridge token(s), renamed \(renamedCount) client token(s)") } private static func isStaleBridge(_ token: MCPAuthToken) -> Bool { token.isBridgeCredential || token.name == stdioBridgeTokenName } + // Builds before the agent's name was reserved let a pairing client take it. + private static func claimsAgentName(_ token: MCPAuthToken) -> Bool { + token.name == claudeAgentTokenName && !token.isClaudeAgentCredential + } + + private static func releasingAgentName(_ token: MCPAuthToken) -> MCPAuthToken { + claimsAgentName(token) ? token.renamed(clientName(claiming: token.name)) : token + } + + private static func clientName(claiming reservedName: String) -> String { + reservedName + " (client)" + } + // One entry this build cannot decode costs that entry only, and it is written back untouched. static func decodeStored(_ data: Data) -> (tokens: [MCPAuthToken], undecoded: [Data]) { guard let entries = try? JSONSerialization.jsonObject(with: data) as? [Any] else { @@ -454,7 +505,9 @@ actor MCPTokenStore { } storedTokensUnread = false let minted = Set(tokens.map(\.id)) - tokens = stored.tokens.filter { !minted.contains($0.id) && !Self.isStaleBridge($0) } + tokens + tokens = stored.tokens + .filter { !minted.contains($0.id) && !Self.isStaleBridge($0) } + .map(Self.releasingAgentName) + tokens undecodedEntries = stored.undecoded Self.logger.info("Read the stored MCP tokens after an earlier failure") return true diff --git a/apple/TablePro/Core/MCP/PairingTypes.swift b/apple/TablePro/Core/MCP/PairingTypes.swift index 55afb9969b..92ec3e64a8 100644 --- a/apple/TablePro/Core/MCP/PairingTypes.swift +++ b/apple/TablePro/Core/MCP/PairingTypes.swift @@ -43,8 +43,7 @@ struct PairingRequest: Sendable, Equatable { } } -/// `scopes` names one permission level plus optional grants, separated by commas or spaces. -/// Unknown entries are skipped (RFC 6749 §3.3), and when several levels are named the lowest wins. +// One permission level plus optional grants; unknown entries are skipped (RFC 6749 3.3) and the lowest level wins. struct PairingScopeRequest: Sendable, Equatable { let permissions: TokenPermissions let optionalGrants: Set @@ -59,8 +58,7 @@ struct PairingScopeRequest: Sendable, Equatable { ) } - /// A grant needs all three: the client asked for it, the user ticked it on the sheet, and the - /// setting allows it. + // Granted only when the client asked, the user ticked it on the sheet, and the setting allows it. func grantedOptionalScopes(approved: Set, allowsHiddenConnectionListing: Bool) -> Set { guard allowsHiddenConnectionListing else { return [] } return optionalGrants.intersection(approved) @@ -80,8 +78,7 @@ struct PairingScopeRequest: Sendable, Equatable { } } -/// `legacy` is a link without `response_mode`: deprecated, and kept byte for byte for the clients -/// that shipped before the parameter existed. +// legacy is a link without response_mode, kept byte for byte for clients that shipped before it. enum PairingResponseMode: Sendable, Equatable { case legacy case query @@ -155,10 +152,8 @@ enum PairingValidationError: Error, Sendable, Equatable { } } -/// A pairing code is a bearer credential for the whole grant, so the address it is delivered to -/// decides who ends up holding it. Only two shapes can reach the machine the user is sitting at: a -/// loopback HTTP listener (RFC 8252's native-app redirect) and a private-use scheme registered by an -/// installed app. Any other origin is a web page, and handing it the code hands it the token. +// Whoever receives the code holds the grant, so only a loopback listener (RFC 8252) or an installed +// app's private-use scheme may: any other origin is a web page. enum PairingRedirectValidator { static let loopbackHosts: Set = [ "127.0.0.1", @@ -167,8 +162,7 @@ enum PairingRedirectValidator { "0:0:0:0:0:0:0:1" ] - /// `tablepro` would hand the code back to this app and open another pairing sheet. The rest run - /// or read something locally, or make their handler fetch from the host the URL names. + // tablepro would reopen a pairing sheet; the rest run something locally or fetch from the named host. static let deniedSchemes: Set = [ "about", "afp", "blob", "cifs", "data", "dav", "davs", "feed", "feeds", "file", "ftp", "ftps", "git", "gopher", "irc", "ircs", "itpc", "javascript", "ldap", "ldaps", "news", "nfs", "nntp", @@ -177,8 +171,7 @@ enum PairingRedirectValidator { "wss", "xmpp" ] - /// Every scheme this app handles, database URLs included: opening one of them with the code - /// appended would start a connection to whatever host the redirect names. + // Opening one of these with the code appended would connect to whatever host the redirect names. static let appRegisteredSchemes: Set = { let types = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [[String: Any]] ?? [] let schemes = types.flatMap { $0["CFBundleURLSchemes"] as? [String] ?? [] } @@ -211,7 +204,7 @@ enum PairingRedirectValidator { isWellFormedScheme(scheme) else { throw PairingValidationError.redirectSchemeNotAllowed(scheme) } - /// An opaque URL such as `myapp:https://example.com/` keeps its whole address in the path. + // An opaque URL such as myapp:https://example.com/ keeps its whole address in the path. let components = URLComponents(url: url, resolvingAgainstBaseURL: false) let authority = components?.host.map { "//\($0)" } ?? "" let port = components?.port.map { ":\($0)" } ?? "" @@ -222,8 +215,7 @@ enum PairingRedirectValidator { ) } - /// A browser that owns a custom scheme can unwrap it into a web page: Chrome opens - /// `google-chrome:https://…` and Safari opens `x-safari-https://…`. + // A browser that owns a custom scheme unwraps it into a web page (google-chrome:https://, x-safari-https://). static func validateHandler( of target: PairingRedirectTarget, handlerBundleIdentifier: String?, @@ -247,7 +239,7 @@ enum PairingRedirectValidator { } enum PairingRedirectBuilder { - /// Form decoders split on `&` and `=`, read `+` as a space, and some still split on `;`. + // Form decoders split on & and =, read + as a space, and some still split on ;. private static let valueCharacters = CharacterSet.urlQueryAllowed .subtracting(CharacterSet(charactersIn: "&=+;")) @@ -265,6 +257,16 @@ enum PairingRedirectBuilder { ) } + // The user approved, then TablePro could not issue the token (RFC 6749 4.1.2.1 server_error). + static func failed(base: URL, state: String?, mode: PairingResponseMode) -> URL? { + redirect( + base: base, + parameters: [("error", "server_error"), ("error_description", "token_not_issued")], + state: state, + mode: mode + ) + } + private static func redirect( base: URL, parameters: [(name: String, value: String)], @@ -303,7 +305,7 @@ enum PairingRedirectBuilder { guard var components = URLComponents(url: base, resolvingAgainstBaseURL: false) else { return nil } - /// Decoding and re-encoding the client's own items would turn its `%2B` into `+`. + // Decoding and re-encoding the client's own items would turn its %2B into +. var items = components.percentEncodedQueryItems ?? [] for parameter in parameters { guard let value = parameter.value.addingPercentEncoding(withAllowedCharacters: valueCharacters) else { @@ -316,9 +318,7 @@ enum PairingRedirectBuilder { } } -/// RFC 7636 fixes both halves of PKCE: the verifier is 43 to 128 characters of the unreserved set, -/// and the challenge is its base64url SHA-256, which is always 43 characters. Anything else is not a -/// PKCE exchange and is rejected before it can reach a comparison. +// RFC 7636: a verifier of 43 to 128 unreserved characters, a challenge of 43; anything else never reaches a comparison. enum PairingPkceValidator { static let minimumVerifierLength = 43 static let maximumVerifierLength = 128 diff --git a/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Notifications.swift b/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Notifications.swift index 02a4ac25e3..23d1f13908 100644 --- a/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Notifications.swift +++ b/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Notifications.swift @@ -21,13 +21,45 @@ extension MCPProtocolDispatcher { Self.logger.debug("Dropping cancellation without a usable requestId") return } - let key = MCPInflightKey(principal: principal, requestId: requestId) + guard let key = await cancellationKey( + requestId: requestId, + params: notification.params, + principal: principal, + exchange: exchange + ) else { + Self.logger.debug("Dropping a cancellation that does not say which stdio client sent it") + return + } let reason = notification.params?["reason"]?.stringValue let cancelled = await inflight.cancel(key: key, reason: .clientRequested(reason)) guard !cancelled else { return } Self.logger.debug("Cancellation referenced a request that is no longer in flight") } + // The sender is resolved the way its request was, so a cancellation reaches only that client's request. + private func cancellationKey( + requestId: JsonRpcId, + params: JsonValue?, + principal: MCPPrincipal, + exchange: MCPInboundExchange + ) async -> MCPInflightKey? { + guard principal.metadata.isBridgeCredential else { + return MCPInflightKey(principal: principal, requestId: requestId) + } + if let bridgeInstance = MCPRequestMeta.bridgeInstance(in: params) { + return MCPInflightKey(bridgeInstance: bridgeInstance, requestId: requestId) + } + let meta: MCPRequestMeta + switch try? await legacyAdapter.resolve(message: exchange.message, inbound: exchange.context) { + case .modern(let resolved)?, .legacy(let resolved, _)?: + meta = resolved + case .legacyInitialize?, nil: + return nil + } + let client = MCPClientIdentity(meta: meta, principal: principal, address: exchange.context.clientAddress) + return MCPInflightKey(client: client, requestId: requestId) + } + internal static func cancellationRequestId(in params: JsonValue?) -> JsonRpcId? { switch params?["requestId"] { case .string(let value): diff --git a/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Requests.swift b/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Requests.swift index 3e34ad8fdb..bd3281c6a4 100644 --- a/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Requests.swift +++ b/apple/TablePro/Core/MCP/Protocol/Extensions/MCPProtocolDispatcher+Requests.swift @@ -118,19 +118,22 @@ extension MCPProtocolDispatcher { return } - await activityLedger.record( - meta: meta, - principal: principal, - address: exchange.context.clientAddress, - at: exchange.context.receivedAt - ) + let client = MCPClientIdentity(meta: meta, principal: principal, address: exchange.context.clientAddress) + if !Self.activityExemptMethods.contains(request.method) { + await activityLedger.record(identity: client, at: exchange.context.receivedAt) + } - let key = MCPInflightKey(principal: principal, requestId: request.id) + let key = MCPInflightKey( + client: client, + bridgeInstance: MCPRequestMeta.bridgeInstance(in: request.params), + requestId: request.id + ) let cancellation = MCPCancellationToken() let registered = await inflight.register( key: key, token: cancellation, tokenId: principal.tokenId, + clientId: client.id, method: request.method, startedAt: exchange.context.receivedAt ) diff --git a/apple/TablePro/Core/MCP/Protocol/Handlers/PromptsGetHandler.swift b/apple/TablePro/Core/MCP/Protocol/Handlers/PromptsGetHandler.swift index bace8167ee..4450e19380 100644 --- a/apple/TablePro/Core/MCP/Protocol/Handlers/PromptsGetHandler.swift +++ b/apple/TablePro/Core/MCP/Protocol/Handlers/PromptsGetHandler.swift @@ -42,6 +42,7 @@ public struct PromptsGetHandler: MCPMethodHandler { ) MCPAuditLogger.logResourceRead( principal: context.principal, + client: MCPAuditLogger.clientName(for: context.meta), uri: Self.auditUri(name: name), outcome: .success ) @@ -50,6 +51,7 @@ public struct PromptsGetHandler: MCPMethodHandler { let protocolError = error as? MCPProtocolError MCPAuditLogger.logResourceRead( principal: context.principal, + client: MCPAuditLogger.clientName(for: context.meta), uri: Self.auditUri(name: name), outcome: protocolError?.code == JsonRpcErrorCode.forbidden ? .denied : .error, errorMessage: protocolError?.message ?? error.localizedDescription diff --git a/apple/TablePro/Core/MCP/Protocol/Handlers/ResourcesReadHandler.swift b/apple/TablePro/Core/MCP/Protocol/Handlers/ResourcesReadHandler.swift index 73ebc728f1..99da848d08 100644 --- a/apple/TablePro/Core/MCP/Protocol/Handlers/ResourcesReadHandler.swift +++ b/apple/TablePro/Core/MCP/Protocol/Handlers/ResourcesReadHandler.swift @@ -27,6 +27,7 @@ public struct ResourcesReadHandler: MCPMethodHandler { Self.logger.debug("resources/read uri=\(uri, privacy: .private(mask: .hash))") MCPAuditLogger.logResourceRead( principal: context.principal, + client: MCPAuditLogger.clientName(for: context.meta), uri: uri, outcome: .success ) @@ -38,6 +39,7 @@ public struct ResourcesReadHandler: MCPMethodHandler { } catch { MCPAuditLogger.logResourceRead( principal: context.principal, + client: MCPAuditLogger.clientName(for: context.meta), uri: uri, outcome: .error, errorMessage: (error as? MCPProtocolError)?.message ?? error.localizedDescription diff --git a/apple/TablePro/Core/MCP/Protocol/Handlers/ToolsCallHandler.swift b/apple/TablePro/Core/MCP/Protocol/Handlers/ToolsCallHandler.swift index df4650c1b0..a7c4324785 100644 --- a/apple/TablePro/Core/MCP/Protocol/Handlers/ToolsCallHandler.swift +++ b/apple/TablePro/Core/MCP/Protocol/Handlers/ToolsCallHandler.swift @@ -120,6 +120,7 @@ public struct ToolsCallHandler: MCPMethodHandler { ) { MCPAuditLogger.logToolCalled( principal: context.principal, + client: MCPAuditLogger.clientName(for: context.meta), toolName: tool, connectionId: connectionId, outcome: outcome, diff --git a/apple/TablePro/Core/MCP/Protocol/MCPProtocolDispatcher.swift b/apple/TablePro/Core/MCP/Protocol/MCPProtocolDispatcher.swift index 1135d5525e..701de80598 100644 --- a/apple/TablePro/Core/MCP/Protocol/MCPProtocolDispatcher.swift +++ b/apple/TablePro/Core/MCP/Protocol/MCPProtocolDispatcher.swift @@ -21,6 +21,10 @@ public actor MCPProtocolDispatcher { public static let deadlineExemptMethods: Set = ["subscriptions/listen"] + // Needs no scope and opens no connection. The bridge and the tablepro command probe with it before + // every session, so recording it listed them as clients of their own. + public static let activityExemptMethods: Set = ["server/discover"] + internal static let legacyInitializeMethod = "initialize" internal static let legacySessionHeader = "Mcp-Session-Id" internal static let cancelledNotificationMethod = "notifications/cancelled" @@ -99,6 +103,16 @@ public actor MCPProtocolDispatcher { return count } + // Ends one client's requests without touching the credential it shares with other stdio clients. + @discardableResult + public func cancelInflight(matchingClientId clientId: String) async -> Int { + let count = await inflight.cancelAll(matchingClientId: clientId, reason: .clientDisconnected) + if count > 0 { + Self.logger.info("Cancelled \(count, privacy: .public) in-flight request(s) for a disconnected client") + } + return count + } + // For a superseded credential: its requests may finish, but none outlives the credential's own expiry. public func cancelInflight(matchingTokenId tokenId: UUID, at deadline: Date) async { let clock = self.clock diff --git a/apple/TablePro/Core/MCP/Protocol/Tools/ToolQueryExecutor.swift b/apple/TablePro/Core/MCP/Protocol/Tools/ToolQueryExecutor.swift index 81d490792e..433f6a0689 100644 --- a/apple/TablePro/Core/MCP/Protocol/Tools/ToolQueryExecutor.swift +++ b/apple/TablePro/Core/MCP/Protocol/Tools/ToolQueryExecutor.swift @@ -18,6 +18,7 @@ enum ToolQueryExecutor { maxRows: maxRows, timeoutSeconds: timeoutSeconds, principal: context.principal, + client: MCPAuditLogger.clientName(for: context.meta), cancellation: context.cancellation, secrets: secrets, source: historySource(for: context), @@ -36,6 +37,7 @@ enum ToolQueryExecutor { maxRows: Int, timeoutSeconds: Int, principal: MCPPrincipal, + client: String? = nil, cancellation: MCPCancellationToken? = nil, secrets: [String] = [], source: QueryHistorySource = .mcp, @@ -45,6 +47,7 @@ enum ToolQueryExecutor { services: services, approved: operation, principal: principal, + client: client, secrets: secrets, source: source ) { @@ -73,6 +76,7 @@ enum ToolQueryExecutor { services: services, approved: operation, principal: context.principal, + client: MCPAuditLogger.clientName(for: context.meta), secrets: secrets, source: historySource(for: context) ) { @@ -91,6 +95,7 @@ enum ToolQueryExecutor { services: MCPToolServices, approved: ApprovedOperation, principal: MCPPrincipal, + client: String?, secrets: [String], source: QueryHistorySource, operation: () async throws -> (Output, Int) @@ -122,6 +127,7 @@ enum ToolQueryExecutor { ) MCPAuditLogger.logQueryExecuted( principal: principal, + client: client, connectionId: connectionId, sql: query, durationMs: Int(elapsed * 1_000), @@ -146,6 +152,7 @@ enum ToolQueryExecutor { ) MCPAuditLogger.logQueryExecuted( principal: principal, + client: client, connectionId: connectionId, sql: query, durationMs: Int(elapsed * 1_000), @@ -208,9 +215,7 @@ enum ToolQueryExecutor { return MCPToolExecutionError.queryFailed(MCPErrorRedactor.message(for: error, secrets: secrets)) } - /// An MCP query has no tab and no window of its own, so its completion is owned by the - /// connection. Clicking the notification brings the connection's most recent window forward - /// rather than focusing a tab that never existed. + // An MCP query has no tab, so its notification brings the connection's most recent window forward. @MainActor private static func reportMcpQueryFinished( _ outcome: OperationOutcome, diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift index ffb2448528..a67a39c49b 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift @@ -1,8 +1,3 @@ -// -// LaunchIntentRouter.swift -// TablePro -// - import AppKit import Foundation import os @@ -75,16 +70,31 @@ internal final class LaunchIntentRouter { } } - /// No alert on refusal: the bridge reads the refusal file and tells its client, and an alert - /// would greet every client that tries while MCP is off. + // No alert: the bridge reads the refusal file and tells its client, and an alert would greet every + // client that tries while MCP is off or broken. private func startMCPServer() async { + let quits = await Self.startMCPServerLeavesNothingToDo( + manager: MCPServerManager.shared, + isIdleMachineSession: { AppActivationPolicyController.shared.isIdleMachineSession } + ) + guard quits else { return } + NSApp.terminate(nil) + } + + // A launch made only to serve MCP has nothing left to do once the server is refused or fails to start. + internal static func startMCPServerLeavesNothingToDo( + manager: MCPServerManager, + isIdleMachineSession: () -> Bool + ) async -> Bool { do { - try await MCPServerManager.shared.lazyStart() + try await manager.lazyStart() } catch { - Self.logger.info("start-mcp refused: \(error.publicLogShape, privacy: .public)") - guard AppActivationPolicyController.shared.isIdleMachineSession else { return } - NSApp.terminate(nil) + logger.info("start-mcp refused: \(error.publicLogShape, privacy: .public)") + return isIdleMachineSession() } + guard case .failed = manager.state else { return false } + logger.error("start-mcp failed: the MCP server did not start") + return isIdleMachineSession() } private func installPlugin(_ url: URL) async throws { diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 2048ba13f6..8c76e0547b 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -169,6 +169,7 @@ final class AppSettingsManager: ObservableObject { didSet { guard !isValidating else { return } var validated = mcp + validated.port = mcp.validatedPort validated.maxRowLimit = mcp.validatedMaxRowLimit validated.defaultRowLimit = mcp.validatedDefaultRowLimit validated.queryTimeoutSeconds = mcp.validatedQueryTimeoutSeconds diff --git a/apple/TablePro/Core/Utilities/SQL/CsvRowConverter.swift b/apple/TablePro/Core/Utilities/SQL/CsvRowConverter.swift index e611a514d3..9fde311c93 100644 --- a/apple/TablePro/Core/Utilities/SQL/CsvRowConverter.swift +++ b/apple/TablePro/Core/Utilities/SQL/CsvRowConverter.swift @@ -46,10 +46,20 @@ internal struct CsvRowConverter { // An unquoted field holds no quote, so wrapping it for its edge spaces needs no escaping. static func encode(_ value: String) -> String { - let field = PluginRowWriters.csvField(value, options: fieldOptions) + encode(value, options: fieldOptions) + } + + // For a file the user opens in a spreadsheet, where a field another program wrote must not run as a formula. + static func encodeForSpreadsheet(_ value: String) -> String { + encode(value, options: spreadsheetFieldOptions) + } + + private static func encode(_ value: String, options: PluginCsvWriteOptions) -> String { + let field = PluginRowWriters.csvField(value, options: options) guard field.unicodeScalars.first != "\"", value.hasPrefix(" ") || value.hasSuffix(" ") else { return field } return "\"\(field)\"" } private static let fieldOptions = PluginCsvWriteOptions(sanitizesFormulas: false) + private static let spreadsheetFieldOptions = PluginCsvWriteOptions(sanitizesFormulas: true) } diff --git a/apple/TablePro/Models/AI/AIModels.swift b/apple/TablePro/Models/AI/AIModels.swift index 778b3a5af8..ccc9918338 100644 --- a/apple/TablePro/Models/AI/AIModels.swift +++ b/apple/TablePro/Models/AI/AIModels.swift @@ -104,21 +104,21 @@ enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { /// The types `OpenAICompatibleProvider` serves, which share one registration. static let openAICompatibleFamily: [AIProviderType] = [.openRouter, .openCode, .ollama, .llamaCpp, .mlx, .custom] - var symbolName: String { + var icon: BrandIcon { switch self { - case .copilot: return "chevron.left.forwardslash.chevron.right" - case .chatgptCodex: return "bubble.left.and.bubble.right" - case .claude: return "brain" - case .claudeAgent: return "terminal" - case .openAI: return "cpu" - case .openRouter: return "globe" - case .gemini: return "wand.and.stars" - case .xai: return "x.circle" - case .ollama: return "desktopcomputer" - case .llamaCpp: return "memorychip" - case .mlx: return "m.square" - case .openCode: return "sparkles" - case .custom: return "server.rack" + case .copilot: return BrandIcon(slug: "githubcopilot", fallbackSystemImage: "chevron.left.forwardslash.chevron.right") + case .chatgptCodex: return BrandIcon(slug: "openai", fallbackSystemImage: "bubble.left.and.bubble.right") + case .claude: return BrandIcon(slug: "claude", fallbackSystemImage: "brain") + case .claudeAgent: return BrandIcon(slug: "claudecode", fallbackSystemImage: "terminal") + case .openAI: return BrandIcon(slug: "openai", fallbackSystemImage: "cpu") + case .openRouter: return BrandIcon(slug: "openrouter", fallbackSystemImage: "globe") + case .gemini: return BrandIcon(slug: "googlegemini", fallbackSystemImage: "wand.and.stars") + case .xai: return BrandIcon(slug: "xai", fallbackSystemImage: "x.circle") + case .ollama: return BrandIcon(slug: "ollama", fallbackSystemImage: "desktopcomputer") + case .llamaCpp: return BrandIcon(slug: "llamacpp", fallbackSystemImage: "memorychip") + case .mlx: return BrandIcon(slug: "mlx", fallbackSystemImage: "m.square") + case .openCode: return BrandIcon(slug: "opencode", fallbackSystemImage: "sparkles") + case .custom: return BrandIcon(slug: nil, fallbackSystemImage: "server.rack") } } } @@ -195,7 +195,7 @@ struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { name.isEmpty ? kindName : name } - var symbolName: String { preset?.symbolName ?? type.symbolName } + var icon: BrandIcon { preset?.icon ?? type.icon } var authStyle: AIProviderType.AuthStyle { preset?.authStyle ?? type.authStyle } diff --git a/apple/TablePro/Models/AI/AIProviderPreset.swift b/apple/TablePro/Models/AI/AIProviderPreset.swift index 4de1f96518..9021669d47 100644 --- a/apple/TablePro/Models/AI/AIProviderPreset.swift +++ b/apple/TablePro/Models/AI/AIProviderPreset.swift @@ -10,7 +10,7 @@ struct AIProviderPreset: Identifiable, Equatable, Sendable { let id: String let displayName: String let endpoint: String - let symbolName: String + let icon: BrandIcon let authStyle: AIProviderType.AuthStyle // A 403 for a wrong key would otherwise read as a server error, which the chat offers to retry. let rejectsBadKeyWithForbidden: Bool @@ -24,7 +24,7 @@ struct AIProviderPreset: Identifiable, Equatable, Sendable { id: String, displayName: String, endpoint: String, - symbolName: String, + icon: BrandIcon, authStyle: AIProviderType.AuthStyle, rejectsBadKeyWithForbidden: Bool, curatedModels: [CuratedModel] = [], @@ -34,7 +34,7 @@ struct AIProviderPreset: Identifiable, Equatable, Sendable { self.id = id self.displayName = displayName self.endpoint = endpoint - self.symbolName = symbolName + self.icon = icon self.authStyle = authStyle self.rejectsBadKeyWithForbidden = rejectsBadKeyWithForbidden self.curatedModels = curatedModels @@ -46,7 +46,7 @@ struct AIProviderPreset: Identifiable, Equatable, Sendable { id: "requesty", displayName: "Requesty", endpoint: "https://router.requesty.ai", - symbolName: "arrow.triangle.branch", + icon: BrandIcon(slug: "requesty", fallbackSystemImage: "arrow.triangle.branch"), authStyle: .apiKey, rejectsBadKeyWithForbidden: true ) @@ -63,7 +63,7 @@ struct AIProviderPreset: Identifiable, Equatable, Sendable { id: "meta", displayName: "Meta", endpoint: "https://api.meta.ai", - symbolName: "infinity.circle", + icon: BrandIcon(slug: "meta", fallbackSystemImage: "infinity.circle"), authStyle: .apiKey, rejectsBadKeyWithForbidden: false, curatedModels: [ diff --git a/apple/TablePro/Models/AuditEntry.swift b/apple/TablePro/Models/AuditEntry.swift index 8b09a5f2f1..b19520f65c 100644 --- a/apple/TablePro/Models/AuditEntry.swift +++ b/apple/TablePro/Models/AuditEntry.swift @@ -1,8 +1,3 @@ -// -// AuditEntry.swift -// TablePro -// - import Foundation enum AuditCategory: String, Codable, CaseIterable, Sendable, Identifiable { @@ -63,6 +58,9 @@ struct AuditEntry: Codable, Identifiable, Sendable, Equatable, Hashable { let action: String let outcome: String let details: String? + // The name the client reported for itself, never its token. Nil for rows no client caused and for + // rows written before the log recorded it. + let clientName: String? init( id: UUID = UUID(), @@ -73,7 +71,8 @@ struct AuditEntry: Codable, Identifiable, Sendable, Equatable, Hashable { connectionId: UUID? = nil, action: String, outcome: String, - details: String? = nil + details: String? = nil, + clientName: String? = nil ) { self.id = id self.timestamp = timestamp @@ -84,6 +83,7 @@ struct AuditEntry: Codable, Identifiable, Sendable, Equatable, Hashable { self.action = action self.outcome = outcome self.details = details + self.clientName = clientName } init( @@ -95,7 +95,8 @@ struct AuditEntry: Codable, Identifiable, Sendable, Equatable, Hashable { connectionId: UUID? = nil, action: String, outcome: AuditOutcome, - details: String? = nil + details: String? = nil, + clientName: String? = nil ) { self.init( id: id, @@ -106,7 +107,8 @@ struct AuditEntry: Codable, Identifiable, Sendable, Equatable, Hashable { connectionId: connectionId, action: action, outcome: outcome.rawValue, - details: details + details: details, + clientName: clientName ) } } diff --git a/apple/TablePro/Models/Settings/MCPSettings.swift b/apple/TablePro/Models/Settings/MCPSettings.swift index a6d7eca727..2738d6364e 100644 --- a/apple/TablePro/Models/Settings/MCPSettings.swift +++ b/apple/TablePro/Models/Settings/MCPSettings.swift @@ -10,6 +10,9 @@ struct MCPSettings: Codable, Equatable { var connectionApproval: MCPConnectionApproval var allowsHiddenConnectionListing: Bool + // Linux takes the same range, so one client setup works against either app. + static let portRange: ClosedRange = 1_024...65_535 + static let `default` = MCPSettings( enabled: false, port: 23_508, @@ -46,7 +49,7 @@ struct MCPSettings: Codable, Equatable { let fallback = Self.default enabled = container.decodeSetting(.enabled, default: fallback.enabled) let rawPort = container.decodeSetting(.port, default: fallback.port) - port = (1...65_535).contains(rawPort) ? rawPort : fallback.port + port = Self.portRange.contains(rawPort) ? rawPort : fallback.port defaultRowLimit = container.decodeSetting(.defaultRowLimit, default: fallback.defaultRowLimit) maxRowLimit = container.decodeSetting(.maxRowLimit, default: fallback.maxRowLimit) queryTimeoutSeconds = container.decodeSetting(.queryTimeoutSeconds, default: fallback.queryTimeoutSeconds) @@ -61,6 +64,10 @@ struct MCPSettings: Codable, Equatable { queryTimeoutSeconds = validatedQueryTimeoutSeconds } + var validatedPort: Int { + port.clamped(to: Self.portRange) + } + var validatedMaxRowLimit: Int { maxRowLimit.clamped(to: SettingsValidationRules.mcpRowLimitRange) } diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 317814063a..2b00af6758 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -1292,6 +1292,9 @@ } } } + }, + "“%@” will be disconnected and its token revoked. Any in-flight requests will be cancelled." : { + }, "\"%@\" will be moved to Trash. You can recover it from there." : { "localizations" : { @@ -1492,6 +1495,12 @@ } } } + }, + "“%@”'s in-flight requests will be cancelled. It reconnects the next time it starts; to stop it, remove TablePro from it in Connect a Client." : { + + }, + "“%@”'s running requests will be cancelled, but it can send new ones right away. To stop it, remove TablePro from it in Connect a Client, or turn off the MCP server." : { + }, "“%1$@” could not be written. %2$@" : { "localizations" : { @@ -3176,6 +3185,9 @@ } } } + }, + "%@ connected" : { + }, "%@ connections do not support adding rows from Shortcuts." : { @@ -3219,6 +3231,9 @@ } } } + }, + "%@ connects with a token from Settings > MCP > Authentication, which can limit what it reaches. TablePro leaves it as is." : { + }, "%@ contains characters Spanner does not allow." : { "extractionState" : "manual", @@ -3277,6 +3292,9 @@ } } } + }, + "%@ could not be read as valid settings, so TablePro left it unchanged." : { + }, "%@ could not be updated" : { @@ -3295,6 +3313,9 @@ }, "%@ DDL" : { + }, + "%@ defines TablePro in a form TablePro cannot edit safely, so it left the file unchanged." : { + }, "%@ does not accept this column change." : { "localizations" : { @@ -3566,6 +3587,9 @@ } } } + }, + "%@ has an unexpected shape where TablePro would add itself, so TablePro left it unchanged." : { + }, "%@ has no column named %@" : { "localizations" : { @@ -3616,6 +3640,9 @@ }, "%@ has no recorded reads." : { + }, + "%@ has TablePro in one project only. Install adds it for every project." : { + }, "%@ holds a character macOS would turn into command line punctuation." : { "extractionState" : "manual", @@ -4237,6 +4264,18 @@ } } } + }, + "%@ is set up for a copy of TablePro that is no longer there." : { + + }, + "%@ is set up for a different copy of TablePro. Update points it to this one." : { + + }, + "%@ is set up with an address or token that no longer works." : { + + }, + "%@ is set up, but one project has its own older TablePro setup that wins there. Remove TablePro from that project's settings." : { + }, "%@ is showing another sheet. Close it, then try again." : { "localizations" : { @@ -4289,6 +4328,9 @@ "%@ isn't compiled for debugging." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%@ kept changing while TablePro wrote it. Try again." : { + }, "%@ lines have unreadable characters" : { "localizations" : { @@ -4566,6 +4608,9 @@ } } } + }, + "%@ names the same key twice, so TablePro left it unchanged." : { + }, "%@ needs %@." : { "extractionState" : "manual", @@ -4835,6 +4880,9 @@ } } } + }, + "%@ picks up the change right away." : { + }, "%@ Plan" : { @@ -4930,6 +4978,9 @@ } } } + }, + "%@ reaches MCP servers only from its maker's cloud, so it cannot reach TablePro on this Mac." : { + }, "%@ read" : { "extractionState" : "manual", @@ -5419,6 +5470,9 @@ } } } + }, + "%@ starts MCP servers only as local commands, so it cannot reach TablePro's HTTP server." : { + }, "%@ statement" : { @@ -5448,6 +5502,9 @@ } } } + }, + "%@ stops reaching your databases through TablePro." : { + }, "%@ succeeded" : { "extractionState" : "manual", @@ -7308,6 +7365,9 @@ "%1$@ is not a level %2$@ accepts. Use one of %3$@." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%1$@ is set up, but the project %2$@ has its own older TablePro setup that wins there. Remove TablePro from that project's settings." : { + }, "%1$@ is the local port, %2$@ and %3$@ are this connection's host and port. The command runs directly rather than through a shell, so start it with /usr/bin/env if you need environment variables." : { "localizations" : { @@ -7574,6 +7634,9 @@ }, "%1$@ rows modified since it was last analyzed, more than the %2$@ that start an autoanalyze." : { + }, + "%1$@ stops reaching your databases through TablePro. The current %2$@ is kept next to it as %3$@." : { + }, "%1$@ tables hold “%2$@”." : { @@ -20383,6 +20446,9 @@ } } } + }, + "Add it in %@'s settings" : { + }, "Add Jump Host" : { "localizations" : { @@ -20836,6 +20902,9 @@ } } } + }, + "Add this to %@:" : { + }, "Add to Favorites" : { "comment" : "A label that describes an action to add an item to a user's favorites.", @@ -21267,6 +21336,9 @@ } } } + }, + "Adds through the %@ command" : { + }, "Adjust Limit" : { "localizations" : { @@ -22717,6 +22789,9 @@ } } } + }, + "All clients" : { + }, "All collections" : { "extractionState" : "manual", @@ -33792,6 +33867,9 @@ } } } + }, + "Can't read settings" : { + }, "Can't read this folder" : { @@ -39550,6 +39628,15 @@ } } } + }, + "Claude Agent can't use this connection: TablePro couldn't create its access token. Try again." : { + + }, + "Claude Agent can't use this connection: TablePro couldn't save its access token to the Keychain. Try again." : { + + }, + "Claude Agent can't use this connection: TablePro couldn't write its MCP settings file. Try again." : { + }, "Claude Code" : { "localizations" : { @@ -41334,6 +41421,9 @@ } } } + }, + "Client List Unavailable" : { + }, "Client Secret" : { "localizations" : { @@ -41415,6 +41505,18 @@ } } } + }, + "Client: %@" : { + + }, + "Clients can connect once the MCP server is running." : { + + }, + "Clients can connect while the MCP server is on. Turn it on in Settings > MCP." : { + + }, + "Clients cannot connect until it runs. Open Settings > MCP to see why and try again." : { + }, "Clients will appear here while they have an active MCP session." : { "localizations" : { @@ -43294,6 +43396,9 @@ } } } + }, + "Code expires in ^[%lld second](inflect: true)" : { + }, "Code folding" : { "localizations" : { @@ -46931,6 +47036,9 @@ } } } + }, + "Configuration" : { + }, "Configure an active provider or turn on Apple Intelligence to enable inline suggestions." : { @@ -48021,6 +48129,9 @@ } } } + }, + "Connected just now" : { + }, "Connected Threads" : { "localizations" : { @@ -51293,6 +51404,12 @@ } } } + }, + "Copy Command" : { + + }, + "Copy Configuration" : { + }, "Copy Connection ID" : { "localizations" : { @@ -52349,6 +52466,9 @@ } } } + }, + "Copy Setup for %@" : { + }, "Copy Special" : { "localizations" : { @@ -52482,6 +52602,9 @@ } } } + }, + "Copy the command and run it in Terminal" : { + }, "Copy the full error to the clipboard" : { "localizations" : { @@ -52522,6 +52645,9 @@ } } } + }, + "Copy the setup into %@" : { + }, "Copy to" : { "localizations" : { @@ -55157,6 +55283,9 @@ } } } + }, + "Couldn't Create the Token" : { + }, "Couldn't Detach Partition" : { @@ -55194,6 +55323,9 @@ }, "Couldn't Import Formatter Rules" : { + }, + "Couldn't install" : { + }, "Couldn't Load" : { @@ -55419,6 +55551,9 @@ }, "Couldn't refresh the team library" : { + }, + "Couldn't remove" : { + }, "Couldn't Rename the Theme" : { @@ -55518,12 +55653,18 @@ } } } + }, + "Couldn't Save the Deletion" : { + }, "Couldn't Save the Revocation" : { }, "Couldn't start" : { + }, + "Couldn't update" : { + }, "Count" : { "localizations" : { @@ -62531,6 +62672,9 @@ } } } + }, + "Delete %d tokens?" : { + }, "Delete %lld columns?" : { "localizations" : { @@ -69839,6 +69983,9 @@ } } } + }, + "e.g., Cursor on my Mac" : { + }, "Each array element must be a JSON object" : { "extractionState" : "manual", @@ -71316,6 +71463,9 @@ "Editor Text" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Edits %@" : { + }, "Effective" : { "localizations" : { @@ -84285,6 +84435,9 @@ }, "Findings the check reported" : { + }, + "Finish in %@" : { + }, "Finish Signing In" : { "localizations" : { @@ -87621,6 +87774,9 @@ } } } + }, + "Give your client this address and header:" : { + }, "global" : { "localizations" : { @@ -96386,6 +96542,12 @@ }, "Install %@…" : { + }, + "Install adds TablePro to a client on this Mac. Select a client to see its settings and set it up by hand." : { + + }, + "Install in %@" : { + }, "Install it with “brew install libpq” and link it." : { "localizations" : { @@ -96562,6 +96724,9 @@ }, "Install Update…" : { + }, + "Install…" : { + }, "Installed" : { "localizations" : { @@ -106708,6 +106873,10 @@ } } }, + "Local socket" : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "Locale Provider" : { "extractionState" : "manual", "generatesSymbol" : false, @@ -107357,6 +107526,9 @@ } } } + }, + "macOS could not generate a secure token. Try again." : { + }, "macOS will ask for your login password" : { "localizations" : { @@ -109823,6 +109995,18 @@ } } } + }, + "MCP Server Couldn't Start" : { + + }, + "MCP Server Not Running" : { + + }, + "MCP Server Off" : { + + }, + "MCP Server Starting" : { + }, "MCP Server: Running (%d clients)" : { "extractionState" : "stale", @@ -123535,6 +123719,9 @@ } } } + }, + "Not found" : { + }, "Not found (404) at %@. Check the Base URL and the model." : { "localizations" : { @@ -126577,6 +126764,9 @@ } } } + }, + "Old setup in a project" : { + }, "Ollama is running but has no models. Run \"ollama pull \" to download one." : { "localizations" : { @@ -126957,6 +127147,9 @@ } } } + }, + "On This Mac" : { + }, "On Update" : { "extractionState" : "manual", @@ -127157,6 +127350,9 @@ } } } + }, + "One project only" : { + }, "One report a day: hashed Mac ID, versions, architecture, language, database types, connection count, license status, update settings, first-use dates. Never hostnames, credentials, queries, or rows." : { "localizations" : { @@ -129963,6 +130159,9 @@ } } } + }, + "Opens %@ to confirm" : { + }, "Opens a database connection in TablePro" : { @@ -131029,6 +131228,12 @@ } } } + }, + "Other Client" : { + + }, + "Other Clients" : { + }, "Other rows hold exactly the same values, so the change cannot reach this row alone." : { @@ -131089,6 +131294,9 @@ } } } + }, + "Out of date" : { + }, "out-of-band check" : { "extractionState" : "manual", @@ -136431,6 +136639,19 @@ } } } + }, + "Port %d cannot be used. Choose a port from %d to %d." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Port %1$d cannot be used. Choose a port from %2$d to %3$d." + } + } + } + }, + "Port %d was in use, so this address changes when TablePro restarts." : { + }, "Port %d was in use." : { @@ -142629,6 +142850,9 @@ } } } + }, + "Quit and reopen %@ to load it." : { + }, "Quit Anyway" : { "localizations" : { @@ -143906,6 +144130,9 @@ } } } + }, + "Reaches only servers on the internet" : { + }, "Read" : { "localizations" : { @@ -147098,6 +147325,9 @@ } } } + }, + "Reload %@ to load it." : { + }, "Reload from Disk" : { "localizations" : { @@ -148715,6 +148945,9 @@ "Remove SET transaction_timeout from the routine to debug it." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Remove TablePro from %@?" : { + }, "Remove tag %@" : { "comment" : "A label for a button that removes a tag from a list of selected tags. The argument is the name of the tag to be removed.", @@ -148909,6 +149142,9 @@ }, "Removing" : { + }, + "Removing…" : { + }, "Rename" : { "localizations" : { @@ -156461,6 +156697,9 @@ } } } + }, + "Run this in Terminal:" : { + }, "Run WATCH again before starting the block." : { "extractionState" : "manual", @@ -161991,6 +162230,9 @@ } } } + }, + "Select a client to see how TablePro connects to it." : { + }, "Select a column" : { @@ -165341,6 +165583,15 @@ } } } + }, + "Set up" : { + + }, + "Set up an app to use TablePro's MCP server" : { + + }, + "Set up with a token" : { + }, "Set Value" : { "localizations" : { @@ -165502,6 +165753,9 @@ } } } + }, + "Settings file" : { + }, "Settings:" : { "extractionState" : "stale", @@ -174322,6 +174576,9 @@ }, "Start" : { + }, + "Start a new %@ session to load it." : { + }, "Start one to ask about this connection." : { "localizations" : { @@ -174468,6 +174725,9 @@ "Starts" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Starts only local command servers" : { + }, "starts with" : { "localizations" : { @@ -181667,6 +181927,9 @@ }, "TablePro could not check whether %@ sends the password in plain text without TLS. Try again, or set SSL Mode to Required." : { + }, + "TablePro could not confirm its change to %@. Check the file before you try again." : { + }, "TablePro could not do this for you. Run this in Terminal instead:" : { "extractionState" : "stale", @@ -181784,6 +182047,12 @@ }, "TablePro could not reach the Schema Registry: %@" : { + }, + "TablePro could not read %@'s settings file, so it leaves the file alone. Copy the setup and add it by hand." : { + + }, + "TablePro could not read its list of clients. Reinstall TablePro to restore it." : { + }, "TablePro could not read its query history, so it moved the file aside as “%@” and started a new one. The copy stays until you delete it or clear all of your history." : { @@ -181810,6 +182079,9 @@ }, "TablePro could not read the Table Health history: %@" : { + }, + "TablePro could not read the tokens saved in the Keychain, so it will not save a new one over them. Restart TablePro and try again." : { + }, "TablePro could not read what this connection is holding, so it kept the file." : { "extractionState" : "manual", @@ -181834,6 +182106,9 @@ }, "TablePro could not save the Table Health history: %@" : { + }, + "TablePro could not save the token to the Keychain, so it was not created. Try again." : { + }, "TablePro could not tell how this Dameng server treats backslashes, so it will not send a value that contains one. Reconnect, then try again." : { "extractionState" : "manual", @@ -181859,6 +182134,9 @@ }, "TablePro could not verify your license with the server. Connect to the internet, then check again." : { + }, + "TablePro could not write %@." : { + }, "TablePro could not write the CA bundle DuckDB reads: %@" : { "extractionState" : "manual", @@ -181870,6 +182148,9 @@ "TablePro couldn't confirm that the routine ended. It may still be running on the server." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "TablePro couldn't create a token for this client, so the client wasn't paired. Try pairing again." : { + }, "TablePro couldn't reach the plugin registry to update this plugin. Check your connection and reopen TablePro." : { "localizations" : { @@ -181916,6 +182197,9 @@ }, "TablePro couldn't reach the team library." : { + }, + "TablePro couldn't save a token for this client to the Keychain, so the client wasn't paired. Try pairing again." : { + }, "TablePro Data Was Removed from iCloud" : { "extractionState" : "manual", @@ -182463,6 +182747,12 @@ } } } + }, + "TablePro is turned off in %1$@. Turn it on in %1$@'s MCP settings to use it." : { + + }, + "TablePro moved" : { + }, "TablePro on iPhone and iPad can't connect to %1$@ with the SSL mode %2$@." : { "extractionState" : "manual", @@ -182768,6 +183058,9 @@ } } } + }, + "TablePro's client list has a setup for this client that it cannot fill in." : { + }, "TablePro's data is no longer in iCloud. It may have been deleted in iCloud settings. Upload what this Mac has again, or turn off sync to keep it on this Mac only." : { @@ -185413,6 +185706,19 @@ } } } + }, + "The %@ command did not finish within %d seconds." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "The %1$@ command did not finish within %2$d seconds." + } + } + } + }, + "The %@ command is no longer installed." : { + }, "The %@ command line tool is not installed." : { "localizations" : { @@ -185454,6 +185760,16 @@ } } }, + "The %@ command stopped with exit code %d." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "The %1$@ command stopped with exit code %2$d." + } + } + } + }, "The %@ filter is not available for Neo4j." : { "extractionState" : "manual", "generatesSymbol" : false @@ -190597,6 +190913,15 @@ }, "The MCP server could not prepare its private socket folder." : { + }, + "The MCP server is not running, so clients you add cannot connect yet. Turn it on in Settings > MCP." : { + + }, + "The MCP server is not running, so TablePro cannot change its tokens now. Start the server, then try again." : { + + }, + "The MCP server is not running, so TablePro cannot save a token now. Start the server, then try again." : { + }, "The MCP server is turned off. Turn it on in Settings > MCP." : { @@ -197200,6 +197525,9 @@ "These theme keys need theme format %1$d: %2$@." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "These tokens will be permanently deleted. External clients using them will lose access immediately." : { + }, "These two engines cannot share a script." : { "localizations" : { @@ -205200,6 +205528,12 @@ } } } + }, + "Tokens are not available" : { + + }, + "Tokens load while the MCP server is running." : { + }, "Too Large to Compare" : { @@ -207462,6 +207796,9 @@ } } } + }, + "Turned off" : { + }, "Two columns are both named “%@”. Rename one, then save again." : { "localizations" : { @@ -210500,6 +210837,9 @@ } } } + }, + "Update in %@" : { + }, "Update Now" : { "localizations" : { @@ -210770,6 +211110,9 @@ } } } + }, + "Update…" : { + }, "Updated" : { "localizations" : { @@ -212602,6 +212945,9 @@ } } } + }, + "Uses another copy" : { + }, "Uses the access key stored in ~/.aws/credentials." : { "localizations" : { diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml b/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml index ad828ffcdf..b499b5b99f 100644 --- a/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml +++ b/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml @@ -269,6 +269,21 @@ LICENSE at the tag is byte-identical to the Go distribution''s LICENSE, but this is a separate module with its own version, so it has its own entry. Reaches users only through the registry-only SAP HANA plugin.' +- id: goose + name: goose + version: vendored at bf760fd63, 2025-03-24 + spdx: Apache-2.0 + copyrights: + - Copyright 2024 Block, Inc. + homepageURL: https://github.com/aaif-goose/goose + licenseTextURL: https://github.com/aaif-goose/goose/blob/bf760fd630b9accd1eff63adba24798d6bf7413a/LICENSE + textFile: texts/goose.txt + source: manual + patched: false + platforms: [macos] + notes: The goose logo only (TablePro/Assets.xcassets/goose-icon.imageset/goose.svg), byte-identical to + documentation/static/img/goose.svg at bf760fd630b9 (block/goose, now aaif-goose/goose). No code ships. The + repository has no NOTICE file. The mark is the project's trademark; the licence covers the file only. - id: vscode-theme-gruvbox name: Gruvbox Theme version: 1.29.1 @@ -360,6 +375,20 @@ Two clause BSD license", and the inet_pton / inet_ntop implementations in src/inet.c, "copyright the Internet Systems Consortium, Inc.", ISC licence. The repo also has LICENSE-docs (documentation only, not linked).' +- id: llama-cpp + name: llama.cpp + version: vendored at ef9c13d4c, 2026-06-24 + spdx: MIT + copyrights: + - Copyright (c) 2023-2026 The ggml authors + homepageURL: https://github.com/ggml-org/llama.cpp + licenseTextURL: https://github.com/ggml-org/llama.cpp/blob/ef9c13d4c27f1ad9804341a0187c33b621609c63/LICENSE + textFile: texts/llama-cpp.txt + source: manual + patched: false + platforms: [macos] + notes: The llama.cpp logo only (TablePro/Assets.xcassets/llamacpp-icon.imageset/llamacpp.svg), byte-identical + to tools/ui/src/lib/assets/logo.svg at ef9c13d4c27f. No code ships. - id: mariadb-connector-c name: MariaDB Connector/C version: 3.4.4 @@ -387,6 +416,22 @@ LGPL: shipping the app must keep the relinking route open (object files or the shipped .a plus the licence text). The build uses Homebrew openssl@3, not the pinned OpenSSL. scripts/ios/build-mariadb-ios.sh pins the same 3.4.4.' +- id: mlx + name: MLX + version: vendored at 9ab391356, 2026-03-24 + spdx: MIT + copyrights: + - Copyright (c) 2023 Apple Inc. + homepageURL: https://github.com/ml-explore/mlx + licenseTextURL: https://github.com/ml-explore/mlx/blob/9ab3913567df16cac539dce7b4e5d569897a1c29/LICENSE + textFile: texts/mlx.txt + source: manual + patched: false + platforms: [macos] + notes: The MLX logo only (TablePro/Assets.xcassets/mlx-icon.imageset/mlx.pdf and mlx-dark.pdf), byte-identical + to docs/logo/mlx_logo.pdf and mlx_logo_dark.pdf at 9ab3913567df. The PDFs, not the SVGs beside them, because + the SVGs draw their glyphs through and render empty in AppKit. No code ships. The original LICENSE + writes the copyright sign; this YAML is ASCII-folded. - id: mongo-c-driver name: MongoDB C Driver (libmongoc / libbson) version: 1.28.1 @@ -406,6 +451,20 @@ grant), mongoc.css_t, zlib, common-md5.c and utf8proc. The full text is saved in the extra text file. Tarball is the GitHub release archive for 1.28.1, pinned by SHA-256. The script writes the flat Libs/libmongoc.a and Libs/libbson.a itself.' +- id: n8n-requesty + name: Requesty n8n node + version: vendored at 6aeafb9e9, 2026-06-02 + spdx: MIT + copyrights: + - Copyright (c) 2024 Requesty + homepageURL: https://github.com/requestyai/n8n-requesty + licenseTextURL: https://github.com/requestyai/n8n-requesty/blob/6aeafb9e98d8b2b783a1316f2a038cf1b729dab4/LICENSE + textFile: texts/n8n-requesty.txt + source: manual + patched: false + platforms: [macos] + notes: The Requesty logo only (TablePro/Assets.xcassets/requesty-icon.imageset/requesty.svg), byte-identical to + icons/requesty.svg at 6aeafb9e98d8, the commit "use official Requesty bubble logo as node icon". No code ships. - id: nord-visual-studio-code name: Nord Visual Studio Code version: vendored at 8ead09822, 2023-05-03 @@ -468,6 +527,21 @@ Atom's original One Light palette (styles/colors.less and styles/syntax-variables.less, package version 1.8.4; the repository is archived) supplies its git colors and confirms the editor values. No code or file from the project ships. +- id: openai-realtime-console + name: OpenAI Realtime Console + version: vendored at 758faf83a, 2024-12-19 + spdx: MIT + copyrights: + - Copyright (c) 2024 OpenAI + homepageURL: https://github.com/openai/openai-realtime-console + licenseTextURL: https://github.com/openai/openai-realtime-console/blob/758faf83a11d0026baafeb7bc072ee2eb9f1c2f9/LICENSE + textFile: texts/openai-realtime-console.txt + source: manual + patched: false + platforms: [macos] + notes: The OpenAI logomark only (TablePro/Assets.xcassets/openai-icon.imageset/openai.svg), byte-identical to + client/assets/openai-logomark.svg at 758faf83a11d, the same bytes as public/openai-logomark.svg in + openai/openai-realtime-agents. No code ships. The mark is an OpenAI trademark (openai.com/brand). - id: openssl name: OpenSSL version: 3.5.9 @@ -562,6 +636,21 @@ file. The COPYRIGHT text is the whole licence; SPDX calls it "PostgreSQL" (a BSD/MIT-style permissive licence), not BSD-2-Clause. The same build also emits Libs/libssl_*.a and Libs/libcrypto_*.a, which are OpenSSL, not PostgreSQL. scripts/ios/build-libpq-ios.sh pins the same 17.4. +- id: primer-octicons + name: Primer Octicons + version: copilot-24, through Simple Icons 16.37.0 + spdx: MIT + copyrights: + - Copyright (c) 2026 GitHub Inc. + homepageURL: https://github.com/primer/octicons + licenseTextURL: https://github.com/primer/octicons/blob/41c780575654fe4fef3fc4e91a46c8c0e91b233b/LICENSE + textFile: texts/primer-octicons.txt + source: manual + patched: false + platforms: [macos] + notes: The GitHub Copilot mark only (TablePro/Assets.xcassets/githubcopilot-icon.imageset/githubcopilot.svg), + byte-identical to icons/githubcopilot.svg in the simple-icons 16.37.0 npm package, whose data file records + its source as https://primer.style/foundations/icons/copilot-24 and its license as MIT. No code ships. - id: rearrange name: Rearrange version: 2.1.1 diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/texts/goose.txt b/apple/TablePro/Resources/ThirdPartyLicenses/texts/goose.txt new file mode 100644 index 0000000000..c83043d449 --- /dev/null +++ b/apple/TablePro/Resources/ThirdPartyLicenses/texts/goose.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Block, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/texts/llama-cpp.txt b/apple/TablePro/Resources/ThirdPartyLicenses/texts/llama-cpp.txt new file mode 100644 index 0000000000..e7dca554bc --- /dev/null +++ b/apple/TablePro/Resources/ThirdPartyLicenses/texts/llama-cpp.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-2026 The ggml authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/texts/mlx.txt b/apple/TablePro/Resources/ThirdPartyLicenses/texts/mlx.txt new file mode 100644 index 0000000000..98ff47b9ef --- /dev/null +++ b/apple/TablePro/Resources/ThirdPartyLicenses/texts/mlx.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2023 Apple Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/texts/n8n-requesty.txt b/apple/TablePro/Resources/ThirdPartyLicenses/texts/n8n-requesty.txt new file mode 100644 index 0000000000..f91f5414c7 --- /dev/null +++ b/apple/TablePro/Resources/ThirdPartyLicenses/texts/n8n-requesty.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Requesty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/texts/openai-realtime-console.txt b/apple/TablePro/Resources/ThirdPartyLicenses/texts/openai-realtime-console.txt new file mode 100644 index 0000000000..91ba98f3a2 --- /dev/null +++ b/apple/TablePro/Resources/ThirdPartyLicenses/texts/openai-realtime-console.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 OpenAI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/texts/primer-octicons.txt b/apple/TablePro/Resources/ThirdPartyLicenses/texts/primer-octicons.txt new file mode 100644 index 0000000000..aa1fa80ed8 --- /dev/null +++ b/apple/TablePro/Resources/ThirdPartyLicenses/texts/primer-octicons.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 GitHub Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apple/TablePro/Views/AIChat/AIChatPanelView.swift b/apple/TablePro/Views/AIChat/AIChatPanelView.swift index 4f4a0c1ee9..7f86511411 100644 --- a/apple/TablePro/Views/AIChat/AIChatPanelView.swift +++ b/apple/TablePro/Views/AIChat/AIChatPanelView.swift @@ -320,14 +320,7 @@ struct AIChatPanelView: View { } } - /// Sized to the model's name, and able to compress below it. - /// - /// Its label used to carry `maxWidth: .infinity`, which spread the button across the window as - /// soon as the conversation had one to spread across. `.fixedSize()` is the other end of the same - /// mistake: measured on macOS 27, a 44-character model name holds the button at 339pt, which - /// overflows the trailing pane's composer row by 85pt at 240pt wide. Unframed it takes the name's - /// width where there is room and truncates where there is not, and the spacer after it is what - /// keeps Send at the trailing edge in both widths. + // No frame and no .fixedSize(): a 44-character model name held a fixed-size button at 339 pt, 85 pt past a 240 pt pane (macOS 27). @ViewBuilder private var modelPicker: some View { let providers = settingsManager.ai.providers @@ -341,6 +334,7 @@ struct AIChatPanelView: View { let label = selectedProvider.map { provider in resolvedModel.isEmpty ? provider.displayName : resolvedModel } ?? String(localized: "Select Model") + let icon = selectedProvider?.icon ?? BrandIcon(slug: nil, fallbackSystemImage: "cpu") Menu { ForEach(providers) { provider in @@ -352,7 +346,7 @@ struct AIChatPanelView: View { } } label: { HStack(spacing: 4) { - Image(systemName: "cpu") + icon.menuImage(pointSize: 12) Text(label) .lineLimit(1) .truncationMode(.middle) diff --git a/apple/TablePro/Views/Components/BrandIconView.swift b/apple/TablePro/Views/Components/BrandIconView.swift new file mode 100644 index 0000000000..bfb2e1cb1f --- /dev/null +++ b/apple/TablePro/Views/Components/BrandIconView.swift @@ -0,0 +1,97 @@ +// +// BrandIconView.swift +// TablePro +// + +import AppKit +import SwiftUI + +internal struct BrandIcon: Equatable, Sendable { + internal let slug: String? + internal let fallbackSystemImage: String + + internal init(slug: String?, fallbackSystemImage: String) { + self.slug = slug + self.fallbackSystemImage = fallbackSystemImage + } + + internal static func assetName(for slug: String) -> String { + "\(slug)-icon" + } + + internal var assetName: String? { + slug.map(Self.assetName(for:)) + } + + internal var assetImage: NSImage? { + assetName.flatMap { NSImage(named: $0) } + } + + // An NSMenu draws an asset at its intrinsic size (Kiro's is 1200 pt), so menus get a copy drawn into a fixed square. + internal func nsImage(pointSize: CGFloat = 16, accessibilityDescription: String? = nil) -> NSImage? { + guard let asset = assetImage else { + return NSImage(systemSymbolName: fallbackSystemImage, accessibilityDescription: accessibilityDescription) + } + let image = NSImage(size: NSSize(width: pointSize, height: pointSize), flipped: false) { rect in + asset.draw(in: Self.aspectFit(asset.size, in: rect)) + return true + } + image.isTemplate = asset.isTemplate + image.accessibilityDescription = accessibilityDescription + return image + } + + internal func menuImage(pointSize: CGFloat = 16) -> Image { + guard assetImage != nil, let image = nsImage(pointSize: pointSize) else { + return Image(systemName: fallbackSystemImage) + } + return Image(nsImage: image) + } + + private static func aspectFit(_ size: NSSize, in rect: NSRect) -> NSRect { + guard size.width > 0, size.height > 0 else { return rect } + let scale = min(rect.width / size.width, rect.height / size.height) + let fitted = NSSize(width: size.width * scale, height: size.height * scale) + return NSRect( + x: rect.midX - fitted.width / 2, + y: rect.midY - fitted.height / 2, + width: fitted.width, + height: fitted.height + ) + } +} + +internal struct BrandIconView: View { + private let assetName: String? + private let isTemplate: Bool + private let fallbackSystemImage: String + + internal init(slug: String, fallbackSystemImage: String) { + self.init(icon: BrandIcon(slug: slug, fallbackSystemImage: fallbackSystemImage)) + } + + internal init(icon: BrandIcon) { + if let asset = icon.assetImage { + assetName = icon.assetName + isTemplate = asset.isTemplate + } else { + assetName = nil + isTemplate = false + } + fallbackSystemImage = icon.fallbackSystemImage + } + + internal var body: some View { + Group { + if let assetName { + Image(decorative: assetName) + .renderingMode(isTemplate ? .template : .original) + .resizable() + .scaledToFit() + } else { + Image(systemName: fallbackSystemImage) + } + } + .accessibilityHidden(true) + } +} diff --git a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift index ae059a6d62..427480ed39 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift @@ -1,8 +1,3 @@ -// -// IntegrationsActivityLogPane.swift -// TablePro -// - import AppKit import SwiftUI import UniformTypeIdentifiers @@ -11,8 +6,10 @@ struct IntegrationsActivityLogPane: View { @ObservedObject private var mcpServerManager = MCPServerManager.shared @State private var entries: [AuditEntry] = [] @State private var tokens: [MCPAuthToken] = [] + @State private var clientNames: [String] = [] @State private var connections: [DatabaseConnection] = [] - @State private var selectedTokenId: UUID? + @State private var selectedToken: ActivityTokenFilter? + @State private var selectedClient: String? @State private var selectedCategory: AuditCategory? @State private var selectedRange: ActivityTimeRange = .last7Days @State private var searchText: String = "" @@ -45,7 +42,8 @@ struct IntegrationsActivityLogPane: View { .onReceive(AppEvents.shared.mcpAuditLogChanged) { _ in Task { await reload() } } - .onChange(of: selectedTokenId) { _ in Task { await reload() } } + .onChange(of: selectedToken) { _ in Task { await reload() } } + .onChange(of: selectedClient) { _ in Task { await reload() } } .onChange(of: selectedCategory) { _ in Task { await reload() } } .onChange(of: selectedRange) { _ in Task { await reload() } } .onChange(of: sortOrder) { newValue in @@ -108,16 +106,26 @@ struct IntegrationsActivityLogPane: View { Text(category.displayName).tag(Optional(category)) } } - Picker(String(localized: "Token"), selection: $selectedTokenId) { - Text(String(localized: "All tokens")).tag(UUID?.none) + Picker(String(localized: "Client"), selection: $selectedClient) { + Text(String(localized: "All clients")).tag(String?.none) + ForEach(clientNames, id: \.self) { name in + Text(verbatim: name).tag(Optional(name)) + } + } + Picker(String(localized: "Token"), selection: $selectedToken) { + Text(String(localized: "All tokens")).tag(ActivityTokenFilter?.none) + ForEach(ActivityTokenFilter.ownCredentialNames, id: \.self) { name in + Text(IntegrationsFormatting.displayTokenName(name)).tag(Optional(ActivityTokenFilter.named(name))) + } ForEach(tokens) { token in - Text(IntegrationsFormatting.displayTokenName(token.name)).tag(Optional(token.id)) + Text(IntegrationsFormatting.displayTokenName(token.name)).tag(Optional(ActivityTokenFilter.token(token.id))) } } if hasActiveFilters { Divider() Button(String(localized: "Clear Filters")) { - selectedTokenId = nil + selectedToken = nil + selectedClient = nil selectedCategory = nil selectedRange = .last7Days } @@ -125,8 +133,7 @@ struct IntegrationsActivityLogPane: View { } label: { Label(String(localized: "Filters"), systemImage: ToolbarSymbols.filter(isActive: hasActiveFilters)) } - /// Named here for the reason `WelcomeViewOptionsMenu` gives: a toolbar-hosted `Menu` - /// publishes "chevron.pulldown" from its label alone. + // A toolbar-hosted Menu otherwise publishes "chevron.pulldown" from its label (see WelcomeViewOptionsMenu). .accessibilityLabel(String(localized: "Filters")) .help(String(localized: "Filter activity")) } @@ -154,8 +161,7 @@ struct IntegrationsActivityLogPane: View { .disabled(isLoading) } - /// `sidebar.trailing` is the glyph AppKit's own inspector toggle draws, and unlike - /// `sidebar.right` it mirrors in a right-to-left layout. + // The glyph AppKit's own inspector toggle draws; unlike sidebar.right it mirrors right to left. private var inspectorToggle: some View { Button { showInspector.toggle() @@ -166,11 +172,12 @@ struct IntegrationsActivityLogPane: View { } private var hasActiveFilters: Bool { - selectedTokenId != nil || selectedCategory != nil || selectedRange != .last7Days + selectedToken != nil || selectedClient != nil || selectedCategory != nil || selectedRange != .last7Days } private var hasNoFilters: Bool { - selectedTokenId == nil + selectedToken == nil + && selectedClient == nil && selectedCategory == nil && selectedRange == .all && searchText.isEmpty @@ -184,16 +191,18 @@ struct IntegrationsActivityLogPane: View { let trimmed = searchText.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return entries } let needle = trimmed.lowercased() - return entries.filter { entry in - if entry.action.lowercased().contains(needle) { return true } - if let tokenName = entry.tokenName?.lowercased(), tokenName.contains(needle) { return true } - if let connectionName = connectionName(for: entry.connectionId)?.lowercased(), - connectionName.contains(needle) { - return true - } - if let details = entry.details?.lowercased(), details.contains(needle) { return true } - return false - } + return entries.filter { Self.searchMatches($0, needle: needle, connectionName: connectionName) } + } + + static func searchMatches(_ entry: AuditEntry, needle: String, connectionName: (UUID?) -> String?) -> Bool { + let fields = [ + entry.action, + entry.clientName, + entry.tokenName.map(IntegrationsFormatting.displayTokenName), + connectionName(entry.connectionId), + entry.details + ] + return fields.contains { $0?.lowercased().contains(needle) == true } } private func connectionName(for id: UUID?) -> String? { @@ -213,13 +222,18 @@ struct IntegrationsActivityLogPane: View { } if let store = mcpServerManager.tokenStore { - tokens = await store.list().filter { !$0.isBridgeCredential } + // TablePro mints these afresh every rotation and every agent turn, so they are filtered by name. + tokens = await store.list().filter { !$0.isBridgeCredential && !$0.isClaudeAgentCredential } } connections = ConnectionStorage.shared.loadConnections() - let result = await MCPAuditLogStorage.shared.query( + let storage = MCPAuditLogStorage.shared + clientNames = await storage.clientNames() + let result = await storage.query( category: selectedCategory, - tokenId: selectedTokenId, + tokenId: selectedToken?.tokenId, + tokenName: selectedToken?.tokenName, + clientName: selectedClient, since: selectedRange.startDate, limit: 1_000 ) @@ -246,7 +260,8 @@ struct IntegrationsActivityLogPane: View { private func writeActivityLog(to url: URL) { do { - try csvString(for: filteredEntries).write(to: url, atomically: true, encoding: .utf8) + try Self.csvString(for: filteredEntries, connectionName: connectionName) + .write(to: url, atomically: true, encoding: .utf8) } catch { AlertHelper.showErrorSheet( title: String(localized: "Could not export activity log"), @@ -256,8 +271,8 @@ struct IntegrationsActivityLogPane: View { } } - private func csvString(for entries: [AuditEntry]) -> String { - let header = ["Timestamp", "Category", "Action", "Connection", "Token", "Outcome", "Details"] + static func csvString(for entries: [AuditEntry], connectionName: (UUID?) -> String?) -> String { + let header = ["Timestamp", "Category", "Action", "Client", "Connection", "Token", "Outcome", "Details"] .joined(separator: ",") let timestampFormatter = ISO8601DateFormatter() let rows = entries.map { entry -> String in @@ -265,12 +280,13 @@ struct IntegrationsActivityLogPane: View { timestampFormatter.string(from: entry.timestamp), entry.category.rawValue, entry.action, - connectionName(for: entry.connectionId) ?? "", + entry.clientName ?? "", + connectionName(entry.connectionId) ?? "", entry.tokenName ?? "", entry.outcome, entry.details ?? "" ] - return cells.map(CsvRowConverter.encode).joined(separator: ",") + return cells.map(CsvRowConverter.encodeForSpreadsheet).joined(separator: ",") } return ([header] + rows).joined(separator: "\n") + "\n" } @@ -311,6 +327,11 @@ private struct ActivityLogTable: View { } .width(min: 160, ideal: 220) + TableColumn(String(localized: "Client")) { entry in + clientCell(for: entry) + } + .width(min: 100, ideal: 140) + TableColumn(String(localized: "Token")) { entry in tokenCell(for: entry) } @@ -351,6 +372,15 @@ private struct ActivityLogTable: View { .font(.system(.body, design: .monospaced)) } + @ViewBuilder + private func clientCell(for entry: AuditEntry) -> some View { + if let name = entry.clientName { + Text(verbatim: name) + } else { + Text(verbatim: "-").foregroundStyle(.tertiary) + } + } + @ViewBuilder private func tokenCell(for entry: AuditEntry) -> some View { if let name = entry.tokenName { @@ -394,6 +424,7 @@ private struct ActivityLogTable: View { String(format: String(localized: "Category: %@"), entry.category.displayName), String(format: String(localized: "Action: %@"), entry.action), String(format: String(localized: "Outcome: %@"), outcome), + entry.clientName.map { String(format: String(localized: "Client: %@"), $0) }, tokenLine, connectionLabel(entry.connectionId).map { String(format: String(localized: "Connection: %@"), $0) }, entry.details.map { String(format: String(localized: "Details: %@"), $0) } @@ -438,6 +469,11 @@ private struct ActivityLogInspector: View { } Section(String(localized: "Source")) { + LabeledContent(String(localized: "Client")) { + Text(entry.clientName ?? String(localized: "None")) + .foregroundStyle(entry.clientName == nil ? .tertiary : .primary) + .textSelection(.enabled) + } LabeledContent(String(localized: "Token")) { let tokenText = entry.tokenName.map(IntegrationsFormatting.displayTokenName) ?? String(localized: "None") Text(tokenText) @@ -484,6 +520,24 @@ private struct ActivityLogInspector: View { } } +enum ActivityTokenFilter: Hashable { + case token(UUID) + // TablePro's own credentials, minted afresh each bridge rotation and each Claude Agent turn. + case named(String) + + static let ownCredentialNames = [MCPTokenStore.stdioBridgeTokenName, MCPTokenStore.claudeAgentTokenName] + + var tokenId: UUID? { + if case .token(let id) = self { return id } + return nil + } + + var tokenName: String? { + if case .named(let name) = self { return name } + return nil + } +} + enum ActivityTimeRange: String, CaseIterable, Identifiable { case last24Hours case last7Days @@ -512,9 +566,7 @@ enum ActivityTimeRange: String, CaseIterable, Identifiable { } } -/// `.inspector` and `.inspectorColumnWidth` are macOS 14. Before them the pane is shown beside -/// the log in an `HSplitView`, which is the same arrangement without the system's show/hide -/// animation and its width persistence. +// .inspector is macOS 14; before it the pane sits beside the log in an HSplitView. private struct ActivityLogInspectorPane: ViewModifier { @Binding var isPresented: Bool let entry: AuditEntry? diff --git a/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift b/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift index 27f00bd25f..a7a248cd1b 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift @@ -1,36 +1,32 @@ -// -// IntegrationsConnectedClientsPane.swift -// TablePro -// - import SwiftUI +import TableProMCPClients struct IntegrationsConnectedClientsPane: View { @ObservedObject private var manager = MCPServerManager.shared @State private var selection: MCPServerManager.SessionSnapshot.ID? @State private var disconnectCandidate: MCPServerManager.SessionSnapshot? @State private var revocationNotSaved = false - @State private var sortOrder: [KeyPathComparator] = [ - KeyPathComparator(\MCPServerManager.SessionSnapshot.connectedSince, order: .reverse) + @State private var showSetupSheet = false + @State private var detectedClientIDs: Set = [] + @State private var sortOrder: [KeyPathComparator] = [ + KeyPathComparator(\ConnectedClientRow.connectedSince, order: .reverse) ] var body: some View { Group { if manager.connectedClients.isEmpty { - UnavailableStateView( - String(localized: "No clients connected"), - systemImage: "person.2.slash", - description: Text(String(localized: "Clients will appear here while they have an active MCP session.")) - ) + emptyState } else { ConnectedClientsTable( - clients: sortedClients, + rows: sortedRows, selection: $selection, sortOrder: $sortOrder, onDisconnect: { client in disconnectCandidate = client } ) + .onDeleteCommand(perform: disconnectSelection) } } + .task(id: ambiguousClientIDs) { await detectAmbiguousClients() } .navigationTitle(IntegrationsActivitySection.connectedClients.title) .navigationSubtitle(subtitle) .task { await manager.refreshClientsWhileShown() } @@ -47,20 +43,101 @@ struct IntegrationsConnectedClientsPane: View { } message: { Text(String(localized: "TablePro could not save the change to the Keychain. The token works again after TablePro restarts.")) } + .sheet(isPresented: $showSetupSheet) { + MCPClientSetupSheet() + } + } + + private var emptyState: some View { + UnavailableStateView { + Label(emptyStateTitle, systemImage: emptyStateSymbol) + } description: { + Text(emptyStateDescription) + } actions: { + Button(String(localized: "Connect a Client…")) { + showSetupSheet = true + } + .accessibilityIdentifier("connected-clients-connect") + } + } + + private var emptyStateTitle: String { + switch manager.state { + case .running: String(localized: "No clients connected") + case .starting: String(localized: "MCP Server Starting") + case .stopped: String(localized: "MCP Server Off") + case .failed: String(localized: "MCP Server Couldn't Start") + } + } + + private var emptyStateSymbol: String { + switch manager.state { + case .running: "person.2.slash" + case .starting: "hourglass" + case .stopped: "power" + case .failed: "exclamationmark.triangle" + } + } + + private var emptyStateDescription: String { + switch manager.state { + case .running: + String(localized: "Clients will appear here while they have an active MCP session.") + case .starting: + String(localized: "Clients can connect once the MCP server is running.") + case .stopped: + String(localized: "Clients can connect while the MCP server is on. Turn it on in Settings > MCP.") + case .failed: + String(localized: "Clients cannot connect until it runs. Open Settings > MCP to see why and try again.") + } + } + + private func disconnectSelection() { + guard let id = selection, let client = manager.connectedClients.first(where: { $0.id == id }) else { return } + disconnectCandidate = client + } + + private var sortedRows: [ConnectedClientRow] { + manager.connectedClients.map { session in + ConnectedClientRow( + session: session, + name: session.clientDisplayName(detected: detectedClientIDs), + iconSlug: session.catalogIconSlug(detected: detectedClientIDs) + ) + } + .sorted(using: sortOrder) } - private var sortedClients: [MCPServerManager.SessionSnapshot] { - manager.connectedClients.sorted(using: sortOrder) + private var ambiguousClientIDs: Set { + let sessions = manager.connectedClients.map { (clientInfoName: $0.sessionInfoName, tokenName: $0.tokenName) } + return MCPClientCatalogBundle.shared?.ambiguousClientIDs(forSessionsNamed: sessions) ?? [] + } + + private func detectAmbiguousClients() async { + let ids = ambiguousClientIDs + guard !ids.isEmpty, let catalog = MCPClientCatalogBundle.shared else { return } + detectedClientIDs = await Self.detect(ids, scanner: MCPClientScanner(catalog: catalog, context: .live())) + } + + @concurrent + nonisolated private static func detect(_ ids: Set, scanner: MCPClientScanner) async -> Set { + scanner.detectedIDs(among: ids) } @ToolbarContentBuilder private func toolbar() -> some ToolbarContent { + ToolbarItem { + Button { + showSetupSheet = true + } label: { + Label(String(localized: "Connect a Client…"), systemImage: "plus") + } + .help(String(localized: "Set up an app to use TablePro's MCP server")) + .accessibilityIdentifier("connected-clients-toolbar-connect") + } ToolbarItem { Button(role: .destructive) { - if let id = selection, - let client = manager.connectedClients.first(where: { $0.id == id }) { - disconnectCandidate = client - } + disconnectSelection() } label: { Label(String(localized: "Disconnect"), systemImage: ToolbarSymbols.disconnect()) } @@ -85,7 +162,19 @@ struct IntegrationsConnectedClientsPane: View { } private func alertMessage(client: MCPServerManager.SessionSnapshot) -> some View { - Text(String(format: String(localized: "“%@” will be disconnected and any in-flight requests will be cancelled."), client.clientName)) + switch client.transport { + case .http: + Text(String( + format: String(localized: "“%@” will be disconnected and its token revoked. Any in-flight requests will be cancelled."), + client.clientDisplayName(detected: detectedClientIDs) + )) + case .stdioBridge: + Text(String( + // swiftlint:disable:next line_length + format: String(localized: "“%@”'s running requests will be cancelled, but it can send new ones right away. To stop it, remove TablePro from it in Connect a Client, or turn off the MCP server."), + client.clientDisplayName(detected: detectedClientIDs) + )) + } } private var subtitle: String { @@ -105,60 +194,70 @@ struct IntegrationsConnectedClientsPane: View { } } +private struct ConnectedClientRow: Identifiable { + let session: MCPServerManager.SessionSnapshot + let name: String + let iconSlug: String? + + var id: MCPServerManager.SessionSnapshot.ID { session.id } + var connectedSince: Date { session.connectedSince } + var lastActivityAt: Date { session.lastActivityAt } +} + private struct ConnectedClientsTable: View { - let clients: [MCPServerManager.SessionSnapshot] + let rows: [ConnectedClientRow] @Binding var selection: MCPServerManager.SessionSnapshot.ID? - @Binding var sortOrder: [KeyPathComparator] + @Binding var sortOrder: [KeyPathComparator] let onDisconnect: (MCPServerManager.SessionSnapshot) -> Void var body: some View { - Table(of: MCPServerManager.SessionSnapshot.self, + Table(of: ConnectedClientRow.self, selection: $selection, sortOrder: $sortOrder) { - TableColumn(String(localized: "Client"), value: \.clientName) { client in - clientCell(for: client) + TableColumn(String(localized: "Client"), value: \.name) { row in + clientCell(for: row) } .width(min: 160, ideal: 200) - TableColumn(String(localized: "Version")) { client in - versionCell(for: client) + TableColumn(String(localized: "Version")) { row in + versionCell(for: row.session) } .width(min: 70, ideal: 90) - TableColumn(String(localized: "Token")) { client in - tokenCell(for: client) + TableColumn(String(localized: "Token")) { row in + tokenCell(for: row.session) } .width(min: 110, ideal: 140) - TableColumn(String(localized: "Address")) { client in - addressCell(for: client) + TableColumn(String(localized: "Address")) { row in + addressCell(for: row.session) } .width(min: 120, ideal: 160) - TableColumn(String(localized: "Connected"), value: \.connectedSince) { client in - connectedCell(for: client) + TableColumn(String(localized: "Connected"), value: \.connectedSince) { row in + connectedCell(for: row.session) } .width(min: 110, ideal: 130) - TableColumn(String(localized: "Last Activity"), value: \.lastActivityAt) { client in - lastActivityCell(for: client) + TableColumn(String(localized: "Last Activity"), value: \.lastActivityAt) { row in + lastActivityCell(for: row.session) } .width(min: 110, ideal: 130) } rows: { - ForEach(clients) { client in - SwiftUI.TableRow(client) - .contextMenu { contextMenu(for: client) } + ForEach(rows) { row in + SwiftUI.TableRow(row) + .contextMenu { contextMenu(for: row.session) } } } } @ViewBuilder - private func clientCell(for client: MCPServerManager.SessionSnapshot) -> some View { + private func clientCell(for row: ConnectedClientRow) -> some View { Label { - Text(client.clientName) + Text(verbatim: row.name) } icon: { - Image(systemName: "checkmark.circle.fill") - .foregroundStyle(.green) + BrandIconView(icon: BrandIcon(slug: row.iconSlug, fallbackSystemImage: "app")) + .frame(width: 16, height: 16) } } @@ -216,3 +315,19 @@ private struct ConnectedClientsTable: View { } } } + +extension MCPServerManager.SessionSnapshot { + fileprivate var sessionInfoName: String { + clientInfoName ?? clientName + } + + // A session two catalog rows share keeps its own clientInfo title unless one of them alone is on this Mac. + func clientDisplayName(detected: Set) -> String { + MCPClientCatalogBundle.shared?.client(forSessionNamed: sessionInfoName, tokenName: tokenName, detected: detected)?.name + ?? IntegrationsFormatting.displayClientName(self) + } + + func catalogIconSlug(detected: Set) -> String? { + MCPClientCatalogBundle.shared?.iconSlug(forSessionNamed: sessionInfoName, tokenName: tokenName, detected: detected) + } +} diff --git a/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift b/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift index aa7b9f4354..f64f64a94d 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift @@ -1,16 +1,26 @@ -// -// IntegrationsFormatting.swift -// TablePro -// - import AppKit import SwiftUI +import TableProMCP enum IntegrationsFormatting { + // MCPTokenStore keeps both reserved names for TablePro's own tokens, at mint and at load, so a paired + // client cannot borrow these labels. static func displayTokenName(_ name: String) -> String { - name == MCPTokenStore.stdioBridgeTokenName - ? String(localized: "Built-in CLI") - : name + switch name { + case MCPTokenStore.stdioBridgeTokenName: + String(localized: "Built-in CLI") + case MCPTokenStore.claudeAgentTokenName: + AIProviderType.claudeAgent.displayName + default: + name + } + } + + // The tablepro command names itself "Command Line"; the window calls it what Settings calls it. + static func displayClientName(_ client: MCPServerManager.SessionSnapshot) -> String { + client.clientInfoName == CLIClientIdentity.name + ? String(localized: "tablepro command") + : client.clientName } static func outcomeSymbol(_ outcome: AuditOutcome?) -> String { diff --git a/apple/TablePro/Views/Integrations/IntegrationsSetupSheet.swift b/apple/TablePro/Views/Integrations/IntegrationsSetupSheet.swift deleted file mode 100644 index b38124dbb3..0000000000 --- a/apple/TablePro/Views/Integrations/IntegrationsSetupSheet.swift +++ /dev/null @@ -1,151 +0,0 @@ -// -// IntegrationsSetupSheet.swift -// TablePro -// - -import AppKit -import SwiftUI - -struct IntegrationsSetupSheet: View { - let port: Int - - @Environment(\.dismiss) private var dismiss - @State private var selectedClient: IntegrationClient = .claudeDesktop - - var body: some View { - VStack(alignment: .leading, spacing: 0) { - header - - Divider() - - ScrollView { - VStack(alignment: .leading, spacing: 16) { - Picker(String(localized: "Client"), selection: $selectedClient) { - ForEach(IntegrationClient.allCases) { client in - Text(client.displayName).tag(client) - } - } - .pickerStyle(.segmented) - - IntegrationsSetupInstructions(client: selectedClient, port: port) - } - .padding(20) - } - - Divider() - - HStack { - Spacer() - Button(String(localized: "Done")) { - dismiss() - } - .keyboardShortcut(.defaultAction) - } - .padding(16) - } - .frame(width: 580, height: 480) - } - - private var header: some View { - VStack(alignment: .leading, spacing: 4) { - Text(String(localized: "Connect a Client")) - .font(.title2.weight(.semibold)) - Text(String(localized: "Choose your client and follow the steps to connect it to TablePro.")) - .font(.callout) - .foregroundStyle(.secondary) - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(20) - } -} - -private struct IntegrationsSetupInstructions: View { - let client: IntegrationClient - let port: Int - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - ForEach(Array(steps.enumerated()), id: \.offset) { index, step in - HStack(alignment: .firstTextBaseline, spacing: 8) { - Text("\(index + 1).") - .foregroundStyle(.secondary) - .monospacedDigit() - .frame(width: 20, alignment: .trailing) - Text(step) - .textSelection(.enabled) - } - } - - if let snippet = configSnippet { - CopyableCodeBlock(text: snippet) - } - if let command { - CopyableCodeBlock(text: command) - } - } - .font(.callout) - } - - private var bridgeBinaryPath: String { - Bundle.main.bundleURL.appendingPathComponent("Contents/MacOS/tablepro-mcp").path - } - - private var steps: [String] { - switch client { - case .claudeDesktop: - [ - String(localized: "Open Claude Desktop, go to Settings > Developer"), - String(localized: "Click \"Edit Config\" to open claude_desktop_config.json"), - String(localized: "Add the JSON below inside the file and save"), - String(localized: "Restart Claude Desktop") - ] - case .claudeCode: - [String(localized: "Run the command below in your terminal")] - case .cursor: - [ - String(localized: "Open Cursor, go to Settings > MCP"), - String(localized: "Click \"+ Add new global MCP server\""), - String(localized: "Paste the JSON below and save") - ] - case .zed: - [ - String(localized: "Open Zed and click the Agent Panel icon in the right side of the title bar"), - String(localized: "Click the menu in the Agent Panel header and choose Settings"), - String(localized: "Under MCP Servers click \"+ Add Custom Server\", select the Local tab, paste the JSON below, then click Add Server") - ] - } - } - - private var configSnippet: String? { - switch client { - case .claudeDesktop, .cursor: - return """ - { - "mcpServers": { - "tablepro": { - "command": "\(bridgeBinaryPath)" - } - } - } - """ - case .zed: - return """ - { - "tablepro": { - "command": "\(bridgeBinaryPath)", - "args": [] - } - } - """ - case .claudeCode: - return nil - } - } - - private var command: String? { - switch client { - case .claudeCode: "claude mcp add tablepro -- \(bridgeBinaryPath)" - default: nil - } - } -} diff --git a/apple/TablePro/Views/Integrations/MCPClientSetupSheet.swift b/apple/TablePro/Views/Integrations/MCPClientSetupSheet.swift new file mode 100644 index 0000000000..ea782d00d9 --- /dev/null +++ b/apple/TablePro/Views/Integrations/MCPClientSetupSheet.swift @@ -0,0 +1,349 @@ +import AppKit +import SwiftUI + +struct MCPClientSetupSheet: View { + @Environment(\.dismiss) private var dismiss + @StateObject private var service = MCPClientSetupService() + @ObservedObject private var manager = MCPServerManager.shared + @State private var selection: String? + @State private var removeCandidate: MCPClientRow? + + var body: some View { + VStack(spacing: 0) { + header + Divider() + content + Divider() + footer + } + .frame(width: 680, height: sheetHeight) + .onExitCommand { dismiss() } + .task { await service.refresh() } + // The sheet says " connected" from the client list, which updates only while a view polls it. + .task { await manager.refreshClientsWhileShown() } + .confirmationDialog( + removeTitle, + isPresented: removeBinding, + titleVisibility: .visible, + presenting: removeCandidate + ) { row in + Button(String(localized: "Remove"), role: .destructive) { + selection = row.id + Task { await service.remove(row.id) } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { row in + Text(verbatim: removeMessage(for: row)) + } + } + + private var header: some View { + VStack(alignment: .leading, spacing: 8) { + Text(String(localized: "Connect a Client")) + .font(.title2.weight(.semibold)) + Text(String(localized: "Install adds TablePro to a client on this Mac. Select a client to see its settings and set it up by hand.")) + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + if service.isAppOnReadOnlyVolume { + NoticeLabel(String(localized: "TablePro is running from a disk image or a temporary location. Move it to the Applications folder first, then open it from there.")) + .font(.callout) + } + if isServerDown { + NoticeLabel(String(localized: "The MCP server is not running, so clients you add cannot connect yet. Turn it on in Settings > MCP.")) + .font(.callout) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(20) + } + + @ViewBuilder + private var content: some View { + if !service.isCatalogAvailable { + UnavailableStateView( + String(localized: "Client List Unavailable"), + systemImage: "exclamationmark.triangle", + description: Text(String(localized: "TablePro could not read its list of clients. Reinstall TablePro to restore it.")) + ) + } else if !service.hasLoaded { + ProgressView() + .controlSize(.small) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + clientList + .frame(maxHeight: .infinity) + Divider() + detail + .frame(height: sheetHeight >= 700 ? 260 : 190) + } + } + + private var clientList: some View { + List(selection: $selection) { + if !foundRows.isEmpty { + Section(String(localized: "On This Mac")) { + ForEach(foundRows) { row in + clientRow(row) + } + } + } + if !otherRows.isEmpty { + Section(String(localized: "Other Clients")) { + ForEach(otherRows) { row in + clientRow(row) + } + } + } + } + .listStyle(.inset(alternatesRowBackgrounds: false)) + .onDeleteCommand { + if let row = selectedRow, row.removeRoute != nil { + removeCandidate = row + } + } + } + + private func clientRow(_ row: MCPClientRow) -> some View { + MCPClientSetupRowView( + row: row, + presentation: service.presentation(for: row), + actionsDisabled: service.isAppOnReadOnlyVolume, + onAction: { action in perform(action, on: row) } + ) + .tag(row.id) + .contextMenu { contextMenu(for: row) } + } + + @ViewBuilder + private func contextMenu(for row: MCPClientRow) -> some View { + if let action = service.presentation(for: row).action, action != .copy { + Button(action.title) { perform(action, on: row) } + .disabled(service.isAppOnReadOnlyVolume) + } + if let snippet = row.snippet { + Button(String(localized: "Copy Configuration")) { copy(snippet) } + } + if let commandLine = row.commandLine { + Button(String(localized: "Copy Command")) { copy(commandLine) } + } + if row.configPath != nil { + Button(String(localized: "Show in Finder")) { reveal(row) } + .disabled(!canReveal(row)) + } + if row.removeRoute != nil { + Divider() + Button(String(localized: "Remove…"), role: .destructive) { removeCandidate = row } + } + } + + @ViewBuilder + private var detail: some View { + if let row = selectedRow { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + detailContent(for: row) + } + .padding(16) + .frame(maxWidth: .infinity, alignment: .leading) + } + } else { + Text(String(localized: "Select a client to see how TablePro connects to it.")) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + + @ViewBuilder + private func detailContent(for row: MCPClientRow) -> some View { + Text(verbatim: row.name) + .font(.headline) + if let unsupported = row.unsupported { + Text(verbatim: MCPClientDetailText.unsupported(unsupported, name: row.name)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } else { + if case let .failed(_, message, output)? = service.activities[row.id] { + NoticeLabel(message, severity: .error) + if let output { + CopyableCodeBlock(text: output) + } + } + if let note = MCPClientDetailText.configState(row.config, name: row.name) { + Text(verbatim: note) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + if let applies = row.applies { + Text(verbatim: MCPClientDetailText.applies(applies, name: row.name)) + .foregroundStyle(.secondary) + } + if let path = row.displayConfigPath { + LabeledContent(String(localized: "Settings file")) { + HStack(spacing: 8) { + Text(verbatim: path) + .font(.system(.callout, design: .monospaced)) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + Button(String(localized: "Show in Finder")) { reveal(row) } + .controlSize(.small) + .disabled(!canReveal(row)) + } + } + } + if let commandLine = row.commandLine { + Text(String(localized: "Command")) + .font(.subheadline.weight(.semibold)) + CopyableCodeBlock(text: commandLine) + } + if let snippet = row.snippet, row.isConfigWritable || row.commandLine == nil { + Text(String(localized: "Configuration")) + .font(.subheadline.weight(.semibold)) + CopyableCodeBlock(text: snippet) + } + if row.removeRoute != nil { + Button(String(localized: "Remove…"), role: .destructive) { removeCandidate = row } + .accessibilityIdentifier("mcp-client-remove") + } + } + } + + private var footer: some View { + HStack { + Spacer() + Button(String(localized: "Done")) { dismiss() } + .keyboardShortcut(.defaultAction) + .accessibilityIdentifier("mcp-client-setup-done") + } + .padding(16) + } + + // A SwiftUI sheet on macOS opens at its minimum size, so the size is fixed here and kept inside a short screen. + private var sheetHeight: CGFloat { + let available = (NSApp.keyWindow?.screen ?? NSScreen.main)?.visibleFrame.height ?? 760 + return min(760, max(480, available - 80)) + } + + private var foundRows: [MCPClientRow] { + service.rows.filter { $0.isInstalled } + } + + private var otherRows: [MCPClientRow] { + service.rows.filter { !$0.isInstalled } + } + + private var selectedRow: MCPClientRow? { + selection.flatMap { service.row(id: $0) } + } + + private var isServerDown: Bool { + switch manager.state { + case .stopped, .failed: true + case .starting, .running: false + } + } + + private func perform(_ action: MCPClientRowAction, on row: MCPClientRow) { + selection = row.id + switch action { + case .install: + Task { await service.install(row.id) } + case .update: + Task { await service.update(row.id) } + case .copy: + if let text = row.copyText { + copy(text) + } + } + } + + private func copy(_ text: String) { + ClipboardService.shared.writeText(text) + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) + } + + private func canReveal(_ row: MCPClientRow) -> Bool { + guard let path = row.configPath else { return false } + return row.configFileExists + || FileManager.default.fileExists(atPath: (path as NSString).deletingLastPathComponent) + } + + private func reveal(_ row: MCPClientRow) { + guard let path = row.configPath else { return } + if FileManager.default.fileExists(atPath: path) { + NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) + } else { + NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: (path as NSString).deletingLastPathComponent) + } + } + + private var removeTitle: String { + guard let row = removeCandidate else { return "" } + return String(format: String(localized: "Remove TablePro from %@?"), row.name) + } + + private func removeMessage(for row: MCPClientRow) -> String { + if row.removeRoute == .file, let file = row.configFileName { + return String( + format: String(localized: "%1$@ stops reaching your databases through TablePro. The current %2$@ is kept next to it as %3$@."), + row.name, + file, + file + ".tablepro-backup" + ) + } + return String(format: String(localized: "%@ stops reaching your databases through TablePro."), row.name) + } + + private var removeBinding: Binding { + Binding( + get: { removeCandidate != nil }, + set: { isPresented in + if !isPresented { + removeCandidate = nil + } + } + ) + } +} + +private struct MCPClientSetupRowView: View { + let row: MCPClientRow + let presentation: MCPClientRowPresentation + let actionsDisabled: Bool + let onAction: (MCPClientRowAction) -> Void + + var body: some View { + HStack(spacing: 10) { + BrandIconView(slug: row.iconSlug, fallbackSystemImage: "app") + .frame(width: 18, height: 18) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: presentation.title) + Text(verbatim: presentation.subtitle) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + Spacer(minLength: 8) + if let status = presentation.status { + Text(verbatim: status) + .font(.callout) + .foregroundStyle(.secondary) + .lineLimit(1) + } + if presentation.isBusy { + ProgressView() + .controlSize(.small) + } else if let action = presentation.action { + Button(action.title) { onAction(action) } + .buttonStyle(.bordered) + .controlSize(.small) + .disabled(actionsDisabled && action != .copy) + .accessibilityLabel(action.accessibilityLabel(clientName: row.name)) + .accessibilityIdentifier("mcp-client-action-\(row.id)") + } + } + .padding(.vertical, 3) + } +} diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index 0b707876c7..94f6291fba 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -2,9 +2,6 @@ // AISettingsView.swift // TablePro // -// Single settings tab for AI: providers, active provider, inline suggestions, -// context, and privacy. Modeled after Xcode 26 Intelligence settings. -// import Combine import SwiftUI @@ -102,7 +99,13 @@ struct AISettingsView: View { Picker("Active Provider", selection: $settings.activeProviderID) { Text("None").tag(UUID?.none) ForEach(settings.providers) { provider in - Text(provider.displayName).tag(UUID?.some(provider.id)) + Label { + Text(provider.displayName) + } icon: { + provider.icon.menuImage() + } + .labelStyle(.titleAndIcon) + .tag(UUID?.some(provider.id)) } } .pickerStyle(.menu) @@ -169,8 +172,9 @@ struct AISettingsView: View { } .frame(width: 14) - Image(systemName: provider.symbolName) + BrandIconView(icon: provider.icon) .foregroundStyle(.secondary) + .frame(width: 16, height: 16) .frame(width: 20) VStack(alignment: .leading, spacing: 2) { @@ -201,21 +205,32 @@ struct AISettingsView: View { Button { addingProvider = makeNewProvider(type: type) } label: { - Label(type.displayName, systemImage: type.symbolName) + Label { + Text(type.displayName) + } icon: { + type.icon.menuImage() + } + .labelStyle(.titleAndIcon) } } ForEach(AIProviderPreset.all) { preset in Button { addingProvider = AIProviderConfig(preset: preset) } label: { - Label(preset.displayName, systemImage: preset.symbolName) + Label { + Text(preset.displayName) + } icon: { + preset.icon.menuImage() + } + .labelStyle(.titleAndIcon) } } Divider() Button { addingProvider = makeNewProvider(type: .custom) } label: { - Label(String(localized: "Add Custom Provider…"), systemImage: AIProviderType.custom.symbolName) + Label(String(localized: "Add Custom Provider…"), systemImage: AIProviderType.custom.icon.fallbackSystemImage) + .labelStyle(.titleAndIcon) } } label: { Label(String(localized: "Add Provider…"), systemImage: "plus") diff --git a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift index 414b86118f..9f9ffb0948 100644 --- a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift +++ b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift @@ -2,11 +2,12 @@ import SwiftUI struct CopyableCodeBlock: View { let text: String + var displayText: String? var isSecret = false var body: some View { HStack(alignment: .top) { - Text(text) + Text(verbatim: displayText ?? text) .font(.system(.caption, design: .monospaced)) .textSelection(.enabled) .padding(8) diff --git a/apple/TablePro/Views/Settings/Components/IntegrationClient.swift b/apple/TablePro/Views/Settings/Components/IntegrationClient.swift deleted file mode 100644 index c8b9949adc..0000000000 --- a/apple/TablePro/Views/Settings/Components/IntegrationClient.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation - -enum IntegrationClient: String, CaseIterable, Identifiable, Sendable { - case claudeCode - case claudeDesktop - case cursor - case zed - - var id: String { rawValue } - - var displayName: String { - switch self { - case .claudeCode: return "Claude Code" - case .claudeDesktop: return "Claude Desktop" - case .cursor: return "Cursor" - case .zed: return "Zed" - } - } -} diff --git a/apple/TablePro/Views/Settings/Sections/MCPSection.swift b/apple/TablePro/Views/Settings/Sections/MCPSection.swift index 66a2b46c14..96d67c7902 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPSection.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPSection.swift @@ -9,9 +9,9 @@ struct MCPSection: View { @State private var showSetupSheet = false @State private var showCreateSheet = false @State private var showRevealSheet = false - @State private var revealedToken: MCPAuthToken? @State private var revealedPlaintext: String = "" - @State private var revocationNotSaved = false + @State private var tokenAlert: MCPTokenAlert? + @State private var rejectedPort: Int? var body: some View { Section { @@ -67,11 +67,12 @@ struct MCPSection: View { } private var configurationSection: some View { - Section(String(localized: "Server Configuration")) { + Section { LabeledContent(String(localized: "Port")) { - TextField("", value: $settings.port, format: .number.grouping(.never)) + TextField("", value: portBinding, format: .number.grouping(.never)) .frame(width: 80) .multilineTextAlignment(.trailing) + .accessibilityIdentifier("mcp-port-field") } LabeledContent(String(localized: "Default row limit")) { @@ -97,64 +98,113 @@ struct MCPSection: View { } Toggle(String(localized: "Log MCP queries in history"), isOn: $settings.logQueriesInHistory) + } header: { + Text(String(localized: "Server Configuration")) + } footer: { + if let rejectedPort { + NoticeLabel( + String( + format: String(localized: "Port %d cannot be used. Choose a port from %d to %d."), + rejectedPort, + MCPSettings.portRange.lowerBound, + MCPSettings.portRange.upperBound + ), + severity: .error + ) + .font(.caption) + } } } + // An out-of-range port is kept out of the settings, so the server never binds a port the field did not show. + private var portBinding: Binding { + Binding( + get: { settings.port }, + set: { newValue in + if MCPSettings.portRange.contains(newValue) { + rejectedPort = nil + settings.port = newValue + } else { + rejectedPort = newValue + } + } + ) + } + private var authenticationSection: some View { Section(String(localized: "Authentication")) { MCPTokenListView( tokens: tokenList, + isStoreAvailable: manager.tokenStore != nil, onGenerate: { showCreateSheet = true }, - onRevoke: { id in - Task { - if !(await manager.revokeToken(id: id)) { - revocationNotSaved = true - } - await refreshTokens() - } - }, - onDelete: { id in Task { await manager.tokenStore?.delete(tokenId: id); await refreshTokens() } } + onRevoke: { id in revoke(id) }, + onDelete: { ids in delete(ids) } ) } - .task { await refreshTokens() } + .task(id: manager.tokenStore.map { ObjectIdentifier($0) }) { await refreshTokens() } .sheet(isPresented: $showCreateSheet) { - MCPTokenCreateSheet(onGenerate: handleGenerate) + MCPTokenCreateSheet { name, permissions, connectionIds, expiresAt in + await generate(name: name, permissions: permissions, connectionIds: connectionIds, expiresAt: expiresAt) + } } .sheet(isPresented: $showRevealSheet) { - if let revealedToken { + if !revealedPlaintext.isEmpty { MCPTokenRevealSheet( - token: revealedToken, plaintext: revealedPlaintext, - port: manager.listeningPort ?? settings.port + port: manager.listeningPort ?? settings.port, + configuredPort: settings.port ) } } - .alert(String(localized: "Couldn't Save the Revocation"), isPresented: $revocationNotSaved) { + .alert(tokenAlert?.title ?? "", isPresented: tokenAlertBinding, presenting: tokenAlert) { _ in Button(String(localized: "OK")) {} - } message: { - Text(String(localized: "TablePro could not save the change to the Keychain. The token works again after TablePro restarts.")) + } message: { alert in + Text(verbatim: alert.message) } } + private var tokenAlertBinding: Binding { + Binding( + get: { tokenAlert != nil }, + set: { isPresented in + if !isPresented { + tokenAlert = nil + } + } + ) + } + private var helpSection: some View { Section { Button(String(localized: "Connect a Client…")) { showSetupSheet = true } + .accessibilityIdentifier("mcp-connect-client") Button(String(localized: "View Activity…")) { WindowOpener.shared.openIntegrationsActivity() } + .accessibilityIdentifier("mcp-view-activity") } .sheet(isPresented: $showSetupSheet) { - IntegrationsSetupSheet(port: manager.listeningPort ?? settings.port) + MCPClientSetupSheet() } } - private func handleGenerate(name: String, permissions: TokenPermissions, connectionIds: Set?, expiresAt: Date?) { - Task { - guard let store = manager.tokenStore else { return } - let access: ConnectionAccess = connectionIds.map { .limited($0) } ?? .all - guard let result = try? await store.generate( + private func generate( + name: String, + permissions: TokenPermissions, + connectionIds: Set?, + expiresAt: Date? + ) async -> MCPTokenCreateFailure? { + guard let store = manager.tokenStore else { + return MCPTokenCreateFailure( + message: String(localized: "The MCP server is not running, so TablePro cannot save a token now. Start the server, then try again."), + endsSheet: true + ) + } + let access: ConnectionAccess = connectionIds.map { .limited($0) } ?? .all + do { + let result = try await store.generate( name: name, permissions: permissions, connectionAccess: access, @@ -162,21 +212,88 @@ struct MCPSection: View { isBridgeCredential: false, isClaudeAgentCredential: false, extraScopes: [] - ) else { return } - revealedToken = result.token + ) revealedPlaintext = result.plaintext showCreateSheet = false showRevealSheet = true await refreshTokens() + return nil + } catch { + return MCPTokenCreateFailure(message: Self.generateFailureMessage(error), endsSheet: false) + } + } + + private static func generateFailureMessage(_ error: Error) -> String { + switch error as? MCPTokenStoreError { + case .storedTokensUnreadable?: + String(localized: "TablePro could not read the tokens saved in the Keychain, so it will not save a new one over them. Restart TablePro and try again.") + case .randomGenerationFailed?: + String(localized: "macOS could not generate a secure token. Try again.") + case .keychainUnavailable?, .notSaved?, nil: + String(localized: "TablePro could not save the token to the Keychain, so it was not created. Try again.") + } + } + + private func revoke(_ id: UUID) { + Task { + guard manager.tokenStore != nil else { + tokenAlert = .serverNotRunning + return + } + if !(await manager.revokeToken(id: id)) { + tokenAlert = .revocationNotSaved + } + await refreshTokens() + } + } + + private func delete(_ ids: Set) { + Task { + guard let store = manager.tokenStore else { + tokenAlert = .serverNotRunning + return + } + var allSaved = true + for id in ids { + let saved = await store.delete(tokenId: id) + allSaved = allSaved && saved + } + if !allSaved { + tokenAlert = .deletionNotSaved + } + await refreshTokens() } } private func refreshTokens() async { - guard let store = MCPServerManager.shared.tokenStore else { return } + guard let store = manager.tokenStore else { return } tokenList = await store.list().filter { !$0.isBridgeCredential } } } +private enum MCPTokenAlert: Equatable { + case serverNotRunning + case revocationNotSaved + case deletionNotSaved + + var title: String { + switch self { + case .serverNotRunning: String(localized: "MCP Server Not Running") + case .revocationNotSaved: String(localized: "Couldn't Save the Revocation") + case .deletionNotSaved: String(localized: "Couldn't Save the Deletion") + } + } + + var message: String { + switch self { + case .serverNotRunning: + String(localized: "The MCP server is not running, so TablePro cannot change its tokens now. Start the server, then try again.") + case .revocationNotSaved, .deletionNotSaved: + String(localized: "TablePro could not save the change to the Keychain. The token works again after TablePro restarts.") + } + } +} + private struct MCPStatusRow: View { @ObservedObject private var manager = MCPServerManager.shared let configuredPort: Int diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift index 7bd91997bc..7e8b296c7b 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift @@ -1,12 +1,18 @@ import SwiftUI +struct MCPTokenCreateFailure: Equatable, Sendable { + let message: String + // Nothing in this sheet can fix a server that is not running, so the alert closes it. + let endsSheet: Bool +} + struct MCPTokenCreateSheet: View { private enum Field: Hashable { case name } @Environment(\.dismiss) private var dismiss - let onGenerate: (String, TokenPermissions, Set?, Date?) -> Void + let onGenerate: (String, TokenPermissions, Set?, Date?) async -> MCPTokenCreateFailure? @State private var tokenName = "" @State private var permissions: TokenPermissions = .readOnly @@ -15,6 +21,8 @@ struct MCPTokenCreateSheet: View { @State private var expirationOption: ExpirationOption = .never @State private var customExpirationDate = Calendar.current.date(byAdding: .day, value: 30, to: .now) ?? .now @State private var connections: [DatabaseConnection] = [] + @State private var isGenerating = false + @State private var failure: MCPTokenCreateFailure? @FocusState private var focused: Field? var body: some View { @@ -36,11 +44,36 @@ struct MCPTokenCreateSheet: View { .task { connections = ConnectionStorage.shared.loadConnections() } + .alert( + String(localized: "Couldn't Create the Token"), + isPresented: failureBinding, + presenting: failure + ) { failure in + Button(String(localized: "OK")) { + self.failure = nil + if failure.endsSheet { + dismiss() + } + } + } message: { failure in + Text(verbatim: failure.message) + } + } + + private var failureBinding: Binding { + Binding( + get: { failure != nil }, + set: { isPresented in + if !isPresented { + failure = nil + } + } + ) } private var nameSection: some View { Section(String(localized: "Token Name")) { - TextField(String(localized: "e.g., Claude Code on VPS"), text: $tokenName) + TextField(String(localized: "e.g., Cursor on my Mac"), text: $tokenName) .focused($focused, equals: .name) } } @@ -120,10 +153,15 @@ struct MCPTokenCreateSheet: View { Button(String(localized: "Generate")) { let connectionIds: Set? = connectionAccess == .selected ? selectedConnectionIds : nil - onGenerate(tokenName, permissions, connectionIds, resolvedExpirationDate) + isGenerating = true + Task { + failure = await onGenerate(tokenName, permissions, connectionIds, resolvedExpirationDate) + isGenerating = false + } } .keyboardShortcut(.defaultAction) - .disabled(tokenName.trimmingCharacters(in: .whitespaces).isEmpty + .disabled(isGenerating + || tokenName.trimmingCharacters(in: .whitespaces).isEmpty || (connectionAccess == .selected && selectedConnectionIds.isEmpty)) } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift index e949d0b88c..8f1e0f9ad9 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift @@ -4,12 +4,13 @@ import TableProMCP struct MCPTokenListView: View { let tokens: [MCPAuthToken] + let isStoreAvailable: Bool let onGenerate: () -> Void let onRevoke: (UUID) -> Void - let onDelete: (UUID) -> Void + let onDelete: (Set) -> Void @State private var selection: Set = [] - @State private var deleteCandidate: MCPAuthToken? + @State private var deleteCandidates: [MCPAuthToken] = [] var body: some View { VStack(alignment: .leading, spacing: 8) { @@ -36,22 +37,28 @@ struct MCPTokenListView: View { Label(String(localized: "Generate Token"), systemImage: "plus") } .buttonStyle(.borderedProminent) + .disabled(!isStoreAvailable) .accessibilityLabel(String(localized: "Generate token")) Spacer() } } - .alert(deleteAlertTitle, isPresented: deleteAlertBinding, presenting: deleteCandidate) { token in + .alert( + deleteAlertTitle, + isPresented: deleteAlertBinding, + presenting: deleteCandidates.isEmpty ? nil : deleteCandidates + ) { candidates in Button(String(localized: "Cancel"), role: .cancel) { - deleteCandidate = nil + deleteCandidates = [] } Button(String(localized: "Delete"), role: .destructive) { - onDelete(token.id) - selection.remove(token.id) - deleteCandidate = nil + let ids = Set(candidates.map(\.id)) + onDelete(ids) + selection.subtract(ids) + deleteCandidates = [] } - } message: { token in - Text(String(format: String(localized: "“%@” will be permanently deleted. External clients using this token will lose access immediately."), token.name)) + } message: { candidates in + Text(verbatim: Self.deleteAlertMessage(for: candidates)) } } @@ -60,9 +67,11 @@ struct MCPTokenListView: View { Image(systemName: "key") .font(.title) .foregroundStyle(.tertiary) - Text(String(localized: "No tokens created")) + Text(isStoreAvailable ? String(localized: "No tokens created") : String(localized: "Tokens are not available")) .foregroundStyle(.secondary) - Text(String(localized: "Generate a token so external clients can connect with their own credentials.")) + Text(isStoreAvailable + ? String(localized: "Generate a token so external clients can connect with their own credentials.") + : String(localized: "Tokens load while the MCP server is running.")) .font(.caption) .foregroundStyle(.tertiary) .multilineTextAlignment(.center) @@ -87,15 +96,19 @@ struct MCPTokenListView: View { } Divider() Button(role: .destructive) { - deleteCandidate = token + // A right-click inside a multiple selection acts on all of it, as in Finder. + deleteCandidates = selection.contains(token.id) ? selectedTokens : [token] } label: { Label(String(localized: "Delete…"), systemImage: "trash") } } + private var selectedTokens: [MCPAuthToken] { + tokens.filter { selection.contains($0.id) } + } + private func deleteSelectionFromKeyboard() { - guard let id = selection.first, let token = tokens.first(where: { $0.id == id }) else { return } - deleteCandidate = token + deleteCandidates = selectedTokens } private func copyTokenId(_ id: UUID) { @@ -104,15 +117,27 @@ struct MCPTokenListView: View { } private var deleteAlertTitle: String { - String(localized: "Delete token?") + deleteCandidates.count > 1 + ? String(format: String(localized: "Delete %d tokens?"), deleteCandidates.count) + : String(localized: "Delete token?") + } + + private static func deleteAlertMessage(for candidates: [MCPAuthToken]) -> String { + guard candidates.count > 1 else { + return String( + format: String(localized: "“%@” will be permanently deleted. External clients using this token will lose access immediately."), + candidates.first?.name ?? "" + ) + } + return String(localized: "These tokens will be permanently deleted. External clients using them will lose access immediately.") } private var deleteAlertBinding: Binding { Binding( - get: { deleteCandidate != nil }, + get: { !deleteCandidates.isEmpty }, set: { isPresented in if !isPresented { - deleteCandidate = nil + deleteCandidates = [] } } ) diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift index 9c2c59ab94..7dd6d41913 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift @@ -2,14 +2,24 @@ import AppKit import SwiftUI struct MCPTokenRevealSheet: View { - let token: MCPAuthToken let plaintext: String let port: Int + let configuredPort: Int @Environment(\.dismiss) private var dismiss @State private var isTokenRevealed = false - @State private var selectedClient: IntegrationClient = .claudeCode - @FocusState private var doneFocused: Bool + @State private var selectedClientID: String + + private let setup: MCPHTTPClientSetup + + init(plaintext: String, port: Int, configuredPort: Int) { + self.plaintext = plaintext + self.port = port + self.configuredPort = configuredPort + let setup = MCPHTTPClientSetup(port: port) + self.setup = setup + _selectedClientID = State(initialValue: setup.choices.first?.id ?? MCPHTTPClientSetup.otherClientID) + } var body: some View { VStack(spacing: 0) { @@ -28,7 +38,6 @@ struct MCPTokenRevealSheet: View { Spacer() Button(String(localized: "Done")) { dismiss() } .keyboardShortcut(.defaultAction) - .focused($doneFocused) } .padding() } @@ -46,7 +55,7 @@ struct MCPTokenRevealSheet: View { .font(.headline) HStack(spacing: 8) { - Text(isTokenRevealed ? plaintext : maskedToken) + Text(verbatim: displayedToken) .font(.system(.body, design: .monospaced)) .textSelection(.enabled) .lineLimit(1) @@ -71,74 +80,84 @@ struct MCPTokenRevealSheet: View { .clipShape(RoundedRectangle(cornerRadius: 6)) Button { - copyToClipboard(plaintext) + ClipboardService.shared.writeSecretText(plaintext) + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) } label: { Label(String(localized: "Copy Token"), systemImage: "doc.on.doc") } - .buttonStyle(.borderedProminent) .accessibilityLabel(String(localized: "Copy token")) } } - private var maskedToken: String { - String(plaintext.prefix(8)) + String(repeating: "\u{2022}", count: 24) - } - private var setupInstructions: some View { VStack(alignment: .leading, spacing: 12) { Text(String(localized: "Setup Instructions")) .font(.headline) - Picker(String(localized: "Client"), selection: $selectedClient) { - ForEach(IntegrationClient.allCases) { client in - Text(client.displayName).tag(client) + Picker(String(localized: "Client"), selection: $selectedClientID) { + ForEach(setup.choices) { choice in + Text(verbatim: choice.name).tag(choice.id) } } - .labelsHidden() - .pickerStyle(.segmented) + .pickerStyle(.menu) + .fixedSize() + .accessibilityIdentifier("mcp-token-client-picker") + + if port != configuredPort { + NoticeLabel(String( + format: String(localized: "Port %d was in use, so this address changes when TablePro restarts."), + configuredPort + )) + } - CopyableCodeBlock(text: configSnippet(for: selectedClient), isSecret: true) + if selectedClientID == MCPHTTPClientSetup.otherClientID { + otherClientInstructions + } else { + clientInstructions + } } } - private var baseURL: String { - let scheme = "http" - return "\(scheme)://127.0.0.1:\(port)/mcp" - } - - private func configSnippet(for client: IntegrationClient) -> String { - switch client { - case .claudeCode: - return "claude mcp add tablepro --transport http \(baseURL) --header \"Authorization: Bearer \(plaintext)\"" - case .claudeDesktop, .cursor: - return """ - { - "mcpServers": { - "tablepro": { - "url": "\(baseURL)", - "headers": { - "Authorization": "Bearer \(plaintext)" - } - } - } + @ViewBuilder + private var clientInstructions: some View { + if let copied = setup.render(clientID: selectedClientID, token: plaintext), + let shown = setup.render(clientID: selectedClientID, token: displayedToken) { + if let commandLine = copied.commandLine { + Text(String(localized: "Run this in Terminal:")) + CopyableCodeBlock(text: commandLine, displayText: shown.commandLine, isSecret: true) } - """ - case .zed: - return """ - { - "tablepro": { - "url": "\(baseURL)", - "headers": { - "Authorization": "Bearer \(plaintext)" + if let snippet = copied.snippet { + if let path = copied.displayConfigPath { + Text(String(format: String(localized: "Add this to %@:"), path)) } - } + CopyableCodeBlock(text: snippet, displayText: shown.snippet, isSecret: true) } - """ + } else { + otherClientInstructions + } + } + + private var otherClientInstructions: some View { + VStack(alignment: .leading, spacing: 8) { + Text(String(localized: "Give your client this address and header:")) + CopyableCodeBlock(text: setup.url) + CopyableCodeBlock( + text: header(token: plaintext), + displayText: header(token: displayedToken), + isSecret: true + ) } } - private func copyToClipboard(_ text: String) { - ClipboardService.shared.writeSecretText(text) - AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) + private func header(token: String) -> String { + "Authorization: " + MCPHTTPClientSetup.authorization(token: token) + } + + private var displayedToken: String { + isTokenRevealed ? plaintext : maskedToken + } + + private var maskedToken: String { + String(plaintext.prefix(8)) + String(repeating: "\u{2022}", count: 24) } } diff --git a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift index 08ed74db2d..501dd6e6b9 100644 --- a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift @@ -56,12 +56,7 @@ struct PairingApprovalSheet: View { expirySection } .formStyle(.grouped) - /// The one greedy child, and the reason the sheet needs a bound at all. A grouped - /// `Form` is a scroll container, so it answers any proposal with the whole proposed - /// height: unbounded, it measured `CGFloat.greatestFiniteMagnitude`, and the window - /// sized from that raised. Capping it here rather than fixing the sheet's own height - /// keeps the rest of the sheet free to grow with the text size. The sections scroll - /// inside the cap. (#2930) + // A grouped Form answers any proposal with the whole height, so it alone is capped (#2930). .frame(maxHeight: 420) Divider() @@ -81,8 +76,7 @@ struct PairingApprovalSheet: View { private var header: some View { VStack(alignment: .leading, spacing: 6) { - /// The name is whatever the request asked to be called, so it is bounded here rather - /// than trusted to be short enough to lay out. + // The name is whatever the request asked to be called, so its length is bounded here. Text(String(format: String(localized: "Allow %@ to access TablePro?"), request.clientName)) .font(.headline) .lineLimit(2) @@ -97,10 +91,7 @@ struct PairingApprovalSheet: View { .padding() } - /// Where the one-time code is delivered, which is the only part of the request that says who - /// actually receives the grant. The client name above is a label the request chose for itself, - /// so approving on that alone approves a destination nobody was shown. Truncated in the middle - /// rather than the tail, because the scheme and the host are what a reader checks. + // The client name is the request's own label; this says who receives the grant, so it keeps the scheme and host. private var destinationLabel: some View { HStack(spacing: 6) { Image(systemName: "arrow.up.forward.app") @@ -122,7 +113,7 @@ struct PairingApprovalSheet: View { .foregroundStyle(isExpired ? .red : Color(nsColor: .secondaryLabelColor)) .imageScale(.small) .accessibilityHidden(true) - Text(countdownText) + countdownText .font(.caption) .monospacedDigit() .foregroundStyle(.secondary) @@ -139,11 +130,11 @@ struct PairingApprovalSheet: View { remainingSeconds <= 0 } - private var countdownText: String { + private var countdownText: Text { if isExpired { - return String(localized: "Code expired") + return Text(String(localized: "Code expired")) } - return String(format: String(localized: "Code expires in %d seconds"), remainingSeconds) + return Text("Code expires in ^[\(remainingSeconds) second](inflect: true)") } private var permissionsSection: some View { @@ -234,8 +225,7 @@ struct PairingApprovalSheet: View { request.scopeRequest.optionalGrants.contains(.connectionsDisplay) } - /// Starts off even when the setting allows it: an agent with a shell can open a pairing link to - /// its own loopback redirect, and one click on Approve must not hand it these connections. + // Off even when allowed: an agent with a shell can pair to its own redirect, and one Approve must not hand it these. private var hiddenConnectionsSection: some View { Section(String(localized: "Connections Hidden from AI")) { if allowsHiddenConnectionListing { diff --git a/apple/TableProTests/Core/AI/AIProviderPresetTests.swift b/apple/TableProTests/Core/AI/AIProviderPresetTests.swift index 985de058dc..1ba8d7a150 100644 --- a/apple/TableProTests/Core/AI/AIProviderPresetTests.swift +++ b/apple/TableProTests/Core/AI/AIProviderPresetTests.swift @@ -52,7 +52,7 @@ struct AIProviderPresetTests { #expect(config.name == "Requesty") #expect(config.endpoint == "https://router.requesty.ai") #expect(config.kindName == "Requesty") - #expect(config.symbolName == AIProviderPreset.requesty.symbolName) + #expect(config.icon == AIProviderPreset.requesty.icon) #expect(config.authStyle == .apiKey) } @@ -68,7 +68,7 @@ struct AIProviderPresetTests { let config = AIProviderConfig(type: .custom, endpoint: "https://api.z.ai/api/paas/v4") #expect(config.preset == nil) #expect(config.kindName == AIProviderType.custom.displayName) - #expect(config.symbolName == AIProviderType.custom.symbolName) + #expect(config.icon == AIProviderType.custom.icon) #expect(config.authStyle == .optionalApiKey) #expect(config.defaultEndpoint.isEmpty) } diff --git a/apple/TableProTests/Core/AI/ClaudeAgentConnectionScopeTests.swift b/apple/TableProTests/Core/AI/ClaudeAgentConnectionScopeTests.swift index c589970a09..efa65e6e30 100644 --- a/apple/TableProTests/Core/AI/ClaudeAgentConnectionScopeTests.swift +++ b/apple/TableProTests/Core/AI/ClaudeAgentConnectionScopeTests.swift @@ -1,8 +1,3 @@ -// -// ClaudeAgentConnectionScopeTests.swift -// TableProTests -// - import Foundation @testable import TablePro import TableProMCP @@ -19,6 +14,22 @@ private actor RecordingToolBridge: ClaudeAgentMCPBridging { func release(_ grant: ClaudeAgentToolGrant?) async {} } +private struct FailingToolBridge: ClaudeAgentMCPBridging { + func makeGrant(connectionId: UUID?) async throws -> ClaudeAgentToolGrant? { + throw ClaudeAgentToolGrantError.tokenNotSaved + } + + func release(_ grant: ClaudeAgentToolGrant?) async {} +} + +private struct RefusingCredentialStore: MCPTokenCredentialStoring { + func read() -> MCPTokenBlob { .found(Data("[]".utf8)) } + + func write(_ data: Data) -> Bool { false } + + func delete() {} +} + struct ClaudeAgentConnectionScopeTests { @Test("The token reaches the conversation's connection and no other") func tokenIsLimitedToTheConversationConnection() throws { @@ -31,9 +42,39 @@ struct ClaudeAgentConnectionScopeTests { } @Test("A conversation with no connection gets no token") - func noConnectionMeansNoToken() async { + func noConnectionMeansNoToken() async throws { #expect(ClaudeAgentMCPBridge.connectionAccess(for: nil) == nil) - #expect(await ClaudeAgentMCPBridge().makeGrant(connectionId: nil) == nil) + #expect(try await ClaudeAgentMCPBridge().makeGrant(connectionId: nil) == nil) + } + + @Test("A token the Keychain refused stops the grant with a reason instead of dropping the tools") + func unsavedTokenIsAnError() async throws { + let store = MCPTokenStore(credentialStore: RefusingCredentialStore()) + let endpoint = try #require(URL(string: "http://127.0.0.1:1/mcp")) + let bridge = ClaudeAgentMCPBridge(endpoint: { endpoint }, tokenStore: { store }) + + await #expect(throws: ClaudeAgentToolGrantError.tokenNotSaved) { + _ = try await bridge.makeGrant(connectionId: UUID()) + } + #expect(await store.list().isEmpty) + #expect(ClaudeAgentToolGrantError.tokenNotSaved.localizedDescription.contains("Keychain")) + } + + @Test("The chat gets the grant's failure as the turn's error") + func grantFailureEndsTheTurn() async throws { + let provider = ClaudeAgentProvider( + model: "sonnet", + cli: ClaudeAgentCLI(executableOverride: "/usr/bin/true"), + toolBridge: FailingToolBridge() + ) + let stream = provider.streamChat( + turns: [ChatTurnWire(role: .user, blocks: [.text("hi")])], + options: ChatTransportOptions(model: "sonnet", connectionId: UUID()) + ) + + await #expect(throws: ClaudeAgentToolGrantError.tokenNotSaved) { + for try await _ in stream {} + } } @Test("Transport options carry no connection unless the caller names one") diff --git a/apple/TableProTests/Core/MCP/CLIPairingContractTests.swift b/apple/TableProTests/Core/MCP/CLIPairingContractTests.swift index e5bd5729df..56d632522a 100644 --- a/apple/TableProTests/Core/MCP/CLIPairingContractTests.swift +++ b/apple/TableProTests/Core/MCP/CLIPairingContractTests.swift @@ -30,7 +30,7 @@ struct CLIPairingContractTests { #expect(PairingExchangeStore.sha256Base64Url(of: request.verifier) == request.challenge) } - @Test("The app's approve and deny redirects reach the command as approved and denied") + @Test("The app's approve, deny and failure redirects reach the command as approved, denied and failed") func redirectsRoundTrip() throws { let request = CLIPairingRequest.random() let parsed = try pairingRequest(request) @@ -44,6 +44,11 @@ struct CLIPairingContractTests { base: parsed.redirectURL, state: parsed.state, mode: parsed.responseMode )) #expect(CLIPairingCallback.parse(requestTarget: Self.target(of: denied), state: request.state) == .denied) + + let failed = try #require(PairingRedirectBuilder.failed( + base: parsed.redirectURL, state: parsed.state, mode: parsed.responseMode + )) + #expect(CLIPairingCallback.parse(requestTarget: Self.target(of: failed), state: request.state) == .failed) } // What a browser puts on the request line for the URL it was handed. diff --git a/apple/TableProTests/Core/MCP/Clients/MCPClientRowPresentationTests.swift b/apple/TableProTests/Core/MCP/Clients/MCPClientRowPresentationTests.swift new file mode 100644 index 0000000000..72412c8d1c --- /dev/null +++ b/apple/TableProTests/Core/MCP/Clients/MCPClientRowPresentationTests.swift @@ -0,0 +1,179 @@ +import Foundation +@testable import TablePro +import TableProMCPClients +import Testing + +struct MCPClientRowPresentationTests { + private func row( + config: MCPClientConfigState = .notConfigured, + isInstalled: Bool = true, + installRoute: MCPClientRoute = .file, + updateRoute: MCPClientRoute = .file, + removeRoute: MCPClientRoute? = nil, + unsupported: MCPClientUnsupported? = nil, + isConfigWritable: Bool = true, + commandLine: String? = nil + ) -> MCPClientRow { + MCPClientRow( + id: "cursor", + name: "Cursor", + iconSlug: "cursor", + isDetected: isInstalled, + isInstalled: isInstalled, + config: config, + installRoute: installRoute, + updateRoute: updateRoute, + removeRoute: removeRoute, + unsupported: unsupported, + applies: .live, + configPath: "/Users/me/.cursor/mcp.json", + displayConfigPath: "~/.cursor/mcp.json", + configFileExists: true, + isConfigWritable: isConfigWritable, + snippet: "{}", + commandLine: commandLine + ) + } + + private func present( + _ row: MCPClientRow, + activity: MCPClientActivity? = nil, + connection: MCPClientConnection = .notConnected + ) -> MCPClientRowPresentation { + MCPClientRowPresentation(row: row, activity: activity, connection: connection) + } + + @Test("A client that hands off to its own app offers Install with an ellipsis") + func deeplinkInstall() { + let presentation = present(row(installRoute: .deeplink(scheme: "cursor"))) + #expect(presentation.action == .install(handsOff: true)) + #expect(presentation.action?.title == String(localized: "Install…")) + #expect(presentation.subtitle == String(format: String(localized: "Opens %@ to confirm"), "Cursor")) + #expect(presentation.status == nil) + } + + @Test("A client set up through its command or its file offers a plain Install") + func inPlaceInstall() { + let viaCommand = present(row(installRoute: .cli(binary: "claude"))) + #expect(viaCommand.action?.title == String(localized: "Install")) + #expect(viaCommand.subtitle == String(format: String(localized: "Adds through the %@ command"), "claude")) + + let viaFile = present(row(installRoute: .file)) + #expect(viaFile.action == .install(handsOff: false)) + #expect(viaFile.subtitle == String(format: String(localized: "Edits %@"), "~/.cursor/mcp.json")) + } + + @Test("A client set up for this copy offers no button and never offers Remove as one") + func currentHasNoButton() { + let presentation = present(row(config: .current, removeRoute: .file)) + #expect(presentation.action == nil) + #expect(presentation.status == String(localized: "Set up")) + } + + @Test("A client set up for a moved or other copy offers Update") + func staleOffersUpdate() { + let moved = present(row(config: .moved)) + #expect(moved.action == .update(handsOff: false)) + #expect(moved.status == String(localized: "TablePro moved")) + + let otherCopy = present(row(config: .otherCopy, updateRoute: .deeplink(scheme: "cursor"))) + #expect(otherCopy.action?.title == String(localized: "Update…")) + #expect(otherCopy.status == String(localized: "Uses another copy")) + } + + @Test("A client that is not on this Mac offers Copy") + func notFoundOffersCopy() { + let presentation = present(row(isInstalled: false, installRoute: .copy, updateRoute: .copy)) + #expect(presentation.action == .copy) + #expect(presentation.status == String(localized: "Not found")) + #expect(presentation.subtitle == String(format: String(localized: "Copy the setup into %@"), "~/.cursor/mcp.json")) + } + + @Test("A settings file TablePro cannot read is never written, so the row offers Copy") + func unreadableOffersCopy() { + let presentation = present(row(config: .unreadable, installRoute: .file)) + #expect(presentation.action == .copy) + #expect(presentation.status == String(localized: "Can't read settings")) + } + + @Test("A client that cannot reach a local server says why and offers nothing") + func unsupportedHasNoAction() { + let presentation = present(row(unsupported: .remoteOnly), connection: .connected) + #expect(presentation.action == nil) + #expect(presentation.status == nil) + #expect(presentation.subtitle == String(localized: "Reaches only servers on the internet")) + } + + @Test("A running action replaces the button and names what it does") + func busyRow() { + let presentation = present(row(), activity: .running(.install)) + #expect(presentation.isBusy) + #expect(presentation.action == nil) + #expect(presentation.status == String(localized: "Installing…")) + } + + @Test("A live session outranks the settings status, and a new one reads just now") + func connectionStatus() { + #expect(present(row(config: .current), connection: .connected).status == String(localized: "Connected")) + #expect(present(row(config: .current), connection: .justConnected).status == String(localized: "Connected just now")) + } + + @Test("A failed action stays on the row until the next one") + func failedStatus() { + let presentation = present(row(config: .moved), activity: .failed(.update, message: "boom", output: nil)) + #expect(presentation.status == String(localized: "Couldn't update")) + #expect(presentation.action == .update(handsOff: false)) + } + + @Test("A file only the client writes is copied as its command") + func commandOnlyCopy() { + let claudeCode = row(isConfigWritable: false, commandLine: "claude mcp add --scope user tablepro -- /x") + #expect(claudeCode.copyText == "claude mcp add --scope user tablepro -- /x") + #expect(row(commandLine: "codex mcp add tablepro -- /x").copyText == "{}") + } + + @Test("A token setup, a setup turned off in the client and a project override offer no button") + func userChoicesHaveNoButton() { + let token = present(row(config: .usesToken, removeRoute: .file)) + #expect(token.action == nil) + #expect(token.status == String(localized: "Set up with a token")) + #expect(MCPClientDetailText.configState(.usesToken, name: "Cursor") != nil) + + let off = present(row(config: .disabled)) + #expect(off.action == nil) + #expect(off.status == String(localized: "Turned off")) + #expect(MCPClientDetailText.configState(.disabled, name: "Cursor") != nil) + + let shadowed = present(row(config: .shadowed(project: "~/work/shop"))) + #expect(shadowed.action == nil) + #expect(shadowed.status == String(localized: "Old setup in a project")) + #expect(MCPClientDetailText.configState(.shadowed(project: "~/work/shop"), name: "Cursor")?.contains("~/work/shop") == true) + } + + @Test("The engine's statuses map to row states that keep the entry") + func statusMapping() { + #expect(MCPClientConfigState(.usesToken) == .usesToken) + #expect(MCPClientConfigState(.disabled) == .disabled) + let shadowed = MCPClientConfigState(.stale(.shadowed(scope: "/Users/me/shop"))) { $0.replacingOccurrences(of: "/Users/me", with: "~") } + #expect(shadowed == .shadowed(project: "~/shop")) + #expect(MCPClientConfigState.usesToken.hasEntry) + #expect(!MCPClientConfigState.usesToken.needsUpdate) + #expect(!MCPClientConfigState.shadowed(project: "~/shop").needsUpdate) + #expect(MCPClientConfigState.usesToken.isUserChoice) + #expect(MCPClientConfigState.disabled.isUserChoice) + #expect(!MCPClientConfigState.otherCopy.isUserChoice) + } + + @Test("Each row button's spoken label names its client") + func accessibilityLabels() { + let labels = [ + MCPClientRowAction.install(handsOff: true).accessibilityLabel(clientName: "Cursor"), + MCPClientRowAction.update(handsOff: false).accessibilityLabel(clientName: "Cursor"), + MCPClientRowAction.copy.accessibilityLabel(clientName: "Cursor"), + ] + #expect(labels.allSatisfy { $0.contains("Cursor") }) + #expect(Set(labels).count == 3) + #expect(MCPClientRowAction.install(handsOff: false).accessibilityLabel(clientName: "Zed") + != MCPClientRowAction.install(handsOff: false).accessibilityLabel(clientName: "Cursor")) + } +} diff --git a/apple/TableProTests/Core/MCP/Clients/MCPClientSetupFixture.swift b/apple/TableProTests/Core/MCP/Clients/MCPClientSetupFixture.swift new file mode 100644 index 0000000000..ed1a92e6b3 --- /dev/null +++ b/apple/TableProTests/Core/MCP/Clients/MCPClientSetupFixture.swift @@ -0,0 +1,252 @@ +import Combine +import Foundation +@testable import TablePro +import TableProMCPClients + +enum MCPClientSetupFixture { + static let catalogJSON = #""" + { + "schemaVersion": 1, + "serverName": "tablepro", + "configs": { + "editor": { "macos": { "path": "~/.editor/mcp.json", "format": "json", "keyPath": ["mcpServers"] } }, + "agent": { + "macos": { "path": "~/.agent.json", "format": "json", "keyPath": ["mcpServers"], "writable": false, "otherScopes": [["projects", "*", "mcpServers"]] } + }, + "shared": { "macos": { "path": "~/.shared/config.toml", "format": "toml", "keyPath": ["mcp_servers"] } } + }, + "clients": [ + { + "id": "editor", "name": "Editor", "icon": "editor", "config": "editor", + "clientInfo": { "names": ["editor-client"], "prefixes": [] }, + "macos": { + "detect": [{ "bundleId": "com.example.editor" }, { "path": "~/.editor" }], + "entry": { "command": "{command}", "args": [], "tools": ["*"] }, + "install": [ + { "kind": "deeplink", "scheme": "editor", "url": "editor://install?name={name}&config={entry|json|base64|uri}" }, + { "kind": "cli", "binary": "editor", "add": ["mcp", "add", "{name}", "--", "{command}"], "remove": ["mcp", "remove", "{name}"], "update": "add" }, + { "kind": "file" } + ], + "applies": "live" + }, + "linux": { + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }] + } + }, + { + "id": "agent", "name": "Agent", "icon": "agent", "config": "agent", + "clientInfo": { "names": ["agent-cli"], "prefixes": [] }, + "macos": { + "detect": [{ "binary": "agent", "paths": ["~/bin/agent"] }], + "entry": { "type": "stdio", "command": "{command}", "args": [] }, + "install": [ + { + "kind": "cli", "binary": "agent", + "add": ["mcp", "add", "--scope", "user", "{name}", "--", "{command}"], + "remove": ["mcp", "remove", "--scope", "user", "{name}"], + "update": "removeThenAdd" + } + ], + "applies": "newSession" + }, + "linux": { + "entry": { "type": "http", "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [ + { "kind": "cli", "binary": "agent", "add": ["mcp", "add", "--transport", "http", "{name}", "{url}", "--header", "Authorization: {authorization}"] } + ] + } + }, + { + "id": "desk", "name": "Desk", "icon": "desk", "config": "shared", + "clientInfo": { "names": ["shared-client"], "prefixes": [] }, + "macos": { + "detect": [{ "bundleId": "com.example.desk" }], + "entry": { "command": "{command}", "args": [] }, + "install": [{ "kind": "file" }], + "applies": "restartApp" + } + }, + { + "id": "term", "name": "Term", "icon": "term", "config": "shared", + "clientInfo": { "names": ["shared-client"], "prefixes": [] }, + "macos": { + "detect": [{ "path": "~/.shared" }], + "entry": { "command": "{command}", "args": [] }, + "install": [{ "kind": "file" }], + "applies": "newSession" + } + }, + { + "id": "remote", "name": "Remote", "icon": "remote", "config": null, + "clientInfo": { "names": [], "prefixes": [] }, + "macos": { "detect": [{ "bundleId": "com.example.remote" }], "unsupported": "remoteOnly" } + }, + { + "id": "penguin", "name": "Penguin", "icon": "penguin", "config": "editor", + "clientInfo": { "names": ["penguin"], "prefixes": [] }, + "linux": { "detect": [{ "path": "~/.penguin" }], "entry": { "url": "{url}" }, "install": [{ "kind": "file" }] } + } + ] + } + """# + + static func catalog() throws -> MCPClientCatalog { + try MCPClientCatalog.decode(Data(catalogJSON.utf8)) + } +} + +// A home folder of its own, so no test reads or writes the real one. +final class MCPClientTestHome { + let root: URL + let bridge: URL + + init() throws { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("mcp-clients-\(UUID().uuidString.prefix(8))", isDirectory: true) + bridge = root.appendingPathComponent("Applications/TablePro.app/Contents/MacOS/tablepro-mcp") + try FileManager.default.createDirectory(at: bridge.deletingLastPathComponent(), withIntermediateDirectories: true) + FileManager.default.createFile(atPath: bridge.path, contents: Data()) + } + + deinit { + try? FileManager.default.removeItem(at: root) + } + + var path: String { root.path } + + func url(_ relative: String) -> URL { + root.appendingPathComponent(relative) + } + + func write(_ relative: String, _ text: String) throws { + let file = url(relative) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + + func read(_ relative: String) -> String? { + try? String(contentsOf: url(relative), encoding: .utf8) + } + + func makeFolder(_ relative: String) throws { + try FileManager.default.createDirectory(at: url(relative), withIntermediateDirectories: true) + } + + func makeExecutable(_ relative: String) throws { + try write(relative, "#!/bin/sh\n") + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url(relative).path) + } + + func remove(_ relative: String) throws { + try FileManager.default.removeItem(at: url(relative)) + } + + func context(workspace: FakeMCPClientWorkspace) -> MCPClientSetupContext { + let home = path + return MCPClientSetupContext( + home: home, + environment: [:], + bridgePath: bridge.path, + workspace: workspace, + isExecutable: { $0.hasPrefix(home + "/") && FileManager.default.isExecutableFile(atPath: $0) } + ) + } +} + +final class FakeMCPClientWorkspace: MCPClientWorkspace, @unchecked Sendable { + private let lock = NSLock() + private let installedBundleIDs: Set + private let handledSchemes: Set + private var openedURLs: [URL] = [] + + init(installedBundleIDs: Set = [], handledSchemes: Set = []) { + self.installedBundleIDs = installedBundleIDs + self.handledSchemes = handledSchemes + } + + var opened: [URL] { + lock.lock() + defer { lock.unlock() } + return openedURLs + } + + func applicationURL(forBundleIdentifier identifier: String) -> URL? { + installedBundleIDs.contains(identifier) ? URL(fileURLWithPath: "/Applications/\(identifier).app") : nil + } + + func applicationURL(toOpen url: URL) -> URL? { + guard let scheme = url.scheme, handledSchemes.contains(scheme) else { return nil } + return URL(fileURLWithPath: "/Applications/\(scheme).app") + } + + func open(_ url: URL) async throws { + lock.withLock { openedURLs.append(url) } + } +} + +final class FakeMCPClientRunner: MCPClientCommandRunning, @unchecked Sendable { + struct Call: Equatable { + let executable: String + let arguments: [String] + let home: String? + } + + private let lock = NSLock() + private var replies: [MCPClientCommandResult] + private var recorded: [Call] = [] + + init(replies: [MCPClientCommandResult] = []) { + self.replies = replies + } + + var calls: [Call] { + lock.lock() + defer { lock.unlock() } + return recorded + } + + func run(executable: URL, arguments: [String], environment: [String: String]) async throws -> MCPClientCommandResult { + lock.withLock { + recorded.append(Call(executable: executable.path, arguments: arguments, home: environment["HOME"])) + return replies.isEmpty ? MCPClientCommandResult(exitCode: 0, output: "") : replies.removeFirst() + } + } +} + +@MainActor +final class MCPClientAnnouncements { + private(set) var messages: [String] = [] + + func record(_ message: String) { + messages.append(message) + } +} + +@MainActor +struct MCPClientServiceHarness { + let service: MCPClientSetupService + let sessions: PassthroughSubject<[MCPClientSessionSighting], Never> + let announcements: MCPClientAnnouncements + + init( + home: MCPClientTestHome, + workspace: FakeMCPClientWorkspace = FakeMCPClientWorkspace(), + runner: FakeMCPClientRunner = FakeMCPClientRunner(), + isAppOnReadOnlyVolume: Bool = false + ) throws { + let sessions = PassthroughSubject<[MCPClientSessionSighting], Never>() + let announcements = MCPClientAnnouncements() + self.sessions = sessions + self.announcements = announcements + service = MCPClientSetupService( + catalog: try MCPClientSetupFixture.catalog(), + context: home.context(workspace: workspace), + runner: runner, + isAppOnReadOnlyVolume: isAppOnReadOnlyVolume, + sessions: sessions.eraseToAnyPublisher(), + activations: Empty().eraseToAnyPublisher(), + announce: { announcements.record($0) } + ) + } +} diff --git a/apple/TableProTests/Core/MCP/Clients/MCPClientSetupServiceTests.swift b/apple/TableProTests/Core/MCP/Clients/MCPClientSetupServiceTests.swift new file mode 100644 index 0000000000..87e6540b5b --- /dev/null +++ b/apple/TableProTests/Core/MCP/Clients/MCPClientSetupServiceTests.swift @@ -0,0 +1,429 @@ +import Combine +import Foundation +@testable import TablePro +import TableProMCPClients +import Testing + +@MainActor +struct MCPClientSetupServiceTests { + @Test("Each client this Mac can run is listed with the state of its settings") + func rowsCarryConfigStatus() async throws { + let home = try MCPClientTestHome() + try home.write(".editor/mcp.json", #"{ "mcpServers": { "tablepro": { "command": "\#(home.bridge.path)", "args": [] } } }"#) + try home.write(".shared/config.toml", "[mcp_servers.tablepro]\ncommand = \"/Volumes/Gone/TablePro.app/Contents/MacOS/tablepro-mcp\"\nargs = []\n") + let harness = try MCPClientServiceHarness( + home: home, + workspace: FakeMCPClientWorkspace(installedBundleIDs: ["com.example.desk"]) + ) + + await harness.service.refresh() + + let service = harness.service + #expect(service.rows.map { $0.id } == ["editor", "agent", "desk", "term", "remote"]) + #expect(service.row(id: "editor")?.config == .current) + #expect(service.row(id: "agent")?.config == .notConfigured) + #expect(service.row(id: "agent")?.isInstalled == false) + #expect(service.row(id: "desk")?.config == .moved) + #expect(service.row(id: "desk")?.isInstalled == true) + #expect(service.row(id: "term")?.config == .moved) + #expect(service.row(id: "remote")?.unsupported == .remoteOnly) + } + + @Test("Install takes the first method this Mac offers, in the catalog's order") + func installRouteFollowsAvailability() async throws { + let home = try MCPClientTestHome() + try home.makeFolder(".editor") + + let withHandler = try MCPClientServiceHarness(home: home, workspace: FakeMCPClientWorkspace(handledSchemes: ["editor"])) + await withHandler.service.refresh() + #expect(withHandler.service.row(id: "editor")?.installRoute == .deeplink(scheme: "editor")) + + try home.makeExecutable(".local/bin/editor") + let withCommand = try MCPClientServiceHarness(home: home) + await withCommand.service.refresh() + #expect(withCommand.service.row(id: "editor")?.installRoute == .cli(binary: "editor")) + + try home.remove(".local/bin/editor") + let withFileOnly = try MCPClientServiceHarness(home: home) + await withFileOnly.service.refresh() + #expect(withFileOnly.service.row(id: "editor")?.installRoute == .file) + + try home.remove(".editor") + let notFound = try MCPClientServiceHarness(home: home) + await notFound.service.refresh() + let row = try #require(notFound.service.row(id: "editor")) + #expect(row.installRoute == .copy) + #expect(notFound.service.presentation(for: row).action == .copy) + } + + @Test("Updating a client whose command cannot replace removes first, and a missing entry counts as removed") + func removeThenAddUpdate() async throws { + let home = try MCPClientTestHome() + try home.makeExecutable("bin/agent") + try home.write(".agent.json", #"{ "mcpServers": { "tablepro": { "type": "stdio", "command": "/Volumes/Gone/tablepro-mcp", "args": [] } } }"#) + let runner = FakeMCPClientRunner(replies: [ + MCPClientCommandResult(exitCode: 1, output: "No MCP server named tablepro found in user config"), + MCPClientCommandResult(exitCode: 0, output: "Added stdio MCP server tablepro to user config") + ]) + let harness = try MCPClientServiceHarness(home: home, runner: runner) + await harness.service.refresh() + let row = try #require(harness.service.row(id: "agent")) + #expect(row.config == .moved) + #expect(MCPClientRowPresentation.action(row: row) == .update(handsOff: false)) + + let outcome = await harness.service.update("agent") + + #expect(outcome == .done(backupPath: nil)) + #expect(runner.calls.map { $0.arguments } == [ + ["mcp", "remove", "--scope", "user", "tablepro"], + ["mcp", "add", "--scope", "user", "tablepro", "--", home.bridge.path] + ]) + #expect(runner.calls.allSatisfy { $0.executable == home.url("bin/agent").path }) + #expect(runner.calls.allSatisfy { $0.home == home.path }) + } + + @Test("A command that fails keeps its output for the detail area") + func failedCommandKeepsOutput() async throws { + let home = try MCPClientTestHome() + try home.makeExecutable("bin/agent") + let runner = FakeMCPClientRunner(replies: [MCPClientCommandResult(exitCode: 2, output: "permission denied\n")]) + let harness = try MCPClientServiceHarness(home: home, runner: runner) + await harness.service.refresh() + + let outcome = await harness.service.install("agent") + + guard case let .failed(_, output) = outcome else { + Issue.record("Expected a failure, got \(outcome)") + return + } + #expect(output == "permission denied") + let row = try #require(harness.service.row(id: "agent")) + #expect(harness.service.presentation(for: row).status == String(localized: "Couldn't install")) + } + + @Test("A copy running from a disk image refuses to install and writes nothing") + func readOnlyVolumeRefuses() async throws { + let home = try MCPClientTestHome() + try home.makeFolder(".editor") + try home.makeExecutable("bin/agent") + let runner = FakeMCPClientRunner() + let harness = try MCPClientServiceHarness(home: home, runner: runner, isAppOnReadOnlyVolume: true) + await harness.service.refresh() + + #expect(await harness.service.install("editor") == .refusedReadOnlyVolume) + #expect(await harness.service.install("agent") == .refusedReadOnlyVolume) + #expect(home.read(".editor/mcp.json") == nil) + #expect(runner.calls.isEmpty) + } + + @Test("Install merges TablePro into the settings file and Remove takes only its entry out") + func fileInstallAndRemove() async throws { + let home = try MCPClientTestHome() + try home.write(".editor/mcp.json", #"{ "mcpServers": { "other": { "command": "other-server" } } }"#) + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + #expect(harness.service.row(id: "editor")?.installRoute == .file) + + let installed = await harness.service.install("editor") + + guard case .done(let backup) = installed else { + Issue.record("Expected the install to finish, got \(installed)") + return + } + #expect(backup?.hasSuffix("mcp.json.tablepro-backup") == true) + let servers = try Self.servers(in: try #require(home.read(".editor/mcp.json"))) + #expect((servers["tablepro"] as? [String: Any])?["command"] as? String == home.bridge.path) + #expect((servers["other"] as? [String: Any])?["command"] as? String == "other-server") + #expect(harness.service.row(id: "editor")?.config == .current) + #expect(harness.service.row(id: "editor")?.removeRoute == .file) + + let removed = await harness.service.remove("editor") + + guard case .done = removed else { + Issue.record("Expected the removal to finish, got \(removed)") + return + } + let remaining = try Self.servers(in: try #require(home.read(".editor/mcp.json"))) + #expect(remaining["tablepro"] == nil) + #expect(remaining["other"] != nil) + #expect(harness.service.row(id: "editor")?.config == .notConfigured) + } + + @Test("A deeplink install hands off to the client and waits for it to confirm") + func deeplinkHandsOff() async throws { + let home = try MCPClientTestHome() + let workspace = FakeMCPClientWorkspace(installedBundleIDs: ["com.example.editor"], handledSchemes: ["editor"]) + let harness = try MCPClientServiceHarness(home: home, workspace: workspace) + await harness.service.refresh() + + #expect(await harness.service.install("editor") == .handedOff) + + let opened = try #require(workspace.opened.first) + #expect(opened.scheme == "editor") + #expect(opened.absoluteString.contains("name=tablepro")) + let row = try #require(harness.service.row(id: "editor")) + #expect(harness.service.presentation(for: row).status == String(format: String(localized: "Finish in %@"), "Editor")) + } + + @Test("A client that connects while the sheet is open reads Connected just now and is announced once") + func newSessionIsAnnounced() async throws { + let home = try MCPClientTestHome() + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + let open = MCPClientSessionSighting(id: "open", clientInfoName: "agent-cli", tokenName: MCPTokenStore.stdioBridgeTokenName) + + harness.sessions.send([open]) + + #expect(harness.service.connection(for: "agent") == .connected) + #expect(harness.announcements.messages.isEmpty) + + harness.sessions.send([ + open, + MCPClientSessionSighting( + id: "new", clientInfoName: "shared-client", displayName: "Shared", tokenName: MCPTokenStore.stdioBridgeTokenName + ) + ]) + + #expect(harness.service.connection(for: "desk") == .justConnected) + #expect(harness.service.connection(for: "term") == .justConnected) + #expect(harness.service.connection(for: "agent") == .connected) + #expect(harness.announcements.messages == [String(format: String(localized: "%@ connected"), "Shared")]) + let desk = try #require(harness.service.row(id: "desk")) + #expect(harness.service.presentation(for: desk).status == String(localized: "Connected just now")) + } + + @Test("A session two rows share is announced by the one found on this Mac") + func sharedSessionNamesTheClientFoundHere() async throws { + let home = try MCPClientTestHome() + try home.makeFolder(".shared") + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + #expect(harness.service.row(id: "term")?.isDetected == true) + #expect(harness.service.row(id: "desk")?.isDetected == false) + + harness.sessions.send([]) + harness.sessions.send([ + MCPClientSessionSighting( + id: "new", clientInfoName: "shared-client", displayName: "Shared", tokenName: MCPTokenStore.stdioBridgeTokenName + ) + ]) + + #expect(harness.announcements.messages == [String(format: String(localized: "%@ connected"), "Term")]) + #expect(harness.service.connection(for: "term") == .justConnected) + #expect(harness.service.connection(for: "desk") == .notConnected) + } + + @Test("A session already open when the sheet opens lights only the row found here once the rows are read") + func sharedSessionSettlesOnRefresh() async throws { + let home = try MCPClientTestHome() + try home.makeFolder(".shared") + let harness = try MCPClientServiceHarness(home: home) + harness.sessions.send([ + MCPClientSessionSighting(id: "open", clientInfoName: "shared-client", tokenName: MCPTokenStore.stdioBridgeTokenName) + ]) + #expect(harness.service.connection(for: "desk") == .connected) + #expect(harness.service.connection(for: "term") == .connected) + + await harness.service.refresh() + + #expect(harness.service.connection(for: "term") == .connected) + #expect(harness.service.connection(for: "desk") == .notConnected) + } + + @Test("A clientInfo name two rows share names one of them only when it alone is on this Mac") + func sharedSessionAttribution() throws { + let catalog = try MCPClientSetupFixture.catalog() + let bridge = MCPTokenStore.stdioBridgeTokenName + #expect(catalog.client(forSessionNamed: "shared-client", tokenName: bridge, detected: ["term"])?.id == "term") + #expect(catalog.client(forSessionNamed: "shared-client", tokenName: bridge, detected: []) == nil) + #expect(catalog.client(forSessionNamed: "shared-client", tokenName: bridge, detected: ["desk", "term"]) == nil) + #expect(catalog.clientIDs(forSessionNamed: "shared-client", tokenName: bridge, detected: []) == ["desk", "term"]) + #expect(catalog.clientIDs(forSessionNamed: "shared-client", tokenName: bridge, detected: ["desk"]) == ["desk"]) + #expect(catalog.iconSlug(forSessionNamed: "shared-client", tokenName: bridge, detected: ["desk"]) == "desk") + #expect(catalog.iconSlug(forSessionNamed: "shared-client", tokenName: bridge, detected: []) == nil) + #expect(catalog.client(forSessionNamed: "editor-client", tokenName: bridge, detected: [])?.id == "editor") + let sessions = [(clientInfoName: "shared-client", tokenName: Optional(bridge)), (clientInfoName: "editor-client", tokenName: Optional(bridge))] + #expect(catalog.ambiguousClientIDs(forSessionsNamed: sessions) == ["desk", "term"]) + } + + @Test("An old setup in a project names the project and offers no Remove; a project folder that is gone is ignored") + func shadowedProject() async throws { + let home = try MCPClientTestHome() + try home.makeExecutable("bin/agent") + try home.makeFolder("work/shop") + func agentConfig(project: String) -> String { + """ + { "projects": { "\(project)": { "mcpServers": { "tablepro": { "command": "/Volumes/Gone/tablepro-mcp" } } } }, + "mcpServers": { "tablepro": { "type": "stdio", "command": "\(home.bridge.path)", "args": [] } } } + """ + } + try home.write(".agent.json", agentConfig(project: home.url("work/gone").path)) + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + #expect(harness.service.row(id: "agent")?.config == .current) + #expect(harness.service.row(id: "agent")?.removeRoute == .cli(binary: "agent")) + + try home.write(".agent.json", agentConfig(project: home.url("work/shop").path)) + await harness.service.refresh() + + let row = try #require(harness.service.row(id: "agent")) + #expect(row.config == .shadowed(project: "~/work/shop")) + #expect(row.removeRoute == nil) + #expect(await harness.service.remove("agent") == .unavailable) + #expect(MCPClientDetailText.configState(row.config, name: row.name)?.contains("~/work/shop") == true) + } + + @Test("Update rewrites how the entry reaches TablePro and keeps the tool list the user narrowed") + func updateKeepsRestrictions() async throws { + let home = try MCPClientTestHome() + try home.write(".editor/mcp.json", """ + { "mcpServers": { "tablepro": { "command": "/Volumes/Gone/TablePro.app/Contents/MacOS/tablepro-mcp", "args": [], "tools": ["list_connections"] } } } + """) + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + #expect(harness.service.row(id: "editor")?.config == .moved) + + #expect(Self.isDone(await harness.service.update("editor"))) + + let text = try #require(home.read(".editor/mcp.json")) + let server = try #require(try Self.servers(in: text)["tablepro"] as? [String: Any]) + #expect(server["command"] as? String == home.bridge.path) + #expect(server["tools"] as? [String] == ["list_connections"]) + #expect(harness.service.row(id: "editor")?.config == .current) + } + + @Test("A setup made with a token or turned off in the client is never replaced by Install or Update") + func userChoicesAreKept() async throws { + let home = try MCPClientTestHome() + let token = #"{ "mcpServers": { "tablepro": { "url": "http://127.0.0.1:23508/mcp", "headers": { "Authorization": "Bearer tp_x" } } } }"# + try home.write(".editor/mcp.json", token) + let turnedOff = "[mcp_servers.tablepro]\ncommand = \"\(home.bridge.path)\"\nargs = []\nenabled = false\n" + try home.write(".shared/config.toml", turnedOff) + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + + let editor = try #require(harness.service.row(id: "editor")) + #expect(editor.config == .usesToken) + #expect(harness.service.presentation(for: editor).action == nil) + #expect(harness.service.presentation(for: editor).status == String(localized: "Set up with a token")) + #expect(await harness.service.update("editor") == .unavailable) + #expect(await harness.service.install("editor") == .unavailable) + #expect(home.read(".editor/mcp.json") == token) + + let term = try #require(harness.service.row(id: "term")) + #expect(term.config == .disabled) + #expect(harness.service.presentation(for: term).action == nil) + #expect(harness.service.presentation(for: term).status == String(localized: "Turned off")) + #expect(await harness.service.update("term") == .unavailable) + #expect(home.read(".shared/config.toml") == turnedOff) + } + + @Test("Update merges into the settings file and keeps the keys the user added, even when the client's command exists") + func updateMergesFile() async throws { + let home = try MCPClientTestHome() + try home.makeExecutable(".local/bin/editor") + try home.write(".editor/mcp.json", """ + { + "mcpServers": { + "tablepro": { + "command": "/Volumes/Gone/TablePro.app/Contents/MacOS/tablepro-mcp", + "args": [], + "autoApprove": ["list_connections"], + "timeout": 30 + } + } + } + """) + try home.write(".shared/config.toml", """ + [mcp_servers.tablepro] + command = "/Volumes/Gone/TablePro.app/Contents/MacOS/tablepro-mcp" + args = [] + enabled_tools = ["list_connections"] + startup_timeout_sec = 30 + + [mcp_servers.tablepro.env] + TOKEN = "x" + + """) + let runner = FakeMCPClientRunner() + let harness = try MCPClientServiceHarness(home: home, runner: runner) + await harness.service.refresh() + #expect(harness.service.row(id: "editor")?.updateRoute == .file) + + #expect(Self.isDone(await harness.service.update("editor"))) + #expect(Self.isDone(await harness.service.update("term"))) + + #expect(runner.calls.isEmpty) + let editorText = try #require(home.read(".editor/mcp.json")) + let server = try #require(try Self.servers(in: editorText)["tablepro"] as? [String: Any]) + #expect(server["command"] as? String == home.bridge.path) + #expect(server["autoApprove"] as? [String] == ["list_connections"]) + #expect(server["timeout"] as? Int == 30) + #expect(home.read(".shared/config.toml") == """ + [mcp_servers.tablepro] + command = "\(home.bridge.path)" + args = [] + enabled_tools = ["list_connections"] + startup_timeout_sec = 30 + + [mcp_servers.tablepro.env] + TOKEN = "x" + + """) + #expect(harness.service.row(id: "editor")?.config == .current) + #expect(harness.service.row(id: "term")?.config == .current) + } + + @Test("A write the system refuses names the file, and keeps the system's reason as output") + func refusedWriteIsReadable() async throws { + let home = try MCPClientTestHome() + try home.write(".editor/mcp.json", #"{ "mcpServers": {} }"#) + let folder = home.url(".editor").path + try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: folder) + defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: home.url(".editor").path) } + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + + let outcome = await harness.service.install("editor") + + guard case let .failed(message, output) = outcome else { + Issue.record("Expected a failure, got \(outcome)") + return + } + #expect(message == String(format: String(localized: "TablePro could not write %@."), "mcp.json")) + #expect(output?.contains("NSCocoaErrorDomain") == true) + #expect(MCPClientSetupService.message(for: MCPConfigWriteError.io("x"), fileName: "mcp.json") == message) + } + + @Test("A session from TablePro's own Claude Agent lights no client") + func agentSessionIsNotAClient() async throws { + let home = try MCPClientTestHome() + let harness = try MCPClientServiceHarness(home: home) + await harness.service.refresh() + + harness.sessions.send([]) + harness.sessions.send([ + MCPClientSessionSighting(id: "turn", clientInfoName: "agent-cli", tokenName: MCPTokenStore.claudeAgentTokenName) + ]) + + #expect(harness.service.connection(for: "agent") == .notConnected) + #expect(harness.announcements.messages.isEmpty) + } + + @Test("A removal the client reports as already gone counts as done") + func missingEntryReadsAsRemoved() { + #expect(MCPClientSetupService.reportsMissingEntry("No MCP server named tablepro found in user config")) + #expect(MCPClientSetupService.reportsMissingEntry("Error: server \"tablepro\" not found")) + #expect(!MCPClientSetupService.reportsMissingEntry("EACCES: permission denied")) + } + + private static func isDone(_ outcome: MCPClientActionOutcome) -> Bool { + if case .done = outcome { return true } + return false + } + + private static func servers(in text: String) throws -> [String: Any] { + let object = try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] + return try #require(object?["mcpServers"] as? [String: Any]) + } +} diff --git a/apple/TableProTests/Core/MCP/Clients/MCPHTTPClientSetupTests.swift b/apple/TableProTests/Core/MCP/Clients/MCPHTTPClientSetupTests.swift new file mode 100644 index 0000000000..bb5f572a14 --- /dev/null +++ b/apple/TableProTests/Core/MCP/Clients/MCPHTTPClientSetupTests.swift @@ -0,0 +1,42 @@ +import Foundation +@testable import TablePro +import TableProMCPClients +import Testing + +struct MCPHTTPClientSetupTests { + private let token = "tp_secret0123456789" + private let masked = "tp_secre\u{2022}\u{2022}\u{2022}\u{2022}" + + private func setup() throws -> MCPHTTPClientSetup { + MCPHTTPClientSetup( + catalog: try MCPClientSetupFixture.catalog(), + context: MCPClientSetupContext(home: "/Users/me", environment: [:], bridgePath: "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp"), + port: 23_508 + ) + } + + @Test("The token sheet lists the HTTP clients this Mac runs, then Other Client") + func choices() throws { + #expect(try setup().choices.map { $0.id } == ["editor", "agent", MCPHTTPClientSetup.otherClientID]) + } + + @Test("The snippet on screen carries the masked token and the copied one the real token") + func maskedSnippet() throws { + let setup = try setup() + let shown = try #require(setup.render(clientID: "editor", token: masked)) + let copied = try #require(setup.render(clientID: "editor", token: token)) + + #expect(shown.snippet?.contains(token) == false) + #expect(shown.snippet?.contains("http://127.0.0.1:23508/mcp") == true) + #expect(copied.snippet?.contains("Bearer \(token)") == true) + #expect(copied.displayConfigPath == "~/.editor/mcp.json") + } + + @Test("A client whose settings file only it writes gets its command, not a snippet") + func commandForUnwritableFile() throws { + let rendered = try #require(try setup().render(clientID: "agent", token: token)) + #expect(rendered.snippet == nil) + #expect(rendered.commandLine?.contains("--header") == true) + #expect(rendered.commandLine?.contains("Bearer \(token)") == true) + } +} diff --git a/apple/TableProTests/Core/MCP/Identity/MCPIdentityLedgerTests.swift b/apple/TableProTests/Core/MCP/Identity/MCPIdentityLedgerTests.swift index ebedf0ec72..22ba168028 100644 --- a/apple/TableProTests/Core/MCP/Identity/MCPIdentityLedgerTests.swift +++ b/apple/TableProTests/Core/MCP/Identity/MCPIdentityLedgerTests.swift @@ -119,15 +119,30 @@ struct MCPIdentityLedgerTests { #expect(await ledger.isApproved(principal: second, connectionId: connectionId) == false) } - private func meta(clientName: String, version: String) -> MCPRequestMeta { + private func meta(clientName: String, version: String, title: String? = nil) -> MCPRequestMeta { MCPRequestMeta( protocolVersion: .latest, - clientInfo: MCPImplementation(name: clientName, version: version), + clientInfo: MCPImplementation(name: clientName, title: title, version: version), clientCapabilities: .none, progressToken: nil ) } + private func bridgePrincipal(tokenId: UUID, fingerprint: String) -> MCPPrincipal { + MCPPrincipal( + tokenFingerprint: fingerprint, + tokenId: tokenId, + scopes: MCPScope.readWriteSet, + connectionAccess: .all, + metadata: MCPPrincipalMetadata( + label: MCPTokenStore.stdioBridgeTokenName, + issuedAt: .distantPast, + expiresAt: nil, + isBridgeCredential: true + ) + ) + } + @Test("Activity is folded onto one entry per client identity") func activityFoldsRepeatRequests() async { let ledger = MCPClientActivityLedger(idleTimeout: .seconds(300)) @@ -169,7 +184,7 @@ struct MCPIdentityLedgerTests { #expect(await ledger.count(now: start.addingTimeInterval(61)) == 0) } - @Test("Two tokens on one machine are two clients") + @Test("Two HTTP tokens on one machine are two clients") func distinctTokensAreDistinctEntries() async { let ledger = MCPClientActivityLedger() let start = Date(timeIntervalSince1970: 1_700_000_000) @@ -191,6 +206,77 @@ struct MCPIdentityLedgerTests { #expect(await ledger.snapshot(now: start).count == 2) } + @Test("A stdio client keeps one row, and its connected time, across a bridge credential rotation") + func bridgeClientSurvivesRotation() async { + let ledger = MCPClientActivityLedger() + let start = Date(timeIntervalSince1970: 1_700_000_000) + let requestMeta = meta(clientName: "cursor-vscode", version: "1.4") + let rotated = bridgePrincipal(tokenId: UUID(), fingerprint: "b") + + await ledger.record( + meta: requestMeta, + principal: bridgePrincipal(tokenId: UUID(), fingerprint: "a"), + address: .localSocket, + at: start + ) + await ledger.record(meta: requestMeta, principal: rotated, address: .localSocket, at: start.addingTimeInterval(60)) + + let entries = await ledger.snapshot(now: start.addingTimeInterval(60)) + #expect(entries.count == 1) + #expect(entries.first?.transport == .stdioBridge) + #expect(entries.first?.firstSeenAt == start) + #expect(entries.first?.tokenId == rotated.tokenId) + } + + @Test("Two stdio clients sharing the bridge credential are two clients") + func bridgeClientsAreToldApartByClientInfo() async { + let ledger = MCPClientActivityLedger() + let start = Date(timeIntervalSince1970: 1_700_000_000) + let shared = bridgePrincipal(tokenId: UUID(), fingerprint: "a") + + await ledger.record(meta: meta(clientName: "claude-ai", version: "1"), principal: shared, address: .localSocket, at: start) + await ledger.record(meta: meta(clientName: "Zed", version: "1"), principal: shared, address: .localSocket, at: start) + + let entries = await ledger.snapshot(now: start) + #expect(Set(entries.map(\.clientName)) == ["claude-ai", "Zed"]) + #expect(Set(entries.map(\.id)).count == 2) + } + + @Test("A client's own name is kept beside the title it shows under") + func clientInfoNameIsKept() async { + let ledger = MCPClientActivityLedger() + let start = Date(timeIntervalSince1970: 1_700_000_000) + + await ledger.record( + meta: meta(clientName: "tablepro-cli", version: "1", title: "Command Line"), + principal: principal(tokenId: UUID()), + address: .localSocket, + at: start + ) + + let entry = await ledger.snapshot(now: start).first + #expect(entry?.clientName == "Command Line") + #expect(entry?.clientInfoName == "tablepro-cli") + #expect(entry?.transport == .http) + } + + @Test("The app's socket is listed under a readable address, while the audit log keeps its fixed value") + func localSocketAddressIsReadable() async { + let ledger = MCPClientActivityLedger() + let start = Date(timeIntervalSince1970: 1_700_000_000) + + await ledger.record( + meta: meta(clientName: "Claude", version: "1"), + principal: principal(tokenId: UUID()), + address: .localSocket, + at: start + ) + + #expect(await ledger.snapshot(now: start).first?.address == "Local socket") + #expect(MCPClientAddress.localSocket.displayValue == "local socket") + #expect(MCPClientAddress.loopback.localizedDisplayValue == "127.0.0.1") + } + @Test("A revoked token's activity is forgotten with it") func forgettingATokenDropsItsActivity() async { let ledger = MCPClientActivityLedger() diff --git a/apple/TableProTests/Core/MCP/Integration/MCPBridgeIntegrationTests.swift b/apple/TableProTests/Core/MCP/Integration/MCPBridgeIntegrationTests.swift index e5d9c2fabb..f9ecb07118 100644 --- a/apple/TableProTests/Core/MCP/Integration/MCPBridgeIntegrationTests.swift +++ b/apple/TableProTests/Core/MCP/Integration/MCPBridgeIntegrationTests.swift @@ -156,7 +156,7 @@ final class MCPBridgeIntegrationTests: XCTestCase { ) } - func testAModernHostRequestIsForwardedByteForByte() async throws { + func testAModernHostRequestGainsOnlyTheBridgeInstance() async throws { let bridge = try await startBridge() defer { bridge.shutdown() } await upstream.respondWithJson(try Self.successBody(id: .number(6))) @@ -172,7 +172,11 @@ final class MCPBridgeIntegrationTests: XCTestCase { let recordedForwarded = await upstream.requests.first let forwarded = try XCTUnwrap(recordedForwarded) - XCTAssertEqual(forwarded.body, Data(line.utf8), "A modern host already carries its own metadata") + XCTAssertEqual( + forwarded.body, + try Self.stampedWithInstance(line, forwarded: forwarded.body), + "A modern host's message gains only the bridge instance" + ) } func testStampingNeverRewritesTheNumbersInAMessage() async throws { @@ -198,7 +202,7 @@ final class MCPBridgeIntegrationTests: XCTestCase { XCTAssertTrue(text.contains(MCPMetaKeys.protocolVersion)) } - func testAModernMessageWithBigNumbersIsForwardedUntouched() async throws { + func testAModernMessageWithBigNumbersGainsOnlyTheBridgeInstance() async throws { let bridge = try await startBridge() defer { bridge.shutdown() } await upstream.respondWithJson(try Self.successBody(id: .number(8))) @@ -214,7 +218,33 @@ final class MCPBridgeIntegrationTests: XCTestCase { let recordedForwarded = await upstream.requests.first let forwarded = try XCTUnwrap(recordedForwarded) - XCTAssertEqual(forwarded.body, Data(line.utf8)) + XCTAssertEqual(forwarded.body, try Self.stampedWithInstance(line, forwarded: forwarded.body)) + } + + func testEveryForwardedRequestCarriesItsOwnBridgesInstance() async throws { + let first = try await startBridge() + defer { first.shutdown() } + let second = try await startBridge() + defer { second.shutdown() } + await upstream.respondWithJson(try Self.successBody(id: .number(17))) + + try first.write(#"{"jsonrpc":"2.0","id":17,"method":"tools/list","params":{}}"#) + _ = try await first.nextMessage() + try first.write(#"{"jsonrpc":"2.0","id":17,"method":"resources/list"}"#) + _ = try await first.nextMessage() + try second.write(#"{"jsonrpc":"2.0","id":17,"method":"tools/list","params":{}}"#) + _ = try await second.nextMessage() + + let forwarded = await upstream.requests + let instances = try forwarded.map { request in + let body = try JSONDecoder().decode(JsonValue.self, from: request.body) + return try XCTUnwrap(body["params"]?["_meta"]?[MCPMetaKeys.bridgeInstance]?.stringValue) + } + XCTAssertEqual(instances.count, 3) + guard instances.count == 3 else { return } + XCTAssertFalse(instances[0].isEmpty) + XCTAssertEqual(instances[0], instances[1], "One bridge process is one session") + XCTAssertNotEqual(instances[0], instances[2], "Two bridge processes are two sessions") } func testAToolCallCarriesItsNameInTheHeader() async throws { @@ -348,6 +378,17 @@ final class MCPBridgeIntegrationTests: XCTestCase { return BridgeHarness(upstream: transport, discovery: BridgeIntegrationFixtures.discovery) } + // A modern message is forwarded as sent, plus the one reserved key that names the bridge process. + private static func stampedWithInstance(_ line: String, forwarded: Data) throws -> Data { + let body = try JSONDecoder().decode(JsonValue.self, from: forwarded) + let instance = try XCTUnwrap(body["params"]?["_meta"]?[MCPMetaKeys.bridgeInstance]?.stringValue) + let stamped = line.replacingOccurrences( + of: #""_meta":{"#, + with: #""_meta":{"\#(MCPMetaKeys.bridgeInstance)":"\#(instance)","# + ) + return Data(stamped.utf8) + } + private static func successBody(id: JsonRpcId) throws -> Data { try JsonRpcCodec.encode( .successResponse(JsonRpcSuccessResponse(id: id, result: .object(["ok": .bool(true)]))) diff --git a/apple/TableProTests/Core/MCP/Lifecycle/MCPServerManagerClientsTests.swift b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerManagerClientsTests.swift new file mode 100644 index 0000000000..41e543c3d7 --- /dev/null +++ b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerManagerClientsTests.swift @@ -0,0 +1,176 @@ +import Combine +import Foundation +import TableProMCP +import TableProTestSupport +import Testing + +@testable import TablePro + +@MainActor +@Suite(.serialized) +struct MCPServerManagerClientsTests { + private struct Running { + let manager: MCPServerManager + let composition: MCPServerComposition + let bridgeToken: String + } + + private let directory: URL + + init() throws { + // Short, so the socket fits in sun_path inside the folder itself. + directory = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) + .appendingPathComponent("mcp-\(UUID().uuidString.prefix(8))", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path) + } + + private func withRunningServer(_ body: (Running) async throws -> Void) async throws { + let manager = MCPServerManager(handshake: MCPHandshakeFile(directory: directory), isEnabled: { true }) + try await manager.start(port: 0) + do { + try await waitUntil { + await MainActor.run { + if case .failed = manager.state { return true } + return manager.isRunning + } + } + try #require(manager.isRunning, "The MCP server did not start: \(manager.state)") + let composition = try #require(manager.composition) + let data = try Data(contentsOf: MCPHandshakeLocation.file(in: directory)) + let handshake = try MCPHandshakeCoding.decoder().decode(MCPHandshakePayload.self, from: data) + try await body(Running(manager: manager, composition: composition, bridgeToken: handshake.token)) + } catch { + await manager.stop() + throw error + } + await manager.stop() + } + + private func principal(presenting token: String, from address: MCPClientAddress, to running: Running) async throws -> MCPPrincipal { + let decision = await running.composition.authenticator.authenticate( + authorizationHeader: "Bearer \(token)", + clientAddress: address + ) + guard case .allow(let principal) = decision else { + Issue.record("Expected the token to be accepted, got \(decision)") + throw CancellationError() + } + return principal + } + + private func record(_ clientName: String, as principal: MCPPrincipal, from address: MCPClientAddress, in running: Running) async { + let meta = MCPRequestMeta( + protocolVersion: .latest, + clientInfo: MCPImplementation(name: clientName, version: "1"), + clientCapabilities: .none, + progressToken: nil + ) + await running.composition.activityLedger.record(meta: meta, principal: principal, address: address, at: Date()) + } + + @Test("Disconnect on a stdio client forgets that client only and leaves the shared bridge credential working") + func stdioDisconnectKeepsTheBridgeCredential() async throws { + try await withRunningServer { running in + let bridge = try await principal(presenting: running.bridgeToken, from: .localSocket, to: running) + await record("claude-ai", as: bridge, from: .localSocket, in: running) + await record("cursor-vscode", as: bridge, from: .localSocket, in: running) + await running.manager.refreshClients() + + let clients = running.manager.connectedClients + #expect(clients.count == 2) + #expect(clients.allSatisfy { $0.transport == .stdioBridge }) + let claude = try #require(clients.first { $0.clientName == "claude-ai" }) + + #expect(await running.manager.disconnectClient(claude.id)) + + #expect(running.manager.connectedClients.map { $0.clientName } == ["cursor-vscode"]) + #expect(await running.manager.tokenStore?.validate(bearerToken: running.bridgeToken) != nil) + _ = try await principal(presenting: running.bridgeToken, from: .localSocket, to: running) + } + } + + @Test("Disconnect on a client with its own token revokes that token") + func tokenDisconnectRevokesTheToken() async throws { + try await withRunningServer { running in + let store = try #require(running.manager.tokenStore) + let minted = try await store.generate( + name: "Raycast", + permissions: .readOnly, + connectionAccess: .all, + expiresAt: nil, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + let paired = try await principal(presenting: minted.plaintext, from: .loopback, to: running) + await record("raycast", as: paired, from: .loopback, in: running) + await running.manager.refreshClients() + let row = try #require(running.manager.connectedClients.first) + #expect(row.transport == .http) + + #expect(await running.manager.disconnectClient(row.id)) + + #expect(running.manager.connectedClients.isEmpty) + #expect(await store.validate(bearerToken: minted.plaintext) == nil) + #expect(await running.manager.tokenStore?.validate(bearerToken: running.bridgeToken) != nil) + await store.delete(tokenId: minted.token.id) + } + } + + @Test("A refresh that finds nothing new does not publish the client list again") + func unchangedClientsAreNotRepublished() async throws { + try await withRunningServer { running in + let counter = PublishCounter() + let subscription = running.manager.$connectedClients.dropFirst().sink { _ in counter.count += 1 } + defer { subscription.cancel() } + + let bridge = try await principal(presenting: running.bridgeToken, from: .localSocket, to: running) + await record("Zed", as: bridge, from: .localSocket, in: running) + await running.manager.refreshClients() + let afterNewClient = counter.count + #expect(afterNewClient >= 1) + + await running.manager.refreshClients() + await running.manager.refreshClients() + + #expect(counter.count == afterNewClient) + } + } + + @Test("Revoking with no server running reports that nothing was revoked") + func revokeWithoutAStoreFails() async { + let manager = MCPServerManager(handshake: MCPHandshakeFile(directory: directory), isEnabled: { false }) + + #expect(await manager.revokeToken(id: UUID()) == false) + } + + @Test("The window names TablePro's own clients and tokens, not their raw ids") + func ownClientsReadAsTablePro() { + #expect(IntegrationsFormatting.displayTokenName(MCPTokenStore.claudeAgentTokenName) == AIProviderType.claudeAgent.displayName) + #expect(IntegrationsFormatting.displayTokenName("Raycast") == "Raycast") + + let command = Self.snapshot(clientName: CLIClientIdentity.title, clientInfoName: CLIClientIdentity.name) + #expect(IntegrationsFormatting.displayClientName(command) == String(localized: "tablepro command")) + let cursor = Self.snapshot(clientName: "Cursor", clientInfoName: "cursor-vscode") + #expect(IntegrationsFormatting.displayClientName(cursor) == "Cursor") + } + + private static func snapshot(clientName: String, clientInfoName: String) -> MCPServerManager.SessionSnapshot { + MCPServerManager.SessionSnapshot( + id: clientInfoName, + clientName: clientName, + clientInfoName: clientInfoName, + clientVersion: "1", + connectedSince: .distantPast, + lastActivityAt: .distantPast, + tokenName: nil, + remoteAddress: nil, + transport: .http + ) + } +} + +private final class PublishCounter { + var count = 0 +} diff --git a/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift index 59ce1fdab2..ad3d22fd55 100644 --- a/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift +++ b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift @@ -108,6 +108,53 @@ struct MCPServerOffContractTests { } } +@MainActor +struct MCPServerFailedStartTests { + private let root: URL + + init() throws { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("mcp-fail-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + @Test("A start that fails while MCP is on leaves a refusal that says so, for the bridge that asked") + func failedStartWritesARefusal() async throws { + // Too long for a socket path, so the server falls back to the temporary folder, which is a file here. + let directory = root.appendingPathComponent(String(repeating: "d", count: 110), isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let notAFolder = root.appendingPathComponent("tmp-file", isDirectory: false) + try Data().write(to: notAFolder) + let manager = MCPServerManager( + handshake: MCPHandshakeFile(directory: directory, temporaryDirectory: notAFolder), + isEnabled: { true } + ) + let startedAt = Date() + + try await manager.start(port: 0) + + #expect(manager.state == .failed(.socketFolderUnusable)) + #expect(manager.tokenStore == nil) + let data = try Data(contentsOf: MCPHandshakeLocation.refusalFile(in: directory)) + let refusal = try MCPHandshakeCoding.decoder().decode(MCPStartRefusal.self, from: data) + #expect(refusal.reason == .failedToStart) + #expect(refusal.answers(launchRequestedAt: startedAt)) + await manager.stop() + } + + @Test("A refusal while MCP is off still reads as turned off") + func turnedOffRefusalKeepsItsReason() async throws { + let manager = MCPServerManager(handshake: MCPHandshakeFile(directory: root), isEnabled: { false }) + + await #expect(throws: MCPServerStartError.turnedOff) { + try await manager.start(port: 0) + } + + let data = try Data(contentsOf: MCPHandshakeLocation.refusalFile(in: root)) + #expect(try MCPHandshakeCoding.decoder().decode(MCPStartRefusal.self, from: data).reason == .turnedOff) + } +} + struct MCPBridgeRefusalTests { private let directory: URL diff --git a/apple/TableProTests/Core/MCP/MCPAuditChainTests.swift b/apple/TableProTests/Core/MCP/MCPAuditChainTests.swift index 1ca36bbb94..7848cb76dc 100644 --- a/apple/TableProTests/Core/MCP/MCPAuditChainTests.swift +++ b/apple/TableProTests/Core/MCP/MCPAuditChainTests.swift @@ -63,6 +63,72 @@ struct MCPAuditChainTests { ) } + @Test("A row without a client keeps the digest builds before the client column wrote") + func rowWithoutAClientKeepsItsDigest() throws { + let row = AuditEntry( + id: try #require(UUID(uuidString: "00000000-0000-0000-0000-0000000000AA")), + timestamp: Date(timeIntervalSince1970: 1_700_000_000), + category: .tool, + tokenId: UUID(uuidString: "00000000-0000-0000-0000-000000000001"), + tokenName: "client", + connectionId: nil, + action: "tool.run", + outcome: AuditOutcome.success, + details: "sqlDigest=abc" + ) + + #expect( + MCPAuditChainLink.digest(entry: row, sequence: 0, previousHash: MCPAuditChainLink.genesisHash) + == "7ad26117f02b46c632d1367b24359f6a8ff1fc84152c20a2ca825881623c8e99" + ) + } + + @Test("The digest covers the client a row names") + func digestCoversTheClient() { + let base = entry(action: "tool.run") + let named = AuditEntry( + id: base.id, + timestamp: base.timestamp, + category: base.category, + tokenId: base.tokenId, + tokenName: base.tokenName, + connectionId: base.connectionId, + action: base.action, + outcome: base.outcome, + details: base.details, + clientName: "Cursor" + ) + let renamed = AuditEntry( + id: base.id, + timestamp: base.timestamp, + category: base.category, + tokenId: base.tokenId, + tokenName: base.tokenName, + connectionId: base.connectionId, + action: base.action, + outcome: base.outcome, + details: base.details, + clientName: "Zed" + ) + + let previous = MCPAuditChainLink.genesisHash + let digests = Set([base, named, renamed].map { + MCPAuditChainLink.digest(entry: $0, sequence: 0, previousHash: previous) + }) + #expect(digests.count == 3) + } + + @Test("A client renamed behind the app's back is detected") + func editedClientIsDetected() async { + let (storage, path) = Self.makeStorage() + await storage.addEntry(AuditEntry(category: .tool, action: "tool.first", outcome: AuditOutcome.success, clientName: "Cursor")) + await storage.addEntry(AuditEntry(category: .tool, action: "tool.second", outcome: AuditOutcome.success, clientName: "Zed")) + + #expect(Self.execute("UPDATE audit_entries SET client_name = 'Cursor' WHERE sequence = 1;", at: path)) + + #expect(await storage.verify() == .broken(atSequence: 1)) + } + @Test("Reordering two entries breaks the chain") func reorderingBreaksTheChain() { let first = entry(action: "tool.first") diff --git a/apple/TableProTests/Core/MCP/MCPAuditLogStorageTests.swift b/apple/TableProTests/Core/MCP/MCPAuditLogStorageTests.swift index 1bdadb090d..2380830626 100644 --- a/apple/TableProTests/Core/MCP/MCPAuditLogStorageTests.swift +++ b/apple/TableProTests/Core/MCP/MCPAuditLogStorageTests.swift @@ -1,4 +1,5 @@ import Foundation +import SQLite3 import TableProMCP import TableProPluginKit import Testing @@ -310,6 +311,161 @@ struct MCPAuditLogStorageTests { #expect(names.allSatisfy { !$0.hasPrefix("mcp-audit-test_") }) } + @Test("A row keeps the client that caused it, and the log filters by that client") + func filterByClient() async { + let storage = makeStorage() + await storage.addEntry(AuditEntry(category: .tool, action: "tool.a", outcome: AuditOutcome.success, clientName: "Cursor")) + await storage.addEntry(AuditEntry(category: .tool, action: "tool.b", outcome: AuditOutcome.success, clientName: "Zed")) + await storage.addEntry(AuditEntry(category: .admin, action: "server.started", outcome: AuditOutcome.success)) + + let cursor = await storage.query(clientName: "Cursor") + #expect(cursor.map { $0.action } == ["tool.a"]) + #expect(cursor.first?.clientName == "Cursor") + #expect(await storage.query(category: .admin).first?.clientName == nil) + #expect(await storage.clientNames() == ["Cursor", "Zed"]) + #expect(await storage.verify() == .intact(count: 3)) + } + + @Test("Every bridge credential reads as one token, whichever rotation wrote the row") + func filterByTokenName() async { + let storage = makeStorage() + await storage.addEntry(makeEntry(tokenId: UUID(), tokenName: MCPTokenStore.stdioBridgeTokenName, action: "tool.before")) + await storage.addEntry(makeEntry(tokenId: UUID(), tokenName: MCPTokenStore.stdioBridgeTokenName, action: "tool.after")) + await storage.addEntry(makeEntry(tokenName: "Raycast", action: "tool.raycast")) + + let bridge = await storage.query(tokenName: MCPTokenStore.stdioBridgeTokenName) + #expect(Set(bridge.map { $0.action }) == ["tool.before", "tool.after"]) + } + + @Test("A log written before the client column opens with no client on its rows and keeps its chain") + func logWithoutTheClientColumnMigrates() async throws { + let directory = Self.makeDirectory() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let path = directory.appendingPathComponent(MCPAuditLogStorage.databaseFileName).path + // Whole seconds, so the timestamp reads back from SQL text to the same value the digest used. + let old = makeEntry(tokenName: "Raycast", timestamp: Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded(.down)), action: "tool.beforeUpgrade") + let hash = MCPAuditChainLink.digest(entry: old, sequence: 0, previousHash: MCPAuditChainLink.genesisHash) + let created = Self.execute([ + """ + CREATE TABLE audit_entries ( + id TEXT PRIMARY KEY, timestamp REAL NOT NULL, category TEXT NOT NULL, token_id TEXT, + token_name TEXT, connection_id TEXT, action TEXT NOT NULL, outcome TEXT NOT NULL, details TEXT, + sequence INTEGER, previous_hash TEXT, entry_hash TEXT + ); + """, + """ + INSERT INTO audit_entries VALUES ('\(old.id.uuidString)', \(old.timestamp.timeIntervalSince1970), 'tool', + '\(old.tokenId?.uuidString ?? "")', 'Raycast', NULL, 'tool.beforeUpgrade', 'success', NULL, + 0, '\(MCPAuditChainLink.genesisHash)', '\(hash)'); + """ + ], at: path) + #expect(created) + + let storage = MCPAuditLogStorage(directory: directory) + let migrated = await storage.query() + #expect(migrated.count == 1) + #expect(migrated.first?.clientName == nil) + #expect(migrated.first?.tokenName == "Raycast") + #expect(await storage.verify() == .intact(count: 1)) + + #expect(await storage.addEntry(AuditEntry(category: .tool, action: "tool.afterUpgrade", outcome: AuditOutcome.success, clientName: "Cursor"))) + #expect(await storage.verify() == .intact(count: 2)) + #expect(await storage.query(clientName: "Cursor").map { $0.action } == ["tool.afterUpgrade"]) + + // What a build without the column runs: it names its columns, so the log stays its own. + #expect(Self.execute([ + "SELECT id, timestamp, category, token_id, token_name, connection_id, action, outcome, details FROM audit_entries;", + """ + INSERT INTO audit_entries + (id, timestamp, category, token_id, token_name, connection_id, action, outcome, details, + sequence, previous_hash, entry_hash) + VALUES ('\(UUID().uuidString)', 0, 'tool', NULL, NULL, NULL, 'tool.olderBuild', 'success', NULL, 99, '', ''); + """ + ], at: path)) + } + + @Test("A tool call names the client that made it, never its token") + func toolCallCarriesTheClient() async throws { + let tokenId = UUID() + + MCPAuditLogger.logToolCalled( + principal: makePrincipal(tokenId: tokenId, label: MCPTokenStore.stdioBridgeTokenName), + client: "Cursor", + toolName: "list_tables", + outcome: .success + ) + await MCPAuditLogger.flush() + + let row = try #require(await MCPAuditLogStorage.shared.query(tokenId: tokenId).first) + #expect(row.clientName == "Cursor") + #expect(row.tokenName == MCPTokenStore.stdioBridgeTokenName) + } + + @Test("The client is named as Connected Clients names it, before any catalog lookup") + func clientNameFromClientInfo() { + func meta(_ info: MCPImplementation?) -> MCPRequestMeta { + MCPRequestMeta(protocolVersion: .latest, clientInfo: info, clientCapabilities: .none, progressToken: nil) + } + + #expect(MCPAuditLogger.clientName(for: meta(MCPImplementation(name: "claude-ai", title: "Claude", version: "1"))) == "Claude") + #expect(MCPAuditLogger.clientName(for: meta(MCPImplementation(name: "cursor-vscode", title: " ", version: "1"))) == "cursor-vscode") + #expect(MCPAuditLogger.clientName(for: meta(MCPImplementation(name: CLIClientIdentity.name, title: CLIClientIdentity.title, version: "1"))) + == CLIClientIdentity.pairingName) + #expect(MCPAuditLogger.clientName(for: meta(nil)) == nil) + } + + @Test("The Activity Log finds a row by its client and exports the client beside the token") + @MainActor + func activityLogSearchesAndExportsTheClient() throws { + let row = AuditEntry( + timestamp: Date(timeIntervalSince1970: 1_700_000_000), + category: .tool, + tokenName: MCPTokenStore.stdioBridgeTokenName, + action: "tool.list_tables", + outcome: AuditOutcome.success, + clientName: "Cursor" + ) + let noConnection: (UUID?) -> String? = { _ in nil } + + #expect(IntegrationsActivityLogPane.searchMatches(row, needle: "cursor", connectionName: noConnection)) + #expect(!IntegrationsActivityLogPane.searchMatches(row, needle: "zed", connectionName: noConnection)) + + let lines = IntegrationsActivityLogPane.csvString(for: [row], connectionName: noConnection) + .split(separator: "\n") + .map { $0.split(separator: ",", omittingEmptySubsequences: false).map(String.init) } + let header = try #require(lines.first) + let values = try #require(lines.last) + let client = try #require(header.firstIndex(of: "Client")) + let token = try #require(header.firstIndex(of: "Token")) + #expect(values[client] == "Cursor") + #expect(values[token] == MCPTokenStore.stdioBridgeTokenName) + } + + @Test("A client name that reads as a spreadsheet formula is exported as text") + @MainActor + func exportedClientNameNeverRunsAsAFormula() throws { + let row = AuditEntry( + timestamp: Date(timeIntervalSince1970: 1_700_000_000), + category: .tool, + tokenName: MCPTokenStore.stdioBridgeTokenName, + action: "tool.list_tables", + outcome: AuditOutcome.success, + clientName: "=HYPERLINK(\"https://example.com\")" + ) + let csv = IntegrationsActivityLogPane.csvString(for: [row], connectionName: { _ in nil }) + let values = try #require(csv.split(separator: "\n").last) + + #expect(!values.contains(",=HYPERLINK")) + #expect(values.contains("'=HYPERLINK")) + } + + private static func execute(_ statements: [String], at path: String) -> Bool { + var db: OpaquePointer? + guard sqlite3_open(path, &db) == SQLITE_OK else { return false } + defer { sqlite3_close(db) } + return statements.allSatisfy { sqlite3_exec(db, $0, nil, nil, nil) == SQLITE_OK } + } + private static func permissions(ofItemAt path: String) -> Int? { let attributes = try? FileManager.default.attributesOfItem(atPath: path) return (attributes?[.posixPermissions] as? NSNumber)?.intValue diff --git a/apple/TableProTests/Core/MCP/MCPPairingServiceTests.swift b/apple/TableProTests/Core/MCP/MCPPairingServiceTests.swift index ce15993444..f486e1e671 100644 --- a/apple/TableProTests/Core/MCP/MCPPairingServiceTests.swift +++ b/apple/TableProTests/Core/MCP/MCPPairingServiceTests.swift @@ -1,12 +1,4 @@ -// -// MCPPairingServiceTests.swift -// TableProTests -// -// A pairing code is a bearer credential for the whole grant, so each code allows exactly one -// attempt: a verifier that does not match burns the code instead of leaving it alive for the rest -// of the five-minute window, which is what turned PKCE into an offline guessing game. The record -// carries the token id so a caller that fails the exchange can delete the token it was holding. -// +// A pairing code is a bearer credential for the whole grant, so each code allows exactly one attempt. import CryptoKit import Foundation @@ -17,6 +9,14 @@ import Testing @testable import TablePro +private struct RefusingCredentialStore: MCPTokenCredentialStoring { + func read() -> MCPTokenBlob { .found(Data("[]".utf8)) } + + func write(_ data: Data) -> Bool { false } + + func delete() {} +} + struct MCPPairingServiceTests { private func challenge(for verifier: String) -> String { PairingExchangeStore.sha256Base64Url(of: verifier) @@ -200,6 +200,42 @@ struct MCPPairingServiceTests { #expect(await store.contains(code: "code-overflow") == false) } + @Test("An approved pairing whose token the Keychain refused fails in words and leaves no code behind") + @MainActor + func unsavedTokenFailsThePairing() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("mcp-pairing-\(UUID().uuidString)", isDirectory: true) + let store = PairingExchangeStore() + let service = MCPPairingService( + store: store, + serverManager: MCPServerManager(handshake: MCPHandshakeFile(directory: directory), isEnabled: { false }) + ) + let redirect = try #require(URL(string: "http://127.0.0.1:7391/callback")) + let request = PairingRequest( + clientName: "Launcher", + challenge: challenge(for: makeVerifier()), + redirectURL: redirect, + requestedScopes: nil, + requestedConnectionIds: nil, + state: "s1", + responseMode: .query + ) + let target = try PairingRedirectValidator.validate(redirect) + let tokens = MCPTokenStore(credentialStore: RefusingCredentialStore()) + + await #expect(throws: MCPPairingError.tokenNotSaved) { + _ = try await service.issueCode( + for: request, + target: target, + approval: PairingApproval(grantedPermissions: .readOnly, allowedConnectionIds: nil, expiresAt: nil, extraScopes: []), + tokenStore: tokens + ) + } + #expect(await store.count() == 0) + #expect(await tokens.list().isEmpty) + #expect(MCPPairingError.tokenNotSaved.localizedDescription.contains("Keychain")) + } + @Test("The exchange window is the five minutes the client is told about") func exchangeWindowIsFiveMinutes() { #expect(PairingExchangeStore.exchangeWindow == 300) diff --git a/apple/TableProTests/Core/MCP/MCPSettingsTests.swift b/apple/TableProTests/Core/MCP/MCPSettingsTests.swift index 3ccb9899fd..826a3409df 100644 --- a/apple/TableProTests/Core/MCP/MCPSettingsTests.swift +++ b/apple/TableProTests/Core/MCP/MCPSettingsTests.swift @@ -106,6 +106,19 @@ struct MCPSettingsTests { #expect(decoded.port == 5_000) } + @Test("A stored port below 1024 falls back to the default, as on Linux") + func decodesAPrivilegedPort() throws { + let decoded = try JSONDecoder().decode(MCPSettings.self, from: Data(#"{"port": 80}"#.utf8)) + #expect(decoded.port == 23_508) + } + + @Test("A port written outside 1024 to 65535 is clamped into it") + func validatedPortClamps() { + #expect(MCPSettings(port: 80).validatedPort == 1_024) + #expect(MCPSettings(port: 70_000).validatedPort == 65_535) + #expect(MCPSettings(port: 23_508).validatedPort == 23_508) + } + @Test("Row limits decode to the documented defaults") func decodesRowLimitDefaults() throws { let decoded = try JSONDecoder().decode(MCPSettings.self, from: Data("{}".utf8)) diff --git a/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift b/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift index 863bec24e8..1ed522539d 100644 --- a/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift +++ b/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift @@ -1,13 +1,8 @@ -// -// MCPTokenStoreTests.swift -// TableProTests -// // Minting a token is a grant, so the store makes the caller state the grant: `generate` takes the // connection scope and the expiry with no defaults, because the defaults it used to carry handed // every caller that forgot them a token over every connection that never expired. Two tokens may // share a name; pairing no longer revokes an existing token because a new client claimed the same // one, which let any caller name an installed client and take its access away. -// import Foundation import TableProMCP @@ -76,10 +71,15 @@ struct MCPTokenStoreTests { MCPTokenStore(credentialStore: credentialStore) } - private func makeToken(isActive: Bool = true, expiresAt: Date? = nil) -> MCPAuthToken { + private func makeToken( + name: String = "test-token", + isActive: Bool = true, + expiresAt: Date? = nil, + isClaudeAgentCredential: Bool = false + ) -> MCPAuthToken { MCPAuthToken( id: UUID(), - name: "test-token", + name: name, prefix: "tp_abc12", tokenHash: "fakehash", salt: "fakesalt", @@ -88,7 +88,8 @@ struct MCPTokenStoreTests { createdAt: Date.now, lastUsedAt: nil, expiresAt: expiresAt, - isActive: isActive + isActive: isActive, + isClaudeAgentCredential: isClaudeAgentCredential ) } @@ -490,6 +491,110 @@ struct MCPTokenStoreTests { #expect(await store.validate(bearerToken: result.plaintext) == nil) } + @Test("A token the Keychain did not save is never handed out") + func unsavedTokenIsRefused() async throws { + let credentials = InMemoryCredentialStore() + let store = makeStore(credentials) + credentials.failsWrites = true + + await #expect(throws: MCPTokenStoreError.notSaved) { + _ = try await store.generate( + name: "Raycast", + permissions: .readOnly, + connectionAccess: .all, + expiresAt: nil, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + } + + #expect(await store.list().isEmpty) + } + + @Test("The bridge credential is still minted when the Keychain refuses the write") + func bridgeCredentialLivesInMemory() async throws { + let credentials = InMemoryCredentialStore() + let store = makeStore(credentials) + credentials.failsWrites = true + + let bridge = try await store.generate( + name: MCPTokenStore.stdioBridgeTokenName, + permissions: MCPTokenStore.bridgeTokenPermissions, + connectionAccess: .all, + expiresAt: Date.now.addingTimeInterval(3_600), + isBridgeCredential: true, + isClaudeAgentCredential: false, + extraScopes: [] + ) + + #expect(await store.validate(bearerToken: bridge.plaintext)?.id == bridge.token.id) + } + + @Test("Deleting reports whether the Keychain took the change") + func deleteReportsPersistence() async throws { + let credentials = InMemoryCredentialStore() + let store = makeStore(credentials) + let result = try await store.generate( + name: "settings", + permissions: .readOnly, + connectionAccess: .all, + expiresAt: nil, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + + credentials.failsWrites = true + #expect(await store.delete(tokenId: result.token.id) == false) + #expect(await store.validate(bearerToken: result.plaintext) == nil) + + let reloaded = makeStore(credentials) + await reloaded.loadFromDisk() + #expect(await reloaded.token(id: result.token.id) != nil) + + credentials.failsWrites = false + let second = try await store.generate( + name: "second", + permissions: .readOnly, + connectionAccess: .all, + expiresAt: nil, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + #expect(await store.delete(tokenId: second.token.id)) + let afterSave = makeStore(credentials) + await afterSave.loadFromDisk() + #expect(await afterSave.list().isEmpty) + } + + @Test("Only the Claude Agent's own mint may take its token name") + func agentNameIsReserved() async throws { + let store = makeStore() + let paired = try await store.generate( + name: MCPTokenStore.claudeAgentTokenName, + permissions: .readOnly, + connectionAccess: .all, + expiresAt: nil, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + let agent = try await store.generate( + name: MCPTokenStore.claudeAgentTokenName, + permissions: .readOnly, + connectionAccess: .all, + expiresAt: Date.now.addingTimeInterval(900), + isBridgeCredential: false, + isClaudeAgentCredential: true, + extraScopes: [] + ) + + #expect(paired.token.name != MCPTokenStore.claudeAgentTokenName) + #expect(agent.token.name == MCPTokenStore.claudeAgentTokenName) + } + @Test("A superseded bridge credential stops working at once and no revocation observer hears of it") func supersededBridgeCredentialIsDroppedWithoutARevocation() async throws { let store = makeStore() @@ -634,6 +739,28 @@ struct MCPTokenStoreTests { #expect(await reader.token(id: survivor.token.id) != nil) } + @Test("A token an older build let a client name like the Claude Agent is renamed and saved at load") + func claimedAgentNameIsReleasedAtLoad() async throws { + let claimed = makeToken(name: MCPTokenStore.claudeAgentTokenName) + let agent = makeToken(name: MCPTokenStore.claudeAgentTokenName, isClaudeAgentCredential: true) + let credentials = InMemoryCredentialStore( + seed: try MCPTokenStore.encodeStored(tokens: [claimed, agent], undecoded: []) + ) + + let store = makeStore(credentials) + await store.loadFromDisk() + + let renamed = try #require(await store.token(id: claimed.id)) + #expect(renamed.name == MCPTokenStore.claudeAgentTokenName + " (client)") + #expect(renamed.tokenHash == claimed.tokenHash) + #expect(renamed.isClaudeAgentCredential == false) + #expect(await store.token(id: agent.id)?.name == MCPTokenStore.claudeAgentTokenName) + + let saved = MCPTokenStore.decodeStored(Data(credentials.storedText.utf8)).tokens + #expect(saved.first { $0.id == claimed.id }?.name == MCPTokenStore.claudeAgentTokenName + " (client)") + #expect(saved.first { $0.id == agent.id }?.name == MCPTokenStore.claudeAgentTokenName) + } + @Test("An optional grant survives a reload and adds to the tier's scopes") func extraScopesRoundTrip() async throws { let credentials = InMemoryCredentialStore() diff --git a/apple/TableProTests/Core/MCP/PairingRedirectBuilderTests.swift b/apple/TableProTests/Core/MCP/PairingRedirectBuilderTests.swift index 51cbd87e52..2076c5f5a5 100644 --- a/apple/TableProTests/Core/MCP/PairingRedirectBuilderTests.swift +++ b/apple/TableProTests/Core/MCP/PairingRedirectBuilderTests.swift @@ -1,8 +1,3 @@ -// -// PairingRedirectBuilderTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @@ -126,6 +121,19 @@ struct PairingRedirectBuilderTests { #expect(try success(launch, mode: .legacy) == "\(launch)&context=%7B%22code%22:%22\(Self.code)%22%7D") } + @Test("A pairing that failed after approval answers with server_error in every mode, state kept") + func failureAnswersWithServerError() throws { + for base in [Self.raycast, Self.loopback] { + for mode in Self.modes { + let redirect = try #require(PairingRedirectBuilder.failed(base: try url(base), state: "s1", mode: mode)) + let fields = try parameters(of: redirect.absoluteString) + #expect(fields["error"] == "server_error") + #expect(fields["state"] == "s1") + #expect(fields["code"] == nil) + } + } + } + @Test("No state on the link means no state on the redirect") func absentStateIsNotInvented() throws { for base in [Self.raycast, Self.loopback] { diff --git a/apple/TableProTests/Core/MCP/Protocol/MCPProtocolDispatcherTests.swift b/apple/TableProTests/Core/MCP/Protocol/MCPProtocolDispatcherTests.swift index 6ab320fac6..e5045330c7 100644 --- a/apple/TableProTests/Core/MCP/Protocol/MCPProtocolDispatcherTests.swift +++ b/apple/TableProTests/Core/MCP/Protocol/MCPProtocolDispatcherTests.swift @@ -627,6 +627,298 @@ struct MCPProtocolDispatcherTests { #expect(result["inputRequests"]?["approve_connection"] != nil) } + @Test("The bridge's discover probe is not listed as a client, the client it carries is") + func discoverProbeIsNotAClient() async throws { + let dispatcher = MCPProtocolTestSupport.makeDispatcher(handlers: [DiscoverHandler(), StubToolsListHandler()]) + let bridge = Self.bridgePrincipal() + + let probe = Self.request(id: .string("tablepro-bridge-discover"), method: DiscoverHandler.method, clientName: "tablepro-mcp") + let (probeExchange, probeSink) = MCPProtocolTestSupport.makeExchange(message: probe, principal: bridge, clientAddress: .localSocket) + await dispatcher.dispatch(probeExchange) + await probeSink.waitForCompletion() + #expect(try await probeSink.successResult() != nil) + #expect(await dispatcher.activityLedger.snapshot(now: MCPProtocolTestSupport.referenceDate).isEmpty) + + let list = Self.request(id: .number(2), method: StubToolsListHandler.method, clientName: "claude-ai") + let (listExchange, listSink) = MCPProtocolTestSupport.makeExchange(message: list, principal: bridge, clientAddress: .localSocket) + await dispatcher.dispatch(listExchange) + await listSink.waitForCompletion() + + let entries = await dispatcher.activityLedger.snapshot(now: MCPProtocolTestSupport.referenceDate) + #expect(entries.map(\.clientName) == ["claude-ai"]) + #expect(entries.first?.transport == .stdioBridge) + } + + @Test("Ending one stdio client's requests leaves another stdio client's request on the same credential running") + func cancellingOneClientSparesTheOther() async throws { + let handler = StubTestHandler(behavior: .waitForCancellation) + let dispatcher = MCPProtocolTestSupport.makeDispatcher(handlers: [handler]) + let bridge = Self.bridgePrincipal() + let (cursorExchange, cursorSink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(1), method: StubTestHandler.method, clientName: "cursor-vscode"), + principal: bridge, + clientAddress: .localSocket + ) + let (zedExchange, zedSink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(2), method: StubTestHandler.method, clientName: "Zed"), + principal: bridge, + clientAddress: .localSocket + ) + + async let cursorRun: Void = dispatcher.dispatch(cursorExchange) + async let zedRun: Void = dispatcher.dispatch(zedExchange) + #expect(await waitForInflight(dispatcher, count: 2) == 2) + + let entries = await dispatcher.activityLedger.snapshot(now: MCPProtocolTestSupport.referenceDate) + let cursor = try #require(entries.first { $0.clientName == "cursor-vscode" }) + #expect(await dispatcher.cancelInflight(matchingClientId: cursor.id) == 1) + + await cursorSink.waitForCompletion() + let cursorError = try #require(try await cursorSink.errorEnvelope()) + #expect(cursorError.code == JsonRpcErrorCode.requestCancelled) + #expect(await dispatcher.inflightCount() == 1) + #expect(await zedSink.jsonWrites.isEmpty) + + _ = await dispatcher.cancelAllInflight() + await zedSink.waitForCompletion() + _ = await cursorRun + _ = await zedRun + } + + @Test("Two stdio clients may use the same request id, and one's cancellation stops only its own request") + func stdioClientsShareARequestIdWithoutCollapsing() async throws { + let handler = StubTestHandler(behavior: .waitForCancellation) + let dispatcher = MCPProtocolTestSupport.makeDispatcher(handlers: [handler]) + let bridge = Self.bridgePrincipal() + let (cursorExchange, cursorSink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(1), method: StubTestHandler.method, clientName: "cursor-vscode"), + principal: bridge, + clientAddress: .localSocket + ) + let (zedExchange, zedSink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(1), method: StubTestHandler.method, clientName: "Zed"), + principal: bridge, + clientAddress: .localSocket + ) + + async let cursorRun: Void = dispatcher.dispatch(cursorExchange) + async let zedRun: Void = dispatcher.dispatch(zedExchange) + #expect(await waitForInflight(dispatcher, count: 2) == 2) + + let cancel = JsonRpcMessage.notification(JsonRpcNotification( + method: "notifications/cancelled", + params: .object([ + "requestId": .int(1), + "_meta": .object(MCPProtocolTestSupport.metaFields(clientName: "Zed")) + ]) + )) + let (cancelExchange, cancelSink) = MCPProtocolTestSupport.makeExchange( + message: cancel, + principal: bridge, + clientAddress: .localSocket + ) + await dispatcher.dispatch(cancelExchange) + #expect(await cancelSink.acceptedCount == 1) + + await zedSink.waitForCompletion() + let zedError = try #require(try await zedSink.errorEnvelope()) + #expect(zedError.code == JsonRpcErrorCode.requestCancelled) + #expect(await dispatcher.inflightCount() == 1) + #expect(await cursorSink.jsonWrites.isEmpty) + + _ = await dispatcher.cancelAllInflight() + await cursorSink.waitForCompletion() + _ = await cursorRun + _ = await zedRun + } + + @Test("A stdio cancellation that names no client stops nothing") + func stdioCancellationWithoutAClientIsDropped() async throws { + let handler = StubTestHandler(behavior: .waitForCancellation) + let dispatcher = MCPProtocolTestSupport.makeDispatcher(handlers: [handler]) + let bridge = Self.bridgePrincipal() + let (exchange, sink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(4), method: StubTestHandler.method, clientName: "Zed"), + principal: bridge, + clientAddress: .localSocket + ) + + async let run: Void = dispatcher.dispatch(exchange) + #expect(await waitForInflight(dispatcher, count: 1) == 1) + + let (cancelExchange, cancelSink) = MCPProtocolTestSupport.makeExchange( + message: MCPProtocolTestSupport.makeNotification( + method: "notifications/cancelled", + params: .object(["requestId": .int(4)]) + ), + principal: bridge, + clientAddress: .localSocket + ) + await dispatcher.dispatch(cancelExchange) + #expect(await cancelSink.acceptedCount == 1) + #expect(await dispatcher.inflightCount() == 1) + #expect(await sink.jsonWrites.isEmpty) + + _ = await dispatcher.cancelAllInflight() + await sink.waitForCompletion() + _ = await run + } + + @Test("A stdio cancellation sent with the renewed bridge credential stops the request the old one started") + func stdioCancellationCrossesACredentialRotation() async throws { + let handler = StubTestHandler(behavior: .waitForCancellation) + let dispatcher = MCPProtocolTestSupport.makeDispatcher(handlers: [handler], handlerTimeout: .seconds(10)) + let (exchange, sink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(3), method: StubTestHandler.method, clientName: "claude-code", bridgeInstance: "one"), + principal: Self.bridgePrincipal(fingerprint: "a"), + clientAddress: .localSocket + ) + + async let run: Void = dispatcher.dispatch(exchange) + #expect(await waitForInflight(dispatcher, count: 1) == 1) + + let (cancelExchange, cancelSink) = MCPProtocolTestSupport.makeExchange( + message: Self.cancellation(requestId: 3, clientName: "claude-code", bridgeInstance: "one"), + principal: Self.bridgePrincipal(fingerprint: "b"), + clientAddress: .localSocket + ) + await dispatcher.dispatch(cancelExchange) + #expect(await cancelSink.acceptedCount == 1) + #expect(await dispatcher.inflightCount() == 0) + + _ = await dispatcher.cancelAllInflight() + await sink.waitForCompletion() + let error = try #require(try await sink.errorEnvelope()) + #expect(error.code == JsonRpcErrorCode.requestCancelled) + _ = await run + } + + @Test("A stdio cancellation without clientInfo stops the request that sent it, matched by bridge instance") + func stdioCancellationWithoutClientInfo() async throws { + let handler = StubTestHandler(behavior: .waitForCancellation) + let dispatcher = MCPProtocolTestSupport.makeDispatcher(handlers: [handler], handlerTimeout: .seconds(10)) + let bridge = Self.bridgePrincipal() + let (exchange, sink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(3), method: StubTestHandler.method, clientName: "claude-code", bridgeInstance: "one"), + principal: bridge, + clientAddress: .localSocket + ) + + async let run: Void = dispatcher.dispatch(exchange) + #expect(await waitForInflight(dispatcher, count: 1) == 1) + + let (otherSession, _) = MCPProtocolTestSupport.makeExchange( + message: Self.cancellation(requestId: 3, clientName: nil, bridgeInstance: "two"), + principal: bridge, + clientAddress: .localSocket + ) + await dispatcher.dispatch(otherSession) + #expect(await dispatcher.inflightCount() == 1) + + let (cancelExchange, cancelSink) = MCPProtocolTestSupport.makeExchange( + message: Self.cancellation(requestId: 3, clientName: nil, bridgeInstance: "one"), + principal: bridge, + clientAddress: .localSocket + ) + await dispatcher.dispatch(cancelExchange) + #expect(await cancelSink.acceptedCount == 1) + #expect(await dispatcher.inflightCount() == 0) + + _ = await dispatcher.cancelAllInflight() + await sink.waitForCompletion() + let error = try #require(try await sink.errorEnvelope()) + #expect(error.code == JsonRpcErrorCode.requestCancelled) + _ = await run + } + + @Test("Sessions of one stdio client share a request id: a cancellation stops its own session, Disconnect ends them all") + func sessionsOfOneStdioClientKeepTheirRequestsApart() async throws { + let handler = StubTestHandler(behavior: .waitForCancellation) + let dispatcher = MCPProtocolTestSupport.makeDispatcher(handlers: [handler], handlerTimeout: .seconds(10)) + let bridge = Self.bridgePrincipal() + let (oneExchange, oneSink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(1), method: StubTestHandler.method, clientName: "claude-code", bridgeInstance: "one"), + principal: bridge, + clientAddress: .localSocket + ) + let (twoExchange, twoSink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(1), method: StubTestHandler.method, clientName: "claude-code", bridgeInstance: "two"), + principal: bridge, + clientAddress: .localSocket + ) + let (threeExchange, threeSink) = MCPProtocolTestSupport.makeExchange( + message: Self.request(id: .number(1), method: StubTestHandler.method, clientName: "claude-code", bridgeInstance: "three"), + principal: bridge, + clientAddress: .localSocket + ) + + async let oneRun: Void = dispatcher.dispatch(oneExchange) + async let twoRun: Void = dispatcher.dispatch(twoExchange) + async let threeRun: Void = dispatcher.dispatch(threeExchange) + #expect(await waitForInflight(dispatcher, count: 3) == 3) + + let entries = await dispatcher.activityLedger.snapshot(now: MCPProtocolTestSupport.referenceDate) + #expect(entries.count == 1) + let row = try #require(entries.first) + + let (cancelExchange, _) = MCPProtocolTestSupport.makeExchange( + message: Self.cancellation(requestId: 1, clientName: "claude-code", bridgeInstance: "three"), + principal: bridge, + clientAddress: .localSocket + ) + await dispatcher.dispatch(cancelExchange) + #expect(await dispatcher.inflightCount() == 2) + #expect(await oneSink.jsonWrites.isEmpty) + #expect(await twoSink.jsonWrites.isEmpty) + + #expect(await dispatcher.cancelInflight(matchingClientId: row.id) == 2) + #expect(await dispatcher.inflightCount() == 0) + + _ = await dispatcher.cancelAllInflight() + for sink in [oneSink, twoSink, threeSink] { + await sink.waitForCompletion() + let error = try #require(try await sink.errorEnvelope()) + #expect(error.code == JsonRpcErrorCode.requestCancelled) + } + _ = await oneRun + _ = await twoRun + _ = await threeRun + } + + private static func bridgePrincipal(fingerprint: String = "bridge") -> MCPPrincipal { + MCPPrincipal( + tokenFingerprint: fingerprint, + tokenId: UUID(), + scopes: MCPScope.readWriteSet, + connectionAccess: .all, + metadata: MCPPrincipalMetadata( + label: MCPTokenStore.stdioBridgeTokenName, + issuedAt: MCPProtocolTestSupport.referenceDate, + expiresAt: nil, + isBridgeCredential: true + ) + ) + } + + private static func request(id: JsonRpcId, method: String, clientName: String, bridgeInstance: String? = nil) -> JsonRpcMessage { + .request(JsonRpcRequest(id: id, method: method, params: .object(["_meta": .object(meta(clientName, bridgeInstance))]))) + } + + private static func cancellation(requestId: Int, clientName: String?, bridgeInstance: String?) -> JsonRpcMessage { + .notification(JsonRpcNotification( + method: "notifications/cancelled", + params: .object(["requestId": .int(requestId), "_meta": .object(meta(clientName, bridgeInstance))]) + )) + } + + private static func meta(_ clientName: String?, _ bridgeInstance: String?) -> [String: JsonValue] { + var fields = MCPProtocolTestSupport.metaFields(clientName: clientName) + if let bridgeInstance { + fields[MCPMetaKeys.bridgeInstance] = .string(bridgeInstance) + } + return fields + } + private func dispatch( _ message: JsonRpcMessage, handlers: [any MCPMethodHandler], diff --git a/apple/TableProTests/Core/Services/Infrastructure/LaunchIntentFailureOwnershipTests.swift b/apple/TableProTests/Core/Services/Infrastructure/LaunchIntentFailureOwnershipTests.swift index 240400a114..999c63b1d8 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/LaunchIntentFailureOwnershipTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/LaunchIntentFailureOwnershipTests.swift @@ -1,14 +1,8 @@ -// -// LaunchIntentFailureOwnershipTests.swift -// TableProTests -// -// Opening a database file or URL builds its connection inside the router, so the launch intent -// names no connection. A connect that failed there was then alerted over the window that already -// showed the same failure, covering the button that fixed it. -// +// A file or URL open builds its connection in the router, so its failure must not be alerted over the window showing it. import Foundation @testable import TablePro +import TableProMCP import Testing @MainActor @@ -45,4 +39,35 @@ struct LaunchIntentFailureOwnershipTests { #expect(error.localizedDescription == Self.underlying.localizedDescription) } + + @Test("A background launch made only for MCP quits when the server fails to start, as it does when MCP is off") + func failedMCPStartEndsAnIdleLaunch() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("mcp-launch-\(UUID().uuidString)", isDirectory: true) + // Too long for a socket path, so the server falls back to the temporary folder, which is a file here. + let directory = root.appendingPathComponent(String(repeating: "d", count: 110), isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let notAFolder = root.appendingPathComponent("tmp-file", isDirectory: false) + try Data().write(to: notAFolder) + let manager = MCPServerManager( + handshake: MCPHandshakeFile(directory: directory, temporaryDirectory: notAFolder), + isEnabled: { true } + ) + + #expect(await LaunchIntentRouter.startMCPServerLeavesNothingToDo(manager: manager, isIdleMachineSession: { true })) + #expect(manager.state == .failed(.socketFolderUnusable)) + #expect(!(await LaunchIntentRouter.startMCPServerLeavesNothingToDo(manager: manager, isIdleMachineSession: { false }))) + await manager.stop() + } + + @Test("A background launch made only for MCP quits when MCP is off") + func refusedMCPStartEndsAnIdleLaunch() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("mcp-launch-off-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let manager = MCPServerManager(handshake: MCPHandshakeFile(directory: directory), isEnabled: { false }) + + #expect(await LaunchIntentRouter.startMCPServerLeavesNothingToDo(manager: manager, isIdleMachineSession: { true })) + #expect(manager.state == .stopped) + } } diff --git a/apple/TableProTests/Views/Components/BrandIconTests.swift b/apple/TableProTests/Views/Components/BrandIconTests.swift new file mode 100644 index 0000000000..697ee755a5 --- /dev/null +++ b/apple/TableProTests/Views/Components/BrandIconTests.swift @@ -0,0 +1,112 @@ +// +// BrandIconTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import Testing + +struct BrandIconTests { + private static func catalogIconSlugs() throws -> [String] { + let url = try #require(Bundle.main.url(forResource: "clients", withExtension: "json")) + let object = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) + let catalog = try #require(object as? [String: Any]) + let clients = try #require(catalog["clients"] as? [[String: Any]]) + return try clients.map { client in + try #require(client["icon"] as? String, "\(client["id"] ?? "a client") has no icon") + } + } + + private static var providerIcons: [(name: String, icon: BrandIcon)] { + AIProviderType.allCases.map { ($0.rawValue, $0.icon) } + AIProviderPreset.all.map { ($0.id, $0.icon) } + } + + private static func visiblePixelCount(of image: NSImage, side: Int) throws -> Int { + let rep = try #require(NSBitmapImageRep( + bitmapDataPlanes: nil, pixelsWide: side, pixelsHigh: side, bitsPerSample: 8, samplesPerPixel: 4, + hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0 + )) + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep) + image.draw(in: NSRect(x: 0, y: 0, width: side, height: side)) + NSGraphicsContext.restoreGraphicsState() + var count = 0 + for y in 0.. 0 { + count += 1 + } + } + return count + } + + @Test("Every client icon in the bundled catalog is an asset in the app") + func catalogIconsResolve() throws { + let slugs = try Self.catalogIconSlugs() + #expect(!slugs.isEmpty) + for slug in Set(slugs) { + #expect(NSImage(named: BrandIcon.assetName(for: slug)) != nil, "\(slug)-icon is missing") + } + } + + @Test("Every AI provider and preset icon is an asset, and its fallback is an SF Symbol") + func providerIconsResolve() { + for (name, icon) in Self.providerIcons { + if let slug = icon.slug { + #expect(icon.assetImage != nil, "\(name): \(slug)-icon is missing") + } + #expect( + NSImage(systemSymbolName: icon.fallbackSystemImage, accessibilityDescription: nil) != nil, + "\(name): \(icon.fallbackSystemImage) is not an SF Symbol" + ) + } + } + + @Test("A custom provider has no brand and draws its SF Symbol") + func customProviderFallsBack() { + let icon = AIProviderType.custom.icon + #expect(icon.slug == nil) + #expect(icon.assetImage == nil) + #expect(icon.nsImage() != nil) + } + + @Test("A slug with no asset draws the fallback symbol") + func missingAssetFallsBack() throws { + let icon = BrandIcon(slug: "no-such-brand", fallbackSystemImage: "server.rack") + #expect(icon.assetImage == nil) + let image = try #require(icon.nsImage()) + #expect(image.isTemplate) + } + + @Test("The menu copy is the asked square and keeps the asset's template flag") + func menuCopyKeepsTemplateFlag() throws { + let template = try #require(BrandIcon(slug: "claude", fallbackSystemImage: "brain").nsImage(pointSize: 16)) + #expect(template.size == NSSize(width: 16, height: 16)) + #expect(template.isTemplate) + + let original = try #require(BrandIcon(slug: "vscode", fallbackSystemImage: "curlybraces").nsImage()) + #expect(original.size == NSSize(width: 16, height: 16)) + #expect(!original.isTemplate) + } + + // A one-color official mark is a template; a multicolor one keeps its colors, which VS Code's brand terms require. + @Test("Only the brands whose official logo has several colors skip template rendering") + func onlyMulticolorLogosAreOriginal() throws { + let slugs = try Set(Self.catalogIconSlugs() + Self.providerIcons.compactMap { $0.icon.slug }) + let original = slugs.filter { slug in + NSImage(named: BrandIcon.assetName(for: slug))?.isTemplate == false + } + #expect(original == ["kiro", "mlx", "requesty", "vscode"]) + } + + @Test("Every brand asset draws something at menu size") + @MainActor + func everyAssetDraws() throws { + let slugs = try Set(Self.catalogIconSlugs() + Self.providerIcons.compactMap { $0.icon.slug }) + for slug in slugs { + let image = try #require(BrandIcon(slug: slug, fallbackSystemImage: "questionmark").nsImage(pointSize: 16)) + #expect(try Self.visiblePixelCount(of: image, side: 32) > 0, "\(slug)-icon draws nothing") + } + } +} diff --git a/apple/TableProUITests/MCPConnectClientUITests.swift b/apple/TableProUITests/MCPConnectClientUITests.swift new file mode 100644 index 0000000000..e650ab8b3c --- /dev/null +++ b/apple/TableProUITests/MCPConnectClientUITests.swift @@ -0,0 +1,45 @@ +import XCTest + +final class MCPConnectClientUITests: UITestCase { + func testConnectAClientListsTheCatalogAndShowsASetup() throws { + let app = try launchOpeningURL("tablepro://settings/mcp") + let settings = window("settings", in: app) + XCTAssertTrue(settings.waitToExist(timeout: 10), "The settings link must open the settings window") + + let enable = settings.switches["mcp-enable-server-toggle"] + XCTAssertTrue(waitUntilHittable(enable, timeout: 10), "The MCP pane must offer its Enable switch") + if !isOn(enable) { + enable.click() + } + + let connect = settings.buttons["mcp-connect-client"] + XCTAssertTrue(scrollUntilHittable(connect, in: settings, timeout: 10), "An enabled server offers Connect a Client") + connect.click() + + let sheet = settings.sheets.firstMatch + XCTAssertTrue(sheet.waitToExist(timeout: 10), "Connect a Client must open its sheet") + // The list draws only the rows in view, so only the catalog's first clients are asked for. + for name in ["Claude Desktop", "Claude Code"] { + XCTAssertTrue(text(name, in: sheet).waitToExist(timeout: 10), "The sheet should list \(name) from the bundled catalog") + } + + let claudeDesktop = text("Claude Desktop", in: sheet) + XCTAssertTrue(waitUntilHittable(claudeDesktop, timeout: 10)) + claudeDesktop.click() + // Selectable text is not always a static text, so the path is matched by value alone. + let path = sheet.descendants(matching: .any) + .matching(NSPredicate(format: "value == %@", "~/Library/Application Support/Claude/claude_desktop_config.json")) + .firstMatch + XCTAssertTrue(path.waitToExist(timeout: 5), "Selecting a client shows its settings file, inside the sandbox's home") + + let done = sheet.buttons["mcp-client-setup-done"] + XCTAssertTrue(waitUntilHittable(done, timeout: 5)) + done.click() + XCTAssertTrue(waitForPredicate(timeout: 5) { !sheet.exists }, "Done should close the sheet") + } + + // SwiftUI text carries its string in `value` with no label, so a subscript by title finds nothing. + private func text(_ value: String, in container: XCUIElement) -> XCUIElement { + container.staticTexts.matching(NSPredicate(format: "value == %@", value)).firstMatch + } +} diff --git a/apple/TestPlans/Unit.xctestplan b/apple/TestPlans/Unit.xctestplan index 2ac2d49434..7872b0c949 100644 --- a/apple/TestPlans/Unit.xctestplan +++ b/apple/TestPlans/Unit.xctestplan @@ -116,6 +116,13 @@ "name" : "TableProCommandLineTests" } }, + { + "target" : { + "containerPath" : "container:Packages\/TableProMacCore", + "identifier" : "TableProMCPClientsTests", + "name" : "TableProMCPClientsTests" + } + }, { "target" : { "containerPath" : "container:Packages\/TableProMacCore", diff --git a/apple/changelog.d/4211.added.1.md b/apple/changelog.d/4211.added.1.md new file mode 100644 index 0000000000..7921fdf593 --- /dev/null +++ b/apple/changelog.d/4211.added.1.md @@ -0,0 +1 @@ +The MCP Activity Log shows and filters by the client that made each call. diff --git a/apple/changelog.d/4211.added.md b/apple/changelog.d/4211.added.md new file mode 100644 index 0000000000..b040e36e0e --- /dev/null +++ b/apple/changelog.d/4211.added.md @@ -0,0 +1 @@ +Connect a Client lists 21 AI clients, including Codex and VS Code, sets most up in one click and says when one connects. diff --git a/apple/changelog.d/4211.changed.md b/apple/changelog.d/4211.changed.md new file mode 100644 index 0000000000..764926429e --- /dev/null +++ b/apple/changelog.d/4211.changed.md @@ -0,0 +1 @@ +AI provider and MCP client lists show each brand's logo instead of a generic symbol. diff --git a/apple/changelog.d/4211.fixed.1.md b/apple/changelog.d/4211.fixed.1.md new file mode 100644 index 0000000000..66b365425f --- /dev/null +++ b/apple/changelog.d/4211.fixed.1.md @@ -0,0 +1 @@ +A Claude Desktop, Cursor or Zed client showed twice in Connected Clients, and Disconnect cut off every other one. diff --git a/apple/changelog.d/4211.fixed.2.md b/apple/changelog.d/4211.fixed.2.md new file mode 100644 index 0000000000..6d108fd695 --- /dev/null +++ b/apple/changelog.d/4211.fixed.2.md @@ -0,0 +1 @@ +The new token sheet showed the hidden token in its setup snippet. diff --git a/apple/changelog.d/4211.fixed.3.md b/apple/changelog.d/4211.fixed.3.md new file mode 100644 index 0000000000..485891f5fe --- /dev/null +++ b/apple/changelog.d/4211.fixed.3.md @@ -0,0 +1 @@ +Generate Token did nothing when the token could not be saved, and the MCP port took any number. diff --git a/apple/changelog.d/4211.fixed.4.md b/apple/changelog.d/4211.fixed.4.md new file mode 100644 index 0000000000..5e0a7d782b --- /dev/null +++ b/apple/changelog.d/4211.fixed.4.md @@ -0,0 +1 @@ +Claude Agent lost its database tools silently, and pairing failed with a vague message, when a token was not saved. diff --git a/apple/changelog.d/4211.fixed.md b/apple/changelog.d/4211.fixed.md new file mode 100644 index 0000000000..e67edd5a74 --- /dev/null +++ b/apple/changelog.d/4211.fixed.md @@ -0,0 +1 @@ +The Claude Code setup command added TablePro to one project only, and broke on a path with a space. diff --git a/apple/project.yml b/apple/project.yml index 0fcb5d2dfd..345f475d4a 100644 --- a/apple/project.yml +++ b/apple/project.yml @@ -311,6 +311,9 @@ targets: - path: TablePro/Resources/ThirdPartyLicenses type: folder buildPhase: resources + # The MCP client catalog, one file the Linux app reads too. + - path: ../core/crates/mcp/clients.json + buildPhase: resources - path: TablePro/CLI/tablepro buildPhase: copyFiles: @@ -415,7 +418,7 @@ targets: - package: TableProCore products: [TableProAutocomplete, TableProConnectionLibrary, TableProCoreTypes, TableProEtcdCore, TableProFirebaseCore, TableProGeometry, TableProGoogleCloud, TableProGzip, TableProHTTP, TableProImport, TableProInfluxDBCore, TableProLogRedaction, TableProNumberFormatting, TableProProcess, TableProQdrantCore, TableProRedisCore, TableProSQLGrammar, TableProSQLQuoting, TableProSQLVocabulary, TableProSSHTransport, TableProSyncTransport, TableProTLSClientIdentity, TableProTabular, TableProTabularIO, TableProTheme, TableProWeaviateCore] - package: TableProMacCore - products: [TableProCloudAPI, TableProMCP, TableProSSHConfig, TableProUtilities] + products: [TableProCloudAPI, TableProMCP, TableProMCPClients, TableProSSHConfig, TableProUtilities] # Writes nothing for a version CHANGELOG.md has no section for, so a 0.0.0-dev build ships no notes. postCompileScripts: - name: Write WhatsNew.md diff --git a/core/crates/mcp/Cargo.toml b/core/crates/mcp/Cargo.toml index 061977f088..61d744e1ec 100644 --- a/core/crates/mcp/Cargo.toml +++ b/core/crates/mcp/Cargo.toml @@ -25,6 +25,7 @@ serde.workspace = true serde_json.workspace = true subtle = "2.6" thiserror.workspace = true +toml_edit.workspace = true tokio = { workspace = true, features = ["rt"] } tokio-util.workspace = true tracing.workspace = true diff --git a/core/crates/mcp/clients.json b/core/crates/mcp/clients.json new file mode 100644 index 0000000000..fe7c343a1e --- /dev/null +++ b/core/crates/mcp/clients.json @@ -0,0 +1,495 @@ +{ + "schemaVersion": 1, + "serverName": "tablepro", + "configs": { + "claude-desktop": { + "macos": { "path": "~/Library/Application Support/Claude/claude_desktop_config.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "${XDG_CONFIG_HOME:-~/.config}/Claude/claude_desktop_config.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "claude-code": { + "macos": { "path": "${CLAUDE_CONFIG_DIR:-~}/.claude.json", "format": "json", "keyPath": ["mcpServers"], "writable": false, "otherScopes": [["projects", "*", "mcpServers"]] }, + "linux": { "path": "${CLAUDE_CONFIG_DIR:-~}/.claude.json", "format": "json", "keyPath": ["mcpServers"], "writable": false, "otherScopes": [["projects", "*", "mcpServers"]] } + }, + "codex": { + "macos": { "path": "${CODEX_HOME:-~/.codex}/config.toml", "format": "toml", "keyPath": ["mcp_servers"] }, + "linux": { "path": "${CODEX_HOME:-~/.codex}/config.toml", "format": "toml", "keyPath": ["mcp_servers"] } + }, + "cursor": { + "macos": { "path": "~/.cursor/mcp.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "~/.cursor/mcp.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "vscode": { + "macos": { "path": "~/Library/Application Support/Code/User/mcp.json", "format": "jsonc", "keyPath": ["servers"] }, + "linux": { "path": "${XDG_CONFIG_HOME:-~/.config}/Code/User/mcp.json", "format": "jsonc", "keyPath": ["servers"] } + }, + "vscode-insiders": { + "macos": { "path": "~/Library/Application Support/Code - Insiders/User/mcp.json", "format": "jsonc", "keyPath": ["servers"] }, + "linux": { "path": "${XDG_CONFIG_HOME:-~/.config}/Code - Insiders/User/mcp.json", "format": "jsonc", "keyPath": ["servers"] } + }, + "devin": { + "macos": { "path": "${XDG_CONFIG_HOME:-~/.config}/devin/mcp_config.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "${XDG_CONFIG_HOME:-~/.config}/devin/mcp_config.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "zed": { + "macos": { "path": "~/.config/zed/settings.json", "format": "jsonc", "keyPath": ["context_servers"] }, + "linux": { "path": "${XDG_CONFIG_HOME:-~/.config}/zed/settings.json", "format": "jsonc", "keyPath": ["context_servers"] } + }, + "gemini": { + "macos": { "path": "~/.gemini/settings.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "~/.gemini/settings.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "copilot": { + "macos": { "path": "${COPILOT_HOME:-~/.copilot}/mcp-config.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "${COPILOT_HOME:-~/.copilot}/mcp-config.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "opencode": { + "macos": { "path": "${XDG_CONFIG_HOME:-~/.config}/opencode/opencode.json", "format": "jsonc", "keyPath": ["mcp", "servers"], "writable": false, "alternateKeyPaths": [["mcp"]] }, + "linux": { "path": "${XDG_CONFIG_HOME:-~/.config}/opencode/opencode.json", "format": "jsonc", "keyPath": ["mcp", "servers"], "writable": false, "alternateKeyPaths": [["mcp"]] } + }, + "cline": { + "macos": { "path": "${CLINE_DIR:-~/.cline}/data/settings/cline_mcp_settings.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "${CLINE_DIR:-~/.cline}/data/settings/cline_mcp_settings.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "goose": { + "macos": { "path": "${XDG_CONFIG_HOME:-~/.config}/goose/config.yaml", "format": "yaml", "keyPath": ["extensions"], "writable": false }, + "linux": { "path": "${XDG_CONFIG_HOME:-~/.config}/goose/config.yaml", "format": "yaml", "keyPath": ["extensions"], "writable": false } + }, + "lmstudio": { + "macos": { "path": "~/.lmstudio/mcp.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "~/.lmstudio/mcp.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "kiro": { + "macos": { "path": "~/.kiro/settings/mcp.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "~/.kiro/settings/mcp.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "warp": { + "macos": { "path": "~/.warp/.mcp.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "~/.warp/.mcp.json", "format": "json", "keyPath": ["mcpServers"] } + }, + "junie": { + "macos": { "path": "~/.junie/mcp/mcp.json", "format": "json", "keyPath": ["mcpServers"] }, + "linux": { "path": "~/.junie/mcp/mcp.json", "format": "json", "keyPath": ["mcpServers"] } + } + }, + "clients": [ + { + "id": "claude-desktop", + "name": "Claude Desktop", + "icon": "claude", + "config": "claude-desktop", + "clientInfo": { "names": ["claude-ai"], "prefixes": [] }, + "macos": { + "detect": [{ "bundleId": "com.anthropic.claudefordesktop" }], + "entry": { "command": "{command}", "args": [] }, + "install": [{ "kind": "file" }], + "applies": "restartApp" + }, + "linux": { + "detect": [{ "binary": "claude-desktop", "paths": ["/usr/bin/claude-desktop", "/usr/lib/claude-desktop/claude-desktop"] }], + "unsupported": "stdioOnly" + } + }, + { + "id": "claude-code", + "name": "Claude Code", + "icon": "claudecode", + "config": "claude-code", + "clientInfo": { "names": ["claude-code"], "prefixes": [] }, + "macos": { + "detect": [{ "binary": "claude", "paths": ["~/.local/bin/claude", "~/.claude/local/claude", "/opt/homebrew/bin/claude", "/usr/local/bin/claude"] }], + "entry": { "type": "stdio", "command": "{command}", "args": [], "env": {} }, + "install": [ + { "kind": "cli", "binary": "claude", "add": ["mcp", "add", "--scope", "user", "{name}", "--", "{command}"], "remove": ["mcp", "remove", "--scope", "user", "{name}"], "update": "removeThenAdd" } + ], + "applies": "newSession" + }, + "linux": { + "detect": [{ "binary": "claude", "paths": ["~/.local/bin/claude", "~/.claude/local/claude", "/usr/bin/claude", "/usr/local/bin/claude"] }], + "entry": { "type": "http", "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [ + { "kind": "cli", "binary": "claude", "add": ["mcp", "add", "--scope", "user", "--transport", "http", "{name}", "{url}", "--header", "Authorization: {authorization}"], "remove": ["mcp", "remove", "--scope", "user", "{name}"], "update": "removeThenAdd" } + ], + "applies": "newSession" + } + }, + { + "id": "chatgpt", + "name": "ChatGPT", + "icon": "openai", + "config": "codex", + "clientInfo": { "names": ["codex-mcp-client", "Codex"], "prefixes": [] }, + "macos": { + "detect": [{ "bundleId": "com.openai.codex" }], + "entry": { "command": "{command}", "args": [] }, + "install": [ + { "kind": "cli", "binary": "codex", "add": ["mcp", "add", "{name}", "--", "{command}"], "remove": ["mcp", "remove", "{name}"], "update": "add" }, + { "kind": "file" } + ], + "applies": "restartApp" + }, + "linux": { + "detect": [{ "binary": "chatgpt", "paths": ["/usr/bin/chatgpt"] }], + "entry": { "url": "{url}", "http_headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "restartApp" + } + }, + { + "id": "codex", + "name": "Codex CLI", + "icon": "openai", + "config": "codex", + "clientInfo": { "names": ["codex-mcp-client", "Codex"], "prefixes": [] }, + "macos": { + "detect": [{ "binary": "codex", "paths": ["~/.local/bin/codex", "/opt/homebrew/bin/codex", "/usr/local/bin/codex"] }], + "entry": { "command": "{command}", "args": [] }, + "install": [ + { "kind": "cli", "binary": "codex", "add": ["mcp", "add", "{name}", "--", "{command}"], "remove": ["mcp", "remove", "{name}"], "update": "add" }, + { "kind": "file" } + ], + "applies": "newSession" + }, + "linux": { + "detect": [{ "binary": "codex", "paths": ["~/.local/bin/codex", "/usr/bin/codex", "/usr/local/bin/codex"] }], + "entry": { "url": "{url}", "http_headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "newSession" + } + }, + { + "id": "chatgpt-classic", + "name": "ChatGPT Classic", + "icon": "openai", + "config": null, + "clientInfo": { "names": [], "prefixes": [] }, + "macos": { + "detect": [{ "bundleId": "com.openai.chat" }], + "unsupported": "remoteOnly" + } + }, + { + "id": "cursor", + "name": "Cursor", + "icon": "cursor", + "config": "cursor", + "clientInfo": { "names": ["cursor-vscode"], "prefixes": [] }, + "macos": { + "detect": [{ "bundleId": "com.todesktop.230313mzl4w4u92" }, { "path": "~/.cursor" }], + "entry": { "type": "stdio", "command": "{command}", "args": [] }, + "install": [ + { "kind": "deeplink", "scheme": "cursor", "url": "cursor://anysphere.cursor-deeplink/mcp/install?name={name}&config={entry|json|base64|uri}" }, + { "kind": "file" } + ], + "applies": "live" + }, + "linux": { + "detect": [{ "binary": "cursor", "paths": ["/usr/bin/cursor", "/usr/local/bin/cursor"] }, { "path": "~/.cursor" }], + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "vscode", + "name": "Visual Studio Code", + "icon": "vscode", + "config": "vscode", + "clientInfo": { "names": [], "prefixes": ["Visual Studio Code", "Visual-Studio-Code"] }, + "macos": { + "detect": [{ "bundleId": "com.microsoft.VSCode" }], + "entry": { "type": "stdio", "command": "{command}", "args": [] }, + "install": [ + { "kind": "deeplink", "scheme": "vscode", "url": "vscode:mcp/install?{entryWithName|json|uri}" }, + { "kind": "file" } + ], + "applies": "live" + }, + "linux": { + "detect": [{ "binary": "code", "paths": ["/usr/bin/code", "/usr/share/code/bin/code", "/snap/bin/code"] }], + "entry": { "type": "http", "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "vscode-insiders", + "name": "Visual Studio Code - Insiders", + "icon": "vscode", + "config": "vscode-insiders", + "clientInfo": { "names": [], "prefixes": ["Visual Studio Code - Insiders"] }, + "macos": { + "detect": [{ "bundleId": "com.microsoft.VSCodeInsiders" }], + "entry": { "type": "stdio", "command": "{command}", "args": [] }, + "install": [ + { "kind": "deeplink", "scheme": "vscode-insiders", "url": "vscode-insiders:mcp/install?{entryWithName|json|uri}" }, + { "kind": "file" } + ], + "applies": "live" + }, + "linux": { + "detect": [{ "binary": "code-insiders", "paths": ["/usr/bin/code-insiders", "/snap/bin/code-insiders"] }], + "entry": { "type": "http", "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "devin", + "name": "Devin Desktop", + "icon": "windsurf", + "config": "devin", + "clientInfo": { "names": ["windsurf-client", "Windsurf"], "prefixes": ["devin"] }, + "macos": { + "detect": [{ "bundleId": "com.exafunction.windsurf" }, { "binary": "devin", "paths": ["~/.local/bin/devin", "/opt/homebrew/bin/devin", "/usr/local/bin/devin"] }, { "path": "~/.config/devin" }], + "entry": { "command": "{command}", "args": [] }, + "install": [{ "kind": "file" }], + "applies": "reload" + }, + "linux": { + "detect": [{ "binary": "devin", "paths": ["~/.local/bin/devin", "/usr/bin/devin"] }, { "path": "~/.config/devin" }], + "entry": { "serverUrl": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "reload" + } + }, + { + "id": "zed", + "name": "Zed", + "icon": "zed", + "config": "zed", + "clientInfo": { "names": ["Zed"], "prefixes": [] }, + "macos": { + "detect": [{ "bundleId": "dev.zed.Zed" }, { "bundleId": "dev.zed.Zed-Preview" }], + "entry": { "command": "{command}", "args": [] }, + "install": [{ "kind": "file" }], + "applies": "live" + }, + "linux": { + "detect": [{ "binary": "zed", "paths": ["~/.local/bin/zed", "/usr/bin/zed", "/usr/bin/zeditor"] }, { "path": "~/.config/zed" }], + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "gemini", + "name": "Gemini CLI", + "icon": "googlegemini", + "config": "gemini", + "clientInfo": { "names": ["gemini-cli-mcp-client"], "prefixes": [] }, + "macos": { + "detect": [{ "binary": "gemini", "paths": ["/opt/homebrew/bin/gemini", "/usr/local/bin/gemini", "~/.npm-global/bin/gemini"] }, { "path": "~/.gemini" }], + "entry": { "command": "{command}", "args": [] }, + "install": [ + { "kind": "cli", "binary": "gemini", "add": ["mcp", "add", "--scope", "user", "{name}", "{command}"], "remove": ["mcp", "remove", "--scope", "user", "{name}"], "update": "add" }, + { "kind": "file" } + ], + "applies": "newSession" + }, + "linux": { + "detect": [{ "binary": "gemini", "paths": ["/usr/bin/gemini", "/usr/local/bin/gemini", "~/.npm-global/bin/gemini"] }, { "path": "~/.gemini" }], + "entry": { "httpUrl": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "newSession" + } + }, + { + "id": "copilot-cli", + "name": "GitHub Copilot CLI", + "icon": "githubcopilot", + "config": "copilot", + "clientInfo": { "names": ["copilot-cli", "github-copilot-developer"], "prefixes": [] }, + "macos": { + "detect": [{ "binary": "copilot", "paths": ["/opt/homebrew/bin/copilot", "/usr/local/bin/copilot", "~/.npm-global/bin/copilot"] }, { "path": "~/.copilot" }], + "entry": { "type": "local", "command": "{command}", "args": [], "tools": ["*"] }, + "install": [{ "kind": "file" }], + "applies": "newSession" + }, + "linux": { + "detect": [{ "binary": "copilot", "paths": ["/usr/bin/copilot", "/usr/local/bin/copilot", "~/.npm-global/bin/copilot"] }, { "path": "~/.copilot" }], + "entry": { "type": "http", "url": "{url}", "headers": { "Authorization": "{authorization}" }, "tools": ["*"] }, + "install": [{ "kind": "file" }], + "applies": "newSession" + } + }, + { + "id": "opencode", + "name": "opencode", + "icon": "opencode", + "config": "opencode", + "clientInfo": { "names": ["opencode"], "prefixes": [] }, + "macos": { + "detect": [{ "binary": "opencode", "paths": ["~/.opencode/bin/opencode", "/opt/homebrew/bin/opencode", "/usr/local/bin/opencode"] }, { "bundleId": "ai.opencode.desktop" }], + "entry": { "type": "local", "command": ["{command}"] }, + "install": [ + { "kind": "cli", "binary": "opencode", "add": ["mcp", "add", "{name}", "--global", "--", "{command}"] } + ], + "applies": "newSession" + }, + "linux": { + "detect": [{ "binary": "opencode", "paths": ["~/.opencode/bin/opencode", "/usr/bin/opencode", "/usr/local/bin/opencode"] }], + "entry": { "type": "remote", "url": "{url}", "oauth": false, "headers": { "Authorization": "{authorization}" } }, + "install": [], + "applies": "newSession" + } + }, + { + "id": "cline", + "name": "Cline", + "icon": "cline", + "config": "cline", + "clientInfo": { "names": ["Cline", "@cline/core"], "prefixes": [] }, + "macos": { + "detect": [{ "path": "~/.cline" }, { "binary": "cline", "paths": ["/opt/homebrew/bin/cline", "/usr/local/bin/cline", "~/.npm-global/bin/cline"] }], + "entry": { "command": "{command}", "args": [], "disabled": false }, + "install": [{ "kind": "file" }], + "applies": "live" + }, + "linux": { + "detect": [{ "path": "~/.cline" }, { "binary": "cline", "paths": ["/usr/bin/cline", "/usr/local/bin/cline", "~/.npm-global/bin/cline"] }], + "entry": { "type": "streamableHttp", "url": "{url}", "headers": { "Authorization": "{authorization}" }, "disabled": false }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "goose", + "name": "Goose", + "icon": "goose", + "config": "goose", + "clientInfo": { "names": ["goose-desktop", "goose-cli"], "prefixes": ["goose"] }, + "macos": { + "detect": [{ "bundleId": "com.electron.goose" }, { "binary": "goose", "paths": ["~/.local/bin/goose", "/opt/homebrew/bin/goose", "/usr/local/bin/goose"] }], + "entry": { "type": "stdio", "name": "{name}", "enabled": true, "cmd": "{command}", "args": [], "envs": {}, "env_keys": [], "timeout": 300 }, + "install": [ + { "kind": "deeplink", "scheme": "goose", "url": "goose://extension?cmd={command|uri}&id={name}&name=TablePro&description=TablePro%20databases" } + ], + "applies": "restartApp" + }, + "linux": { + "detect": [{ "binary": "goose", "paths": ["~/.local/bin/goose", "/usr/bin/goose", "/usr/local/bin/goose"] }, { "path": "~/.config/goose" }], + "entry": { "type": "streamable_http", "name": "{name}", "enabled": true, "uri": "{url}", "headers": { "Authorization": "{authorization}" }, "envs": {}, "env_keys": [], "timeout": 300 }, + "install": [], + "applies": "restartApp" + } + }, + { + "id": "lmstudio", + "name": "LM Studio", + "icon": "lmstudio", + "config": "lmstudio", + "clientInfo": { "names": [], "prefixes": ["lm-studio", "LM Studio"] }, + "macos": { + "detect": [{ "bundleId": "ai.elementlabs.lmstudio" }, { "path": "~/.lmstudio" }], + "entry": { "command": "{command}", "args": [] }, + "install": [ + { "kind": "deeplink", "scheme": "lmstudio", "url": "lmstudio://add_mcp?name={name}&config={entry|json|base64|uri}" }, + { "kind": "file" } + ], + "applies": "live" + }, + "linux": { + "detect": [{ "path": "~/.lmstudio" }], + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "kiro", + "name": "Kiro", + "icon": "kiro", + "config": "kiro", + "clientInfo": { "names": ["Q DEV CLI"], "prefixes": ["kiro", "Kiro"] }, + "macos": { + "detect": [{ "bundleId": "dev.kiro.desktop" }, { "binary": "kiro-cli", "paths": ["~/.local/bin/kiro-cli", "/opt/homebrew/bin/kiro-cli", "/usr/local/bin/kiro-cli"] }, { "path": "~/.kiro" }], + "entry": { "command": "{command}", "args": [], "disabled": false }, + "install": [{ "kind": "file" }], + "applies": "live" + }, + "linux": { + "detect": [{ "binary": "kiro", "paths": ["/usr/bin/kiro", "/usr/local/bin/kiro"] }, { "binary": "kiro-cli", "paths": ["~/.local/bin/kiro-cli", "/usr/bin/kiro-cli"] }, { "path": "~/.kiro" }], + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" }, "disabled": false }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "warp", + "name": "Warp", + "icon": "warp", + "config": "warp", + "clientInfo": { "names": [], "prefixes": ["dev.warp.Warp"] }, + "macos": { + "detect": [{ "bundleId": "dev.warp.Warp-Stable" }, { "bundleId": "dev.warp.Warp-Preview" }, { "path": "~/.warp" }], + "entry": { "command": "{command}", "args": [] }, + "install": [{ "kind": "file" }], + "applies": "live" + }, + "linux": { + "detect": [{ "binary": "warp-terminal", "paths": ["/usr/bin/warp-terminal"] }, { "path": "~/.warp" }], + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "live" + } + }, + { + "id": "junie", + "name": "Junie", + "icon": "jetbrains", + "config": "junie", + "clientInfo": { "names": [], "prefixes": ["junie", "Junie"] }, + "macos": { + "detect": [{ "path": "~/.junie" }, { "binary": "junie", "paths": ["~/.local/bin/junie", "/opt/homebrew/bin/junie", "/usr/local/bin/junie"] }], + "entry": { "command": "{command}", "args": [] }, + "install": [{ "kind": "file" }], + "applies": "newSession" + }, + "linux": { + "detect": [{ "path": "~/.junie" }, { "binary": "junie", "paths": ["~/.local/bin/junie", "/usr/bin/junie"] }], + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [{ "kind": "file" }], + "applies": "newSession" + } + }, + { + "id": "jetbrains-ai", + "name": "JetBrains AI Assistant", + "icon": "jetbrains", + "config": null, + "clientInfo": { "names": [], "prefixes": [] }, + "macos": { + "detect": [ + { "bundleId": "com.jetbrains.intellij" }, { "bundleId": "com.jetbrains.intellij.ce" }, { "bundleId": "com.jetbrains.pycharm" }, + { "bundleId": "com.jetbrains.pycharm.ce" }, { "bundleId": "com.jetbrains.WebStorm" }, { "bundleId": "com.jetbrains.goland" }, + { "bundleId": "com.jetbrains.datagrip" }, { "bundleId": "com.jetbrains.rider" }, { "bundleId": "com.jetbrains.PhpStorm" }, + { "bundleId": "com.jetbrains.rubymine" }, { "bundleId": "com.jetbrains.CLion" }, { "bundleId": "com.jetbrains.toolbox" } + ], + "entry": { "command": "{command}", "args": [] }, + "install": [], + "applies": "restartApp" + }, + "linux": { + "detect": [{ "path": "~/.config/JetBrains" }], + "entry": { "url": "{url}", "headers": { "Authorization": "{authorization}" } }, + "install": [], + "applies": "restartApp" + } + }, + { + "id": "raycast", + "name": "Raycast", + "icon": "raycast", + "config": null, + "clientInfo": { "names": [], "prefixes": ["raycast", "Raycast"] }, + "macos": { + "detect": [{ "bundleId": "com.raycast.macos" }], + "entry": { "type": "stdio", "command": "{command}", "args": [], "env": {} }, + "install": [ + { "kind": "deeplink", "scheme": "raycast", "url": "raycast://mcp/install?{entryWithName|json|uri}" } + ], + "applies": "live" + } + } + ] +} diff --git a/core/crates/mcp/src/clients/catalog.rs b/core/crates/mcp/src/clients/catalog.rs new file mode 100644 index 0000000000..7faa9d07f5 --- /dev/null +++ b/core/crates/mcp/src/clients/catalog.rs @@ -0,0 +1,450 @@ +use std::collections::{BTreeMap, HashSet}; + +use serde::Deserialize; + +use super::json_value::JsonValue; + +const BUNDLED: &str = include_str!("../../clients.json"); + +pub const SCHEMA_VERSION: u32 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClientPlatform { + Macos, + Linux, +} + +#[derive(Debug, thiserror::Error)] +pub enum CatalogError { + #[error("the client catalog has schema version {0}")] + UnsupportedSchema(u32), + #[error("the client catalog is not valid at line {line}, column {column}: {detail}")] + Malformed { line: usize, column: usize, detail: String }, + #[error("client {client} names config {config}, which the catalog does not define")] + UnknownConfig { client: String, config: String }, + #[error("client {0} is listed twice")] + DuplicateClient(String), +} + +impl CatalogError { + pub fn code(&self) -> &'static str { + match self { + Self::UnsupportedSchema(_) => "unsupported_schema", + Self::Malformed { .. } => "malformed", + Self::UnknownConfig { .. } => "unknown_config", + Self::DuplicateClient(_) => "duplicate_client", + } + } +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ClientCatalog { + pub schema_version: u32, + pub server_name: String, + configs: BTreeMap, + pub clients: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +struct ConfigSet { + macos: Option, + linux: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfigLocation { + pub path: String, + pub format: ConfigFormat, + pub key_path: Vec, + #[serde(default = "writable_by_default")] + pub writable: bool, + // An older layout of the same file, read like `key_path` and never + // written. + #[serde(default)] + pub alternate_key_paths: Vec>, + #[serde(default)] + pub other_scopes: Vec>, +} + +fn writable_by_default() -> bool { + true +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ConfigFormat { + Json, + Jsonc, + Toml, + Yaml, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ClientDefinition { + pub id: String, + pub name: String, + pub icon: String, + pub config: Option, + pub client_info: ClientInfoNames, + macos: Option, + linux: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ClientInfoNames { + #[serde(default)] + pub names: Vec, + #[serde(default)] + pub prefixes: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PlatformSpec { + #[serde(default)] + pub detect: Vec, + pub entry: Option, + #[serde(default)] + pub install: Vec, + pub applies: Option, + pub unsupported: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(from = "DetectRuleText")] +pub enum DetectRule { + BundleId(String), + Binary { name: String, paths: Vec }, + Path(String), +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum DetectRuleText { + BundleId(BundleIdRule), + Binary(BinaryRule), + Path(PathRule), +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct BundleIdRule { + bundle_id: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct BinaryRule { + binary: String, + paths: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PathRule { + path: String, +} + +impl From for DetectRule { + fn from(text: DetectRuleText) -> Self { + match text { + DetectRuleText::BundleId(rule) => Self::BundleId(rule.bundle_id), + DetectRuleText::Binary(rule) => Self::Binary { + name: rule.binary, + paths: rule.paths, + }, + DetectRuleText::Path(rule) => Self::Path(rule.path), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum InstallMethod { + Deeplink(DeeplinkInstall), + Cli(CliInstall), + File, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DeeplinkInstall { + pub scheme: String, + pub url: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CliInstall { + pub binary: String, + pub add: Vec, + pub remove: Option>, + #[serde(default)] + pub update: CliUpdate, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CliUpdate { + #[default] + Add, + RemoveThenAdd, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Applies { + Live, + NewSession, + RestartApp, + Reload, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum UnsupportedReason { + RemoteOnly, + StdioOnly, +} + +impl ClientCatalog { + // The catalog both apps ship, compiled into this crate. + pub fn bundled() -> Result { + Self::parse(BUNDLED) + } + + pub fn parse(text: &str) -> Result { + let catalog: Self = serde_json::from_str(text).map_err(|error| CatalogError::Malformed { + line: error.line(), + column: error.column(), + detail: error.to_string(), + })?; + if catalog.schema_version != SCHEMA_VERSION { + return Err(CatalogError::UnsupportedSchema(catalog.schema_version)); + } + let mut ids = HashSet::new(); + for client in &catalog.clients { + if !ids.insert(client.id.as_str()) { + return Err(CatalogError::DuplicateClient(client.id.clone())); + } + if let Some(config) = &client.config + && !catalog.configs.contains_key(config) + { + return Err(CatalogError::UnknownConfig { + client: client.id.clone(), + config: config.clone(), + }); + } + } + Ok(catalog) + } + + pub fn client(&self, id: &str) -> Option<&ClientDefinition> { + self.clients.iter().find(|client| client.id == id) + } + + // A client without an entry for the platform is not shown there. + pub fn clients_on(&self, platform: ClientPlatform) -> impl Iterator { + self.clients + .iter() + .filter(move |client| client.spec(platform).is_some()) + } + + pub fn location(&self, client: &ClientDefinition, platform: ClientPlatform) -> Option<&ConfigLocation> { + let set = self.configs.get(client.config.as_deref()?)?; + match platform { + ClientPlatform::Macos => set.macos.as_ref(), + ClientPlatform::Linux => set.linux.as_ref(), + } + } + + // Exact names first, ignoring case, then prefixes, the longest first. + // Several clients can share one engine, so every match is returned. + pub fn clients_for_client_info(&self, name: &str, platform: ClientPlatform) -> Vec<&ClientDefinition> { + let name = name.trim().to_lowercase(); + if name.is_empty() { + return Vec::new(); + } + let exact: Vec<&ClientDefinition> = self + .clients_on(platform) + .filter(|client| { + client + .client_info + .names + .iter() + .any(|known| known.to_lowercase() == name) + }) + .collect(); + if !exact.is_empty() { + return exact; + } + let mut prefixed: Vec<(usize, &ClientDefinition)> = self + .clients_on(platform) + .filter_map(|client| { + client + .client_info + .prefixes + .iter() + .map(|prefix| prefix.to_lowercase()) + .filter(|prefix| !prefix.is_empty() && name.starts_with(prefix.as_str())) + .map(|prefix| prefix.len()) + .max() + .map(|length| (length, client)) + }) + .collect(); + prefixed.sort_by_key(|(length, _)| std::cmp::Reverse(*length)); + prefixed.into_iter().map(|(_, client)| client).collect() + } +} + +impl ClientDefinition { + pub fn spec(&self, platform: ClientPlatform) -> Option<&PlatformSpec> { + match platform { + ClientPlatform::Macos => self.macos.as_ref(), + ClientPlatform::Linux => self.linux.as_ref(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bundled() -> ClientCatalog { + ClientCatalog::bundled().expect("the bundled catalog") + } + + #[test] + fn the_bundled_catalog_parses() { + let catalog = bundled(); + + assert_eq!(catalog.schema_version, SCHEMA_VERSION); + assert_eq!(catalog.server_name, "tablepro"); + assert!(catalog.client("claude-code").is_some()); + } + + #[test] + fn every_client_on_a_platform_is_either_unsupported_or_has_an_entry() { + let catalog = bundled(); + + for platform in [ClientPlatform::Macos, ClientPlatform::Linux] { + for client in catalog.clients_on(platform) { + let spec = client.spec(platform).expect("a spec"); + assert!( + spec.unsupported.is_some() != spec.entry.is_some(), + "{} on {platform:?}", + client.id + ); + } + } + } + + #[test] + fn a_file_install_needs_a_writable_location_on_its_platform() { + let catalog = bundled(); + + for platform in [ClientPlatform::Macos, ClientPlatform::Linux] { + for client in catalog.clients_on(platform) { + let spec = client.spec(platform).expect("a spec"); + if spec.install.contains(&InstallMethod::File) { + let location = catalog.location(client, platform); + assert!( + location.is_some_and(|location| location.writable), + "{} on {platform:?}", + client.id + ); + } + } + } + } + + #[test] + fn linux_entries_reach_the_server_over_http_and_never_start_a_program() { + let catalog = bundled(); + + for client in catalog.clients_on(ClientPlatform::Linux) { + let Some(entry) = &client.spec(ClientPlatform::Linux).expect("a spec").entry else { + continue; + }; + let text = entry.to_compact(); + assert!(text.contains("{url}"), "{}", client.id); + assert!(text.contains("{authorization}"), "{}", client.id); + assert!(!text.contains("{command}"), "{}", client.id); + } + } + + #[test] + fn linux_offers_no_deeplink_so_the_token_never_goes_into_a_url() { + let catalog = bundled(); + + for client in catalog.clients_on(ClientPlatform::Linux) { + let spec = client.spec(ClientPlatform::Linux).expect("a spec"); + assert!( + !spec + .install + .iter() + .any(|method| matches!(method, InstallMethod::Deeplink(_))), + "{}", + client.id + ); + } + } + + #[test] + fn client_info_names_match_exactly_before_prefixes_and_ignore_case() { + let catalog = bundled(); + let ids = |name: &str| -> Vec { + catalog + .clients_for_client_info(name, ClientPlatform::Linux) + .into_iter() + .map(|client| client.id.clone()) + .collect() + }; + + assert_eq!(ids("claude-code"), ["claude-code"]); + assert_eq!(ids("ZED"), ["zed"]); + assert_eq!(ids("codex-mcp-client"), ["chatgpt", "codex"]); + assert_eq!(ids("Visual Studio Code"), ["vscode"]); + assert_eq!(ids("Visual Studio Code - Insiders"), ["vscode-insiders", "vscode"]); + assert_eq!(ids("goose-cli"), ["goose"]); + assert!(ids("raycast").is_empty(), "Raycast has no Linux build"); + assert!(ids("").is_empty()); + } + + #[test] + fn opencode_reads_its_older_layout_as_an_alternate_key_path() { + let catalog = bundled(); + let opencode = catalog.client("opencode").expect("opencode"); + + for platform in [ClientPlatform::Macos, ClientPlatform::Linux] { + let location = catalog.location(opencode, platform).expect("a location"); + assert_eq!(location.key_path, ["mcp", "servers"]); + assert_eq!(location.alternate_key_paths, [["mcp"]]); + assert!(location.other_scopes.is_empty()); + } + } + + #[test] + fn a_client_naming_an_unknown_config_is_refused() { + let text = r#"{"schemaVersion": 1, "serverName": "tablepro", "configs": {}, + "clients": [{"id": "x", "name": "X", "icon": "x", "config": "missing", "clientInfo": {}}]}"#; + + let error = ClientCatalog::parse(text).expect_err("an unknown config"); + + assert_eq!(error.code(), "unknown_config"); + } + + #[test] + fn a_misspelled_field_is_refused() { + let text = r#"{"schemaVersion": 1, "serverName": "tablepro", "configs": {}, + "clients": [{"id": "x", "name": "X", "icon": "x", "config": null, "clientInfo": {}, + "linux": {"detect": [{"binary": "x", "path": []}]}}]}"#; + + assert_eq!(ClientCatalog::parse(text).expect_err("a typo").code(), "malformed"); + } +} diff --git a/core/crates/mcp/src/clients/config_edit.rs b/core/crates/mcp/src/clients/config_edit.rs new file mode 100644 index 0000000000..491a9b04b8 --- /dev/null +++ b/core/crates/mcp/src/clients/config_edit.rs @@ -0,0 +1,207 @@ +use super::catalog::ConfigFormat; +use super::json_value::JsonValue; +use super::{jsonc, merge, toml_table}; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ConfigEditError { + #[error("the file is not valid at byte {offset:?}")] + InvalidSyntax { offset: Option }, + #[error("{path:?} appears more than once")] + DuplicateKey { path: Vec }, + #[error("{path:?} is not an object")] + NotAnObject { path: Vec }, + #[error("{path:?} is written in a form TablePro does not edit")] + UnsupportedShape { path: Vec }, + #[error("the entry holds a value the file format cannot hold")] + UnsupportedValue, + #[error("files in {0:?} are not edited")] + UnsupportedFormat(ConfigFormat), +} + +impl ConfigEditError { + pub fn code(&self) -> &'static str { + match self { + Self::InvalidSyntax { .. } => "invalid_syntax", + Self::DuplicateKey { .. } => "duplicate_key", + Self::NotAnObject { .. } => "not_an_object", + Self::UnsupportedShape { .. } => "unsupported_shape", + Self::UnsupportedValue => "unsupported_value", + Self::UnsupportedFormat(_) => "unsupported_format", + } + } +} + +// The server `name` in the object at `key_path`. Empty text reads as an +// empty object. +pub fn read_member( + format: ConfigFormat, + text: &str, + key_path: &[String], + name: &str, +) -> Result, ConfigEditError> { + match format { + ConfigFormat::Json | ConfigFormat::Jsonc => jsonc::member(text, key_path, name), + ConfigFormat::Toml => toml_table::member(text, key_path, name), + ConfigFormat::Yaml => Err(ConfigEditError::UnsupportedFormat(format)), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Upsert { + // Writes each member given and keeps the entry's others. + Merge, + Replace, +} + +// Creates what is missing on `key_path` and keeps the rest of the file. +// `template`, the catalog entry `value` was rendered from, decides which +// members of an entry already there are written over. +pub fn upsert_member( + format: ConfigFormat, + text: &str, + key_path: &[String], + name: &str, + value: &JsonValue, + template: &JsonValue, +) -> Result { + let (value, mode) = match read_member(format, text, key_path, name)? { + Some(existing) if merge::transport_differs(&existing, template) => ( + merge::replace_keeping_choices(&existing, value, template), + Upsert::Replace, + ), + Some(existing) => (merge::update_for(&existing, value, template), Upsert::Merge), + None => (value.clone(), Upsert::Merge), + }; + match format { + ConfigFormat::Json | ConfigFormat::Jsonc => jsonc::upserting(text, key_path, name, &value, mode), + ConfigFormat::Toml => toml_table::upserting(text, key_path, name, &value, mode), + ConfigFormat::Yaml => Err(ConfigEditError::UnsupportedFormat(format)), + } +} + +// The text unchanged when the server is not there. +pub fn remove_member( + format: ConfigFormat, + text: &str, + key_path: &[String], + name: &str, +) -> Result { + match format { + ConfigFormat::Json | ConfigFormat::Jsonc => jsonc::removing(text, key_path, name), + ConfigFormat::Toml => toml_table::removing(text, key_path, name), + ConfigFormat::Yaml => Err(ConfigEditError::UnsupportedFormat(format)), + } +} + +// Every server `name` in the objects `scope` reaches; `*` in the scope +// stands for any key at that level. +pub fn members_in_scope( + format: ConfigFormat, + text: &str, + scope: &[String], + name: &str, +) -> Result, ConfigEditError> { + match format { + ConfigFormat::Json | ConfigFormat::Jsonc => jsonc::members_in_scope(text, scope, name), + ConfigFormat::Toml => toml_table::members_in_scope(text, scope, name), + ConfigFormat::Yaml => Err(ConfigEditError::UnsupportedFormat(format)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(text: &str) -> JsonValue { + serde_json::from_str(text).expect("JSON") + } + + fn servers() -> Vec { + vec!["mcpServers".to_owned()] + } + + fn copilot() -> (JsonValue, JsonValue) { + ( + parse( + r#"{"type": "http", "url": "{url}", "headers": {"Authorization": "{authorization}"}, "tools": ["*"]}"#, + ), + parse( + r#"{"type": "http", "url": "http://127.0.0.1:23508/mcp", "headers": {"Authorization": "Bearer tp_new"}, + "tools": ["*"]}"#, + ), + ) + } + + #[test] + fn an_update_never_widens_the_tools_or_turns_an_entry_back_on() { + let (template, rendered) = copilot(); + let text = "{\n \"mcpServers\": {\n \"tablepro\": {\n \"type\": \"http\",\n \ +\"url\": \"http://127.0.0.1:1/mcp\",\n \"headers\": {\"Authorization\": \"Bearer tp_old\"},\n \ +// only this one\n \"tools\": [\"list_connections\"],\n \"disabled\": true\n }\n }\n}\n"; + + let edited = + upsert_member(ConfigFormat::Jsonc, text, &servers(), "tablepro", &rendered, &template).expect("an edit"); + + assert_eq!( + edited, + "{\n \"mcpServers\": {\n \"tablepro\": {\n \"type\": \"http\",\n \ +\"url\": \"http://127.0.0.1:23508/mcp\",\n \"headers\": {\"Authorization\": \"Bearer tp_new\"},\n \ +// only this one\n \"tools\": [\"list_connections\"],\n \"disabled\": true\n }\n }\n}\n" + ); + } + + #[test] + fn a_new_entry_gets_every_member_the_template_has() { + let (template, rendered) = copilot(); + + let edited = + upsert_member(ConfigFormat::Json, "{}", &servers(), "tablepro", &rendered, &template).expect("an edit"); + + assert_eq!( + read_member(ConfigFormat::Json, &edited, &servers(), "tablepro").expect("readable"), + Some(rendered) + ); + } + + #[test] + fn a_stdio_entry_is_replaced_where_it_stands_keeping_the_users_tools() { + let (template, rendered) = copilot(); + let text = r#"{"mcpServers": {"a": {}, "tablepro": {"command": "/x/tablepro-mcp", "args": ["-v"], "tools": ["q"]}, "b": {}}}"#; + + let edited = + upsert_member(ConfigFormat::Json, text, &servers(), "tablepro", &rendered, &template).expect("an edit"); + + assert_eq!( + edited, + r#"{"mcpServers": {"a": {}, "tablepro": {"type":"http","url":"http://127.0.0.1:23508/mcp","headers":{"Authorization":"Bearer tp_new"},"tools":["q"]}, "b": {}}}"# + ); + } + + #[test] + fn a_codex_table_keeps_its_restrictions_and_a_stdio_one_is_replaced_whole() { + let template = + parse(r#"{"url": "{url}", "http_headers": {"Authorization": "{authorization}"}, "enabled": true}"#); + let rendered = + parse(r#"{"url": "http://new", "http_headers": {"Authorization": "Bearer tp_new"}, "enabled": true}"#); + let path = vec!["mcp_servers".to_owned()]; + let off = "[mcp_servers.tablepro]\nurl = \"http://old\"\nenabled = false\n\n\ +[mcp_servers.tablepro.http_headers]\nAuthorization = \"Bearer tp_old\"\n"; + let stdio = "# mine\n[mcp_servers.tablepro]\ncommand = \"/x/tablepro-mcp\"\nargs = [\"-v\"]\n\n\ +[mcp_servers.tablepro.env]\nA = \"1\"\n\n[profile]\nx = 1\n"; + + let kept = upsert_member(ConfigFormat::Toml, off, &path, "tablepro", &rendered, &template).expect("an edit"); + let replaced = + upsert_member(ConfigFormat::Toml, stdio, &path, "tablepro", &rendered, &template).expect("an edit"); + + assert_eq!( + kept, + "[mcp_servers.tablepro]\nurl = \"http://new\"\nenabled = false\n\n\ +[mcp_servers.tablepro.http_headers]\nAuthorization = \"Bearer tp_new\"\n" + ); + assert_eq!( + replaced, + "# mine\n[mcp_servers.tablepro]\nurl = \"http://new\"\nhttp_headers = { Authorization = \"Bearer tp_new\" }\n\ +enabled = true\n\n[profile]\nx = 1\n" + ); + } +} diff --git a/core/crates/mcp/src/clients/json_value.rs b/core/crates/mcp/src/clients/json_value.rs new file mode 100644 index 0000000000..c3d1d5ce04 --- /dev/null +++ b/core/crates/mcp/src/clients/json_value.rs @@ -0,0 +1,282 @@ +use std::fmt; + +use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; + +// A serde_json map sorts its keys, and a client's entry has to keep the +// catalog's order, so objects are kept as a list of members. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum JsonValue { + Null, + Bool(bool), + Number(serde_json::Number), + String(String), + Array(Vec), + Object(Vec<(String, JsonValue)>), +} + +impl JsonValue { + pub fn get(&self, key: &str) -> Option<&JsonValue> { + match self { + Self::Object(members) => members.iter().find(|(name, _)| name == key).map(|(_, value)| value), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + Self::String(text) => Some(text), + _ => None, + } + } + + // Whether every member `wanted` has is here with the same value, as + // an update that keeps the user's own members leaves an entry. Below + // the top, as in a header map, a key matches ignoring case. + pub fn holds(&self, wanted: &JsonValue) -> bool { + holds(self, wanted, false) + } + + pub fn to_compact(&self) -> String { + let mut out = String::new(); + write_compact(self, &mut out); + out + } + + // `base` is the indent of the line the value starts on; nested lines + // add one `unit` per level. + pub fn to_pretty(&self, unit: &str, base: &str) -> String { + let mut out = String::new(); + write_pretty(self, unit, base, &mut out); + out + } +} + +fn holds(actual: &JsonValue, wanted: &JsonValue, nested: bool) -> bool { + let (JsonValue::Object(have), JsonValue::Object(want)) = (actual, wanted) else { + return actual == wanted; + }; + want.iter().all(|(key, value)| { + have.iter() + .find(|(name, _)| name == key) + .or_else(|| have.iter().find(|(name, _)| nested && name.eq_ignore_ascii_case(key))) + .is_some_and(|(_, found)| holds(found, value, true)) + }) +} + +fn write_compact(value: &JsonValue, out: &mut String) { + match value { + JsonValue::Array(items) => { + out.push('['); + for (index, item) in items.iter().enumerate() { + if index > 0 { + out.push(','); + } + write_compact(item, out); + } + out.push(']'); + } + JsonValue::Object(members) => { + out.push('{'); + for (index, (name, member)) in members.iter().enumerate() { + if index > 0 { + out.push(','); + } + out.push_str("e(name)); + out.push(':'); + write_compact(member, out); + } + out.push('}'); + } + scalar => write_scalar(scalar, out), + } +} + +fn write_pretty(value: &JsonValue, unit: &str, base: &str, out: &mut String) { + let inner = format!("{base}{unit}"); + match value { + JsonValue::Array(items) if !items.is_empty() => { + out.push('['); + for (index, item) in items.iter().enumerate() { + out.push_str(if index > 0 { ",\n" } else { "\n" }); + out.push_str(&inner); + write_pretty(item, unit, &inner, out); + } + out.push('\n'); + out.push_str(base); + out.push(']'); + } + JsonValue::Object(members) if !members.is_empty() => { + out.push('{'); + for (index, (name, member)) in members.iter().enumerate() { + out.push_str(if index > 0 { ",\n" } else { "\n" }); + out.push_str(&inner); + out.push_str("e(name)); + out.push_str(": "); + write_pretty(member, unit, &inner, out); + } + out.push('\n'); + out.push_str(base); + out.push('}'); + } + JsonValue::Array(_) => out.push_str("[]"), + JsonValue::Object(_) => out.push_str("{}"), + scalar => write_scalar(scalar, out), + } +} + +fn write_scalar(value: &JsonValue, out: &mut String) { + match value { + JsonValue::Null => out.push_str("null"), + JsonValue::Bool(true) => out.push_str("true"), + JsonValue::Bool(false) => out.push_str("false"), + JsonValue::Number(number) => out.push_str(&number.to_string()), + JsonValue::String(text) => out.push_str("e(text)), + JsonValue::Array(_) | JsonValue::Object(_) => write_compact(value, out), + } +} + +pub(crate) fn quote(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 2); + out.push('"'); + for character in text.chars() { + match character { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{8}' => out.push_str("\\b"), + '\u{c}' => out.push_str("\\f"), + control if u32::from(control) < 0x20 => out.push_str(&format!("\\u{:04x}", u32::from(control))), + other => out.push(other), + } + } + out.push('"'); + out +} + +impl<'de> Deserialize<'de> for JsonValue { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(JsonValueVisitor) + } +} + +struct JsonValueVisitor; + +impl<'de> Visitor<'de> for JsonValueVisitor { + type Value = JsonValue; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a JSON value") + } + + fn visit_bool(self, value: bool) -> Result { + Ok(JsonValue::Bool(value)) + } + + fn visit_i64(self, value: i64) -> Result { + Ok(JsonValue::Number(value.into())) + } + + fn visit_u64(self, value: u64) -> Result { + Ok(JsonValue::Number(value.into())) + } + + fn visit_f64(self, value: f64) -> Result { + serde_json::Number::from_f64(value) + .map(JsonValue::Number) + .ok_or_else(|| E::custom("a number JSON cannot hold")) + } + + fn visit_str(self, value: &str) -> Result { + Ok(JsonValue::String(value.to_owned())) + } + + fn visit_string(self, value: String) -> Result { + Ok(JsonValue::String(value)) + } + + fn visit_unit(self) -> Result { + Ok(JsonValue::Null) + } + + fn visit_none(self) -> Result { + Ok(JsonValue::Null) + } + + fn visit_some>(self, deserializer: D) -> Result { + JsonValue::deserialize(deserializer) + } + + fn visit_seq>(self, mut seq: A) -> Result { + let mut items = Vec::new(); + while let Some(item) = seq.next_element()? { + items.push(item); + } + Ok(JsonValue::Array(items)) + } + + fn visit_map>(self, mut map: A) -> Result { + let mut members: Vec<(String, JsonValue)> = Vec::new(); + while let Some((name, value)) = map.next_entry::()? { + if members.iter().any(|(existing, _)| *existing == name) { + return Err(de::Error::custom(format!("duplicate key {name}"))); + } + members.push((name, value)); + } + Ok(JsonValue::Object(members)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(text: &str) -> JsonValue { + serde_json::from_str(text).expect("a JSON value") + } + + #[test] + fn members_keep_the_order_they_were_written_in() { + let value = parse(r#"{"zeta": 1, "alpha": [true, null], "mid": {"b": "x", "a": 2.5}}"#); + + assert_eq!( + value.to_compact(), + r#"{"zeta":1,"alpha":[true,null],"mid":{"b":"x","a":2.5}}"# + ); + } + + #[test] + fn pretty_output_indents_each_level_and_keeps_empty_containers_on_one_line() { + let value = parse(r#"{"url": "u", "args": [], "env": {}, "tools": ["*"]}"#); + + assert_eq!( + value.to_pretty(" ", ""), + "{\n \"url\": \"u\",\n \"args\": [],\n \"env\": {},\n \"tools\": [\n \"*\"\n ]\n}" + ); + } + + #[test] + fn strings_are_escaped_as_json_requires() { + assert_eq!(quote("a\"b\\c\nd\u{1}"), r#""a\"b\\c\nd\u0001""#); + } + + #[test] + fn an_entry_holds_what_was_written_beside_the_users_own_members() { + let written = parse(r#"{"url": "u", "timeout": 30, "headers": {"authorization": "B", "X-Team": "d"}}"#); + + assert!(written.holds(&parse(r#"{"url": "u", "headers": {"Authorization": "B"}}"#))); + assert!(!written.holds(&parse(r#"{"url": "v", "headers": {"Authorization": "B"}}"#))); + assert!( + !written.holds(&parse(r#"{"URL": "u"}"#)), + "a key on top matches exactly" + ); + assert!(!written.holds(&parse(r#"{"headers": {"Authorization": "C"}}"#))); + assert!(parse("[1]").holds(&parse("[1]")) && !parse("[1, 2]").holds(&parse("[1]"))); + } + + #[test] + fn a_duplicate_key_is_refused() { + assert!(serde_json::from_str::(r#"{"a": 1, "a": 2}"#).is_err()); + } +} diff --git a/core/crates/mcp/src/clients/jsonc.rs b/core/crates/mcp/src/clients/jsonc.rs new file mode 100644 index 0000000000..f88e39a4d8 --- /dev/null +++ b/core/crates/mcp/src/clients/jsonc.rs @@ -0,0 +1,1027 @@ +use super::config_edit::{ConfigEditError, Upsert}; +use super::json_value::{JsonValue, quote}; + +// Deeper than any config file nests; a file past it is refused rather +// than parsed on an ever deeper stack. +const MAX_DEPTH: usize = 256; + +const DEFAULT_INDENT: &str = " "; + +const REPLACEMENT: u32 = 0xFFFD; + +// Edits splice the text, so comments, key order, indentation and every +// byte outside the edited member stay as the user wrote them. +pub(crate) fn member(text: &str, key_path: &[String], name: &str) -> Result, ConfigEditError> { + let document = Document::parse(text)?; + match document.walk(key_path)? { + Walk::Found(object) => Ok(find(object, name, key_path)?.map(|member| member.value.to_value())), + Walk::Missing { .. } | Walk::NoRoot => Ok(None), + } +} + +pub(crate) fn upserting( + text: &str, + key_path: &[String], + name: &str, + value: &JsonValue, + mode: Upsert, +) -> Result { + let document = Document::parse(text)?; + let edits = match document.walk(key_path)? { + Walk::NoRoot => return Ok(document.new_root(&nest(key_path, name, value))), + Walk::Found(object) => match find(object, name, key_path)? { + Some(member) if mode == Upsert::Replace => vec![document.replace_value(object, member, value)], + Some(member) => { + let mut path = key_path.to_vec(); + path.push(name.to_owned()); + let mut edits = Vec::new(); + document.update(object, member, value, &path, false, &mut edits)?; + edits + } + None => document.insert_members(object, &[(name.to_owned(), value.clone())]), + }, + Walk::Missing { deepest, depth } => { + let wrapped = nest(&key_path[depth + 1..], name, value); + document.insert_members(deepest, &[(key_path[depth].clone(), wrapped)]) + } + }; + Ok(splice(text, edits)) +} + +pub(crate) fn removing(text: &str, key_path: &[String], name: &str) -> Result { + let document = Document::parse(text)?; + let Walk::Found(object) = document.walk(key_path)? else { + return Ok(text.to_owned()); + }; + if find(object, name, key_path)?.is_none() { + return Ok(text.to_owned()); + } + let index = object + .members + .iter() + .position(|member| member.key == name) + .unwrap_or_default(); + document.remove_member(object, index) +} + +// `*` in the scope stands for any key at that level. +pub(crate) fn members_in_scope(text: &str, scope: &[String], name: &str) -> Result, ConfigEditError> { + let document = Document::parse(text)?; + let mut found = Vec::new(); + if let Some(root) = document.root_object()? { + collect_in_scope(root, scope, name, &mut found); + } + Ok(found) +} + +fn collect_in_scope(object: &ObjectNode, scope: &[String], name: &str, found: &mut Vec) { + let Some((first, rest)) = scope.split_first() else { + found.extend( + object + .members + .iter() + .filter(|member| member.key == name) + .map(|member| member.value.to_value()), + ); + return; + }; + for member in object + .members + .iter() + .filter(|member| first == "*" || member.key == *first) + { + if let Node::Object(inner) = &member.value { + collect_in_scope(inner, rest, name, found); + } + } +} + +fn nest(keys: &[String], name: &str, value: &JsonValue) -> JsonValue { + let inner = JsonValue::Object(vec![(name.to_owned(), value.clone())]); + keys.iter() + .rev() + .fold(inner, |value, key| JsonValue::Object(vec![(key.clone(), value)])) +} + +fn find<'n>(object: &'n ObjectNode, key: &str, path: &[String]) -> Result, ConfigEditError> { + let mut found = object.members.iter().filter(|member| member.key == key); + let first = found.next(); + if first.is_some() && found.next().is_some() { + let mut path = path.to_vec(); + path.push(key.to_owned()); + return Err(ConfigEditError::DuplicateKey { path }); + } + Ok(first) +} + +enum Node { + Object(ObjectNode), + Array(ArrayNode), + Scalar(ScalarNode), +} + +struct ObjectNode { + open: usize, + close: usize, + members: Vec, +} + +struct Member { + key: String, + key_start: usize, + value: Node, + comma: Option, +} + +struct ArrayNode { + open: usize, + close: usize, + items: Vec, +} + +struct ScalarNode { + start: usize, + end: usize, + value: JsonValue, +} + +impl Node { + fn start(&self) -> usize { + match self { + Self::Object(object) => object.open, + Self::Array(array) => array.open, + Self::Scalar(scalar) => scalar.start, + } + } + + fn end(&self) -> usize { + match self { + Self::Object(object) => object.close + 1, + Self::Array(array) => array.close + 1, + Self::Scalar(scalar) => scalar.end, + } + } + + fn to_value(&self) -> JsonValue { + match self { + Self::Object(object) => JsonValue::Object( + object + .members + .iter() + .map(|member| (member.key.clone(), member.value.to_value())) + .collect(), + ), + Self::Array(array) => JsonValue::Array(array.items.iter().map(Node::to_value).collect()), + Self::Scalar(scalar) => scalar.value.clone(), + } + } +} + +enum Walk<'n> { + NoRoot, + Found(&'n ObjectNode), + // The keys from `depth` on are missing below `deepest`. + Missing { deepest: &'n ObjectNode, depth: usize }, +} + +struct Document<'a> { + text: &'a str, + root: Option, +} + +impl<'a> Document<'a> { + fn parse(text: &'a str) -> Result { + let mut parser = Parser { + text, + bytes: text.as_bytes(), + pos: if text.starts_with('\u{feff}') { 3 } else { 0 }, + }; + parser.skip_trivia()?; + if parser.pos == text.len() { + return Ok(Self { text, root: None }); + } + let root = parser.value(0)?; + parser.skip_trivia()?; + if parser.pos != text.len() { + return Err(parser.error()); + } + Ok(Self { text, root: Some(root) }) + } + + fn root_object(&self) -> Result, ConfigEditError> { + match &self.root { + None => Ok(None), + Some(Node::Object(object)) => Ok(Some(object)), + Some(_) => Err(ConfigEditError::NotAnObject { path: Vec::new() }), + } + } + + fn walk(&self, key_path: &[String]) -> Result, ConfigEditError> { + let Some(mut object) = self.root_object()? else { + return Ok(Walk::NoRoot); + }; + for (depth, key) in key_path.iter().enumerate() { + match find(object, key, &key_path[..depth])? { + None => return Ok(Walk::Missing { deepest: object, depth }), + Some(member) => match &member.value { + Node::Object(inner) => object = inner, + _ => { + return Err(ConfigEditError::NotAnObject { + path: key_path[..=depth].to_vec(), + }); + } + }, + } + } + Ok(Walk::Found(object)) + } + + fn new_root(&self, whole: &JsonValue) -> String { + let kept = self.text.trim_end(); + let separator = if kept.trim_start_matches('\u{feff}').is_empty() { + "" + } else { + "\n" + }; + format!("{kept}{separator}{}\n", whole.to_pretty(DEFAULT_INDENT, "")) + } + + // Rewrites only the members given, so the user's other members and + // their comments stay. Below the top of the entry, as in a header + // map, a key matches ignoring case. + fn update( + &self, + parent: &ObjectNode, + member: &Member, + value: &JsonValue, + path: &[String], + nested: bool, + edits: &mut Vec, + ) -> Result<(), ConfigEditError> { + let (Node::Object(existing), JsonValue::Object(wanted)) = (&member.value, value) else { + edits.push(self.replace_value(parent, member, value)); + return Ok(()); + }; + let mut missing = Vec::new(); + for (key, wanted) in wanted { + let found = match find(existing, key, path)? { + Some(found) => Some(found), + None if nested => existing + .members + .iter() + .find(|candidate| candidate.key.eq_ignore_ascii_case(key)), + None => None, + }; + match found { + Some(found) => { + let mut inner = path.to_vec(); + inner.push(found.key.clone()); + self.update(existing, found, wanted, &inner, true, edits)?; + } + None => missing.push((key.clone(), wanted.clone())), + } + } + if !missing.is_empty() { + edits.extend(self.insert_members(existing, &missing)); + } + Ok(()) + } + + fn replace_value(&self, parent: &ObjectNode, member: &Member, value: &JsonValue) -> Edit { + let rendered = match is_single_line(self.text, parent) { + true => value.to_compact(), + false => value.to_pretty(&self.indent_unit(), line_indent(self.text, member.key_start)), + }; + (member.value.start(), member.value.end(), rendered) + } + + fn insert_members(&self, object: &ObjectNode, members: &[(String, JsonValue)]) -> Vec { + let text = self.text; + let unit = self.indent_unit(); + let open_indent = line_indent(text, object.open); + let pretty = |indent: &str| { + members + .iter() + .map(|(name, value)| format!("{}: {}", quote(name), value.to_pretty(&unit, indent))) + .collect::>() + .join(&format!(",\n{indent}")) + }; + let Some(last) = object.members.last() else { + let indent = format!("{open_indent}{unit}"); + let rendered = pretty(&indent); + if text[object.open + 1..object.close].trim().is_empty() { + let filled = format!("\n{indent}{rendered}\n{open_indent}"); + return vec![(object.open + 1, object.close, filled)]; + } + if starts_line(text, object.close) { + let at = line_start(text, object.close); + return vec![(at, at, format!("{indent}{rendered}\n"))]; + } + let filled = format!("\n{indent}{rendered}\n{open_indent}"); + return vec![(object.close, object.close, filled)]; + }; + if is_single_line(text, object) { + let rendered = members + .iter() + .map(|(name, value)| format!("{}: {}", quote(name), value.to_compact())) + .collect::>() + .join(", "); + return match last.comma { + Some(comma) => vec![(comma + 1, comma + 1, format!(" {rendered},"))], + None => vec![(last.value.end(), last.value.end(), format!(", {rendered}"))], + }; + } + let indent = match starts_line(text, last.key_start) { + true => line_indent(text, last.key_start).to_owned(), + false => format!("{open_indent}{unit}"), + }; + let rendered = pretty(&indent); + let mut edits = Vec::new(); + let anchor = match last.comma { + Some(comma) => comma + 1, + None => { + edits.push((last.value.end(), last.value.end(), ",".to_owned())); + last.value.end() + } + }; + // A comment after the last member stays with it. + let end_of_line = line_end(text, anchor); + let at = match object.close >= end_of_line && only_trivia(&text[anchor..end_of_line]) { + true => end_of_line, + false => anchor, + }; + let trailing = if last.comma.is_some() { "," } else { "" }; + edits.push((at, at, format!("\n{indent}{rendered}{trailing}"))); + edits + } + + fn remove_member(&self, object: &ObjectNode, index: usize) -> Result { + let text = self.text; + let member = &object.members[index]; + if object.members.len() == 1 && !text[object.open..object.close].contains('\n') { + return Ok(splice(text, vec![(object.open + 1, object.close, String::new())])); + } + let last_without_comma = index + 1 == object.members.len() && member.comma.is_none(); + if last_without_comma && index > 0 { + let comma = object.members[index - 1].comma.ok_or(ConfigEditError::InvalidSyntax { + offset: Some(member.key_start), + })?; + if text[comma + 1..member.key_start].trim().is_empty() { + return Ok(splice(text, vec![(comma, member.value.end(), String::new())])); + } + let (start, end) = self.member_span(object, member); + return Ok(splice( + text, + vec![(comma, comma + 1, String::new()), (start, end, String::new())], + )); + } + let (start, end) = self.member_span(object, member); + Ok(splice(text, vec![(start, end, String::new())])) + } + + fn member_span(&self, object: &ObjectNode, member: &Member) -> (usize, usize) { + let text = self.text; + let after = member.comma.map_or(member.value.end(), |comma| comma + 1); + if starts_line(text, member.key_start) { + let end_of_line = line_end(text, after); + if text[after..end_of_line].trim().is_empty() && object.close > end_of_line { + return (line_start(text, member.key_start), end_of_line + 1); + } + return (line_start(text, member.key_start), after); + } + let mut end = after; + if member.comma.is_some() { + while matches!(text.as_bytes().get(end), Some(b' ' | b'\t')) { + end += 1; + } + } + (member.key_start, end) + } + + // The step one level of nesting adds, read from the first object that + // puts a member on a line below its brace. + fn indent_unit(&self) -> String { + self.root + .as_ref() + .and_then(|root| indent_in(self.text, root)) + .unwrap_or_else(|| DEFAULT_INDENT.to_owned()) + } +} + +fn indent_in(text: &str, node: &Node) -> Option { + match node { + Node::Object(object) => { + let brace = line_indent(text, object.open); + for member in &object.members { + if starts_line(text, member.key_start) && line_start(text, member.key_start) > object.open { + let indent = line_indent(text, member.key_start); + if let Some(step) = indent.strip_prefix(brace) + && !step.is_empty() + { + return Some(step.to_owned()); + } + } + } + object.members.iter().find_map(|member| indent_in(text, &member.value)) + } + Node::Array(array) => array.items.iter().find_map(|item| indent_in(text, item)), + Node::Scalar(_) => None, + } +} + +fn is_single_line(text: &str, object: &ObjectNode) -> bool { + !text[object.open..object.close].contains('\n') +} + +fn line_start(text: &str, pos: usize) -> usize { + text[..pos].rfind('\n').map_or(0, |newline| newline + 1) +} + +fn line_end(text: &str, pos: usize) -> usize { + text[pos..].find('\n').map_or(text.len(), |newline| pos + newline) +} + +fn line_indent(text: &str, pos: usize) -> &str { + let line = &text[line_start(text, pos)..]; + let content = line.trim_start_matches([' ', '\t']); + &line[..line.len() - content.len()] +} + +fn starts_line(text: &str, pos: usize) -> bool { + text[line_start(text, pos)..pos].trim_matches([' ', '\t']).is_empty() +} + +fn only_trivia(mut segment: &str) -> bool { + loop { + segment = segment.trim_start(); + if segment.is_empty() || segment.starts_with("//") { + return true; + } + let Some(comment) = segment.strip_prefix("/*") else { + return false; + }; + let Some(close) = comment.find("*/") else { + return false; + }; + segment = &comment[close + 2..]; + } +} + +// A byte range and the text that takes its place. +type Edit = (usize, usize, String); + +// Edits do not overlap; two at one point go in the order given. +fn splice(text: &str, mut edits: Vec) -> String { + edits.sort_by_key(|(start, _, _)| *start); + let mut out = String::with_capacity(text.len() + edits.iter().map(|edit| edit.2.len()).sum::()); + let mut cursor = 0; + for (start, end, replacement) in edits { + out.push_str(text.get(cursor..start).unwrap_or_default()); + out.push_str(&replacement); + cursor = cursor.max(end); + } + out.push_str(text.get(cursor..).unwrap_or_default()); + out +} + +struct Parser<'a> { + text: &'a str, + bytes: &'a [u8], + pos: usize, +} + +impl Parser<'_> { + fn error(&self) -> ConfigEditError { + ConfigEditError::InvalidSyntax { offset: Some(self.pos) } + } + + fn peek(&self) -> Option { + self.bytes.get(self.pos).copied() + } + + fn skip_trivia(&mut self) -> Result<(), ConfigEditError> { + loop { + match self.peek() { + Some(b' ' | b'\t' | b'\n' | b'\r') => self.pos += 1, + Some(b'/') => match self.bytes.get(self.pos + 1) { + Some(b'/') => self.pos = line_end(self.text, self.pos), + Some(b'*') => { + let close = self.text[self.pos + 2..].find("*/").ok_or_else(|| self.error())?; + self.pos += close + 4; + } + _ => return Err(self.error()), + }, + _ => return Ok(()), + } + } + } + + fn value(&mut self, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err(self.error()); + } + let start = self.pos; + let scalar = |value: JsonValue, end: usize| Node::Scalar(ScalarNode { start, end, value }); + match self.peek() { + Some(b'{') => self.object(depth), + Some(b'[') => self.array(depth), + Some(b'"') => { + let text = self.string()?; + Ok(scalar(JsonValue::String(text), self.pos)) + } + Some(b't') => self.literal("true").map(|end| scalar(JsonValue::Bool(true), end)), + Some(b'f') => self.literal("false").map(|end| scalar(JsonValue::Bool(false), end)), + Some(b'n') => self.literal("null").map(|end| scalar(JsonValue::Null, end)), + Some(b'-' | b'0'..=b'9') => { + while matches!(self.peek(), Some(b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9')) { + self.pos += 1; + } + let number = self.text[start..self.pos] + .parse::() + .map_err(|_| ConfigEditError::InvalidSyntax { offset: Some(start) })?; + Ok(scalar(JsonValue::Number(number), self.pos)) + } + _ => Err(self.error()), + } + } + + fn literal(&mut self, word: &str) -> Result { + if !self.text[self.pos..].starts_with(word) { + return Err(self.error()); + } + self.pos += word.len(); + Ok(self.pos) + } + + fn object(&mut self, depth: usize) -> Result { + let open = self.pos; + self.pos += 1; + let mut members = Vec::new(); + loop { + self.skip_trivia()?; + match self.peek() { + Some(b'}') => { + let close = self.pos; + self.pos += 1; + return Ok(Node::Object(ObjectNode { open, close, members })); + } + Some(b'"') => {} + _ => return Err(self.error()), + } + let key_start = self.pos; + let key = self.string()?; + self.skip_trivia()?; + if self.peek() != Some(b':') { + return Err(self.error()); + } + self.pos += 1; + self.skip_trivia()?; + let value = self.value(depth + 1)?; + let comma = self.separator(b'}')?; + members.push(Member { + key, + key_start, + value, + comma, + }); + } + } + + fn array(&mut self, depth: usize) -> Result { + let open = self.pos; + self.pos += 1; + let mut items = Vec::new(); + loop { + self.skip_trivia()?; + if self.peek() == Some(b']') { + let close = self.pos; + self.pos += 1; + return Ok(Node::Array(ArrayNode { open, close, items })); + } + items.push(self.value(depth + 1)?); + self.separator(b']')?; + } + } + + // After a value: a comma, kept where it is, or the closing bracket, + // left for the caller. JSONC allows a comma before the bracket. + fn separator(&mut self, close: u8) -> Result, ConfigEditError> { + self.skip_trivia()?; + match self.peek() { + Some(b',') => { + self.pos += 1; + Ok(Some(self.pos - 1)) + } + Some(found) if found == close => Ok(None), + _ => Err(self.error()), + } + } + + fn string(&mut self) -> Result { + self.pos += 1; + let mut out = String::new(); + loop { + let rest = &self.text[self.pos..]; + let stop = rest + .find(|character: char| character == '"' || character == '\\' || character < ' ') + .ok_or_else(|| self.error())?; + out.push_str(&rest[..stop]); + self.pos += stop; + match self.peek() { + Some(b'"') => { + self.pos += 1; + return Ok(out); + } + Some(b'\\') => { + self.pos += 1; + self.escape(&mut out)?; + } + _ => return Err(self.error()), + } + } + } + + fn escape(&mut self, out: &mut String) -> Result<(), ConfigEditError> { + let code = self.peek().ok_or_else(|| self.error())?; + self.pos += 1; + match code { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push('\u{8}'), + b'f' => out.push('\u{c}'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + let first = self.hex4()?; + let scalar = match first { + 0xD800..=0xDBFF => self.low_surrogate().map_or(REPLACEMENT, |second| { + 0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00) + }), + 0xDC00..=0xDFFF => REPLACEMENT, + other => other, + }; + out.push(char::from_u32(scalar).unwrap_or(char::REPLACEMENT_CHARACTER)); + } + _ => return Err(self.error()), + } + Ok(()) + } + + // The second half of a surrogate pair, taken only when it is one. A + // lone half reads as U+FFFD, so one odd string in a file the user owns + // does not make the rest of it unreadable; edits never write it back. + fn low_surrogate(&mut self) -> Option { + if self.bytes.get(self.pos..self.pos + 2) != Some(b"\\u") { + return None; + } + let digits = self.text.get(self.pos + 2..self.pos + 6)?; + if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + let value = u32::from_str_radix(digits, 16).ok()?; + if !(0xDC00..=0xDFFF).contains(&value) { + return None; + } + self.pos += 6; + Some(value) + } + + fn hex4(&mut self) -> Result { + let digits = self.text.get(self.pos..self.pos + 4).ok_or_else(|| self.error())?; + if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(self.error()); + } + let value = u32::from_str_radix(digits, 16).map_err(|_| self.error())?; + self.pos += 4; + Ok(value) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn path(keys: &[&str]) -> Vec { + keys.iter().map(|key| (*key).to_owned()).collect() + } + + fn entry() -> JsonValue { + JsonValue::Object(vec![ + ( + "url".to_owned(), + JsonValue::String("http://127.0.0.1:23508/mcp".to_owned()), + ), + ( + "headers".to_owned(), + JsonValue::Object(vec![( + "Authorization".to_owned(), + JsonValue::String("Bearer tp_x".to_owned()), + )]), + ), + ]) + } + + fn upsert(text: &str, keys: &[&str]) -> String { + upserting(text, &path(keys), "tablepro", &entry(), Upsert::Merge).expect("an edit") + } + + #[test] + fn an_empty_file_becomes_the_whole_document() { + let edited = upsert("", &["mcpServers"]); + + assert_eq!( + edited, + "{\n \"mcpServers\": {\n \"tablepro\": {\n \"url\": \"http://127.0.0.1:23508/mcp\",\n \ +\"headers\": {\n \"Authorization\": \"Bearer tp_x\"\n }\n }\n }\n}\n" + ); + assert_eq!(upsert(" \n", &["mcpServers"]), edited); + } + + #[test] + fn a_new_server_goes_after_the_others_and_keeps_comments_and_order() { + let text = "// Zed settings\n{\n\t\"theme\": \"One Dark\", // the theme\n\t\"context_servers\": {\n\t\t\ +\"other\": { \"url\": \"x\" } // keep me\n\t},\n\t/* tail */\n\t\"vim_mode\": true\n}\n"; + + let edited = upsert(text, &["context_servers"]); + + assert_eq!( + edited, + "// Zed settings\n{\n\t\"theme\": \"One Dark\", // the theme\n\t\"context_servers\": {\n\t\t\ +\"other\": { \"url\": \"x\" }, // keep me\n\t\t\"tablepro\": {\n\t\t\t\"url\": \"http://127.0.0.1:23508/mcp\",\n\t\t\t\ +\"headers\": {\n\t\t\t\t\"Authorization\": \"Bearer tp_x\"\n\t\t\t}\n\t\t}\n\t},\n\t/* tail */\n\t\"vim_mode\": true\n}\n" + ); + assert_eq!( + member(&edited, &path(&["context_servers"]), "tablepro").expect("readable"), + Some(entry()) + ); + assert!( + member(&edited, &path(&["context_servers"]), "other") + .expect("readable") + .is_some() + ); + } + + #[test] + fn a_trailing_comma_style_is_kept() { + let text = "{\n \"servers\": {\n \"a\": {},\n },\n}\n"; + + let edited = upsert(text, &["servers"]); + + assert!(edited.contains(" \"a\": {},\n \"tablepro\": {\n"), "{edited}"); + assert!(edited.ends_with(" }\n },\n },\n}\n"), "{edited}"); + assert!( + member(&edited, &path(&["servers"]), "tablepro") + .expect("readable") + .is_some() + ); + } + + #[test] + fn missing_objects_on_the_key_path_are_created() { + let text = "{\n \"$schema\": \"https://opencode.ai/config.json\"\n}\n"; + + let edited = upsert(text, &["mcp", "servers"]); + + assert!( + edited.starts_with( + "{\n \"$schema\": \"https://opencode.ai/config.json\",\n \"mcp\": {\n \"servers\": {\n" + ), + "{edited}" + ); + assert_eq!( + member(&edited, &path(&["mcp", "servers"]), "tablepro").expect("readable"), + Some(entry()) + ); + } + + #[test] + fn an_existing_entry_keeps_its_place_and_gets_what_it_lacks() { + let text = "{\n \"mcpServers\": {\n \"tablepro\": { \"url\": \"old\" },\n \"next\": {}\n }\n}"; + + let edited = upsert(text, &["mcpServers"]); + + assert_eq!( + edited, + "{\n \"mcpServers\": {\n \"tablepro\": { \"url\": \"http://127.0.0.1:23508/mcp\", \ +\"headers\": {\"Authorization\":\"Bearer tp_x\"} },\n \"next\": {}\n }\n}" + ); + assert_eq!( + member(&edited, &path(&["mcpServers"]), "tablepro").expect("readable"), + Some(entry()) + ); + } + + #[test] + fn an_update_rewrites_only_what_the_entry_renders() { + let text = "{\n \"mcpServers\": {\n \"tablepro\": {\n // my note\n \"url\": \"http://old\",\n \ +\"timeout\": 30,\n \"headers\": {\n \"authorization\": \"Bearer tp_old\",\n \"X-Team\": \"data\"\n \ +}\n }\n }\n}\n"; + + let edited = upsert(text, &["mcpServers"]); + + assert_eq!( + edited, + "{\n \"mcpServers\": {\n \"tablepro\": {\n // my note\n \"url\": \"http://127.0.0.1:23508/mcp\",\n \ +\"timeout\": 30,\n \"headers\": {\n \"authorization\": \"Bearer tp_x\",\n \"X-Team\": \"data\"\n \ +}\n }\n }\n}\n" + ); + } + + #[test] + fn a_key_on_top_of_the_entry_matches_only_as_spelled() { + let edited = upsert( + r#"{"mcpServers": {"tablepro": {"URL": "x", "headers": {"AUTHORIZATION": "y"}}}}"#, + &["mcpServers"], + ); + + assert_eq!( + edited, + r#"{"mcpServers": {"tablepro": {"URL": "x", "headers": {"AUTHORIZATION": "Bearer tp_x"}, "url": "http://127.0.0.1:23508/mcp"}}}"# + ); + } + + #[test] + fn an_entry_that_is_not_an_object_is_replaced_whole() { + let edited = upsert("{\"mcpServers\": {\"tablepro\": \"x\"}}", &["mcpServers"]); + + assert_eq!( + edited, + r#"{"mcpServers": {"tablepro": {"url":"http://127.0.0.1:23508/mcp","headers":{"Authorization":"Bearer tp_x"}}}}"# + ); + } + + #[test] + fn an_empty_object_gets_its_first_member() { + assert!(upsert("{}", &["mcpServers"]).starts_with("{\n \"mcpServers\": {\n \"tablepro\"")); + let with_comment = upsert("{\n \"mcpServers\": {\n // none yet\n }\n}", &["mcpServers"]); + assert!( + with_comment.contains(" // none yet\n \"tablepro\": {\n"), + "{with_comment}" + ); + } + + #[test] + fn a_one_line_object_stays_on_one_line() { + let edited = upsert(r#"{"mcpServers": {"a": {"url": "y"}}}"#, &["mcpServers"]); + + assert_eq!( + edited, + r#"{"mcpServers": {"a": {"url": "y"}, "tablepro": {"url":"http://127.0.0.1:23508/mcp","headers":{"Authorization":"Bearer tp_x"}}}}"# + ); + } + + #[test] + fn a_duplicate_key_on_the_path_or_the_server_is_refused() { + let twice = "{\"mcpServers\": {}, \"mcpServers\": {}}"; + let server_twice = "{\"mcpServers\": {\"tablepro\": {}, \"tablepro\": {}}}"; + + assert_eq!( + upserting(twice, &path(&["mcpServers"]), "tablepro", &entry(), Upsert::Merge), + Err(ConfigEditError::DuplicateKey { + path: path(&["mcpServers"]) + }) + ); + assert_eq!( + member(server_twice, &path(&["mcpServers"]), "tablepro"), + Err(ConfigEditError::DuplicateKey { + path: path(&["mcpServers", "tablepro"]) + }) + ); + } + + #[test] + fn broken_or_misshapen_files_are_refused() { + for text in [ + "{", + "{\"a\": 1 \"b\": 2}", + "[1, 2]", + "{\"a\": tru}", + "{} {}", + "{\"a\": \"\u{1}\"}", + "/* open", + ] { + assert!( + upserting(text, &path(&["mcpServers"]), "tablepro", &entry(), Upsert::Merge).is_err(), + "{text:?}" + ); + } + assert_eq!( + upserting( + "{\"mcpServers\": []}", + &path(&["mcpServers"]), + "tablepro", + &entry(), + Upsert::Merge + ), + Err(ConfigEditError::NotAnObject { + path: path(&["mcpServers"]) + }) + ); + } + + #[test] + fn escapes_and_a_byte_order_mark_are_read() { + let text = "\u{feff}{\"mcpServers\": {\"tablepro\": {\"url\": \"a\\u00e9\\ud83d\\ude00\\n\"}}}"; + + let found = member(text, &path(&["mcpServers"]), "tablepro").expect("readable"); + + assert_eq!( + found.and_then(|value| value.get("url").cloned()), + Some(JsonValue::String("aé😀\n".to_owned())) + ); + } + + #[test] + fn a_lone_surrogate_reads_as_a_replacement_and_stays_in_the_file() { + let text = "{\"other\": {\"name\": \"a\\ud83d b\\ude00 c\\ud83d\\u0041\"}, \"mcpServers\": {}}"; + + let other = member(text, &[], "other").expect("readable"); + let edited = upsert(text, &["mcpServers"]); + + assert_eq!( + other.and_then(|value| value.get("name").cloned()), + Some(JsonValue::String("a\u{fffd} b\u{fffd} c\u{fffd}A".to_owned())) + ); + assert!( + edited.starts_with("{\"other\": {\"name\": \"a\\ud83d b\\ude00 c\\ud83d\\u0041\"}"), + "{edited}" + ); + assert!( + member(&edited, &path(&["mcpServers"]), "tablepro") + .expect("readable") + .is_some() + ); + } + + #[test] + fn removing_the_last_member_takes_the_comma_before_it() { + let text = + "{\n \"mcpServers\": {\n \"other\": {},\n \"tablepro\": {\n \"url\": \"x\"\n }\n }\n}\n"; + + let removed = removing(text, &path(&["mcpServers"]), "tablepro").expect("an edit"); + + assert_eq!(removed, "{\n \"mcpServers\": {\n \"other\": {}\n }\n}\n"); + } + + #[test] + fn removing_a_middle_member_takes_its_own_line() { + let text = "{\n \"mcpServers\": {\n \"tablepro\": {\"url\": \"x\"},\n \"other\": {}\n }\n}\n"; + + let removed = removing(text, &path(&["mcpServers"]), "tablepro").expect("an edit"); + + assert_eq!(removed, "{\n \"mcpServers\": {\n \"other\": {}\n }\n}\n"); + } + + #[test] + fn removing_the_only_member_leaves_an_empty_object() { + let text = "{\n \"mcpServers\": {\n \"tablepro\": {\"url\": \"x\"}\n }\n}\n"; + + assert_eq!( + removing(text, &path(&["mcpServers"]), "tablepro").expect("an edit"), + "{\n \"mcpServers\": {\n }\n}\n" + ); + assert_eq!( + removing( + r#"{"mcpServers": {"tablepro": {}}}"#, + &path(&["mcpServers"]), + "tablepro" + ) + .expect("an edit"), + r#"{"mcpServers": {}}"# + ); + } + + #[test] + fn removing_what_is_not_there_changes_nothing() { + let text = "{ \"a\": 1 } // done\n"; + + assert_eq!( + removing(text, &path(&["mcpServers"]), "tablepro").expect("no edit"), + text + ); + } + + #[test] + fn a_comment_between_the_last_two_members_is_kept_on_removal() { + let text = "{\n \"a\": 1, // about a\n \"tablepro\": {}\n}\n"; + + let removed = removing(text, &[], "tablepro").expect("an edit"); + + assert_eq!(removed, "{\n \"a\": 1 // about a\n}\n"); + } + + #[test] + fn a_wildcard_scope_finds_a_server_in_any_project() { + let text = r#"{"projects": {"/home/ana/app": {"mcpServers": {"tablepro": {}}}}}"#; + + let scope = path(&["projects", "*", "mcpServers"]); + + assert_eq!( + members_in_scope(text, &scope, "tablepro").expect("readable"), + [JsonValue::Object(Vec::new())] + ); + assert!(members_in_scope(text, &scope, "other").expect("readable").is_empty()); + } +} diff --git a/core/crates/mcp/src/clients/merge.rs b/core/crates/mcp/src/clients/merge.rs new file mode 100644 index 0000000000..c9d38c2d4f --- /dev/null +++ b/core/crates/mcp/src/clients/merge.rs @@ -0,0 +1,193 @@ +use super::json_value::JsonValue; + +const PLACEHOLDERS: [&str; 4] = ["command", "url", "authorization", "name"]; + +// No placeholder, but they decide how the client starts the server. +const ALWAYS_WRITTEN: [&str; 2] = ["type", "args"]; + +// Every spelling the catalog uses; a test below keeps them in step. +const STDIO_MEMBERS: [&str; 2] = ["command", "cmd"]; +const HTTP_MEMBERS: [&str; 4] = ["url", "serverUrl", "httpUrl", "uri"]; + +// Only what reaches TablePro is written over, so an Update never widens +// a restriction the user set, such as `tools` or `disabled`. +pub(crate) fn update_for(existing: &JsonValue, rendered: &JsonValue, template: &JsonValue) -> JsonValue { + filter(existing, rendered, Some(template), false) +} + +fn filter(existing: &JsonValue, rendered: &JsonValue, template: Option<&JsonValue>, nested: bool) -> JsonValue { + let (JsonValue::Object(have), JsonValue::Object(want)) = (existing, rendered) else { + return rendered.clone(); + }; + JsonValue::Object( + want.iter() + .filter_map(|(key, value)| { + let shape = template.and_then(|template| template.get(key)); + match lookup(have, key, nested) { + None => Some((key.clone(), value.clone())), + Some(found) if overwrites(key, shape, nested) => { + Some((key.clone(), filter(found, value, shape, true))) + } + Some(_) => None, + } + }) + .collect(), + ) +} + +// As the editors match: exactly on top of the entry, ignoring case below. +fn lookup<'v>(members: &'v [(String, JsonValue)], key: &str, nested: bool) -> Option<&'v JsonValue> { + members + .iter() + .find(|(name, _)| name == key) + .or_else(|| { + members + .iter() + .find(|(name, _)| nested && name.eq_ignore_ascii_case(key)) + }) + .map(|(_, value)| value) +} + +fn overwrites(key: &str, template: Option<&JsonValue>, nested: bool) -> bool { + (!nested && ALWAYS_WRITTEN.contains(&key)) || template.is_some_and(|template| holds(template, &PLACEHOLDERS)) +} + +fn holds(template: &JsonValue, names: &[&str]) -> bool { + match template { + JsonValue::String(text) => placeholder_names(text).any(|name| names.contains(&name)), + JsonValue::Array(items) => items.iter().any(|item| holds(item, names)), + JsonValue::Object(members) => members.iter().any(|(_, member)| holds(member, names)), + _ => false, + } +} + +fn placeholder_names(text: &str) -> impl Iterator { + text.split('{') + .skip(1) + .filter_map(|after| after.split_once('}')) + .map(|(expression, _)| expression.split('|').next().unwrap_or_default()) +} + +// The old transport's members go, but a limit the user set, such as `tools`, stays. +pub(crate) fn replace_keeping_choices(existing: &JsonValue, rendered: &JsonValue, template: &JsonValue) -> JsonValue { + let JsonValue::Object(want) = rendered else { + return rendered.clone(); + }; + JsonValue::Object( + want.iter() + .map(|(key, value)| { + let chosen = !ALWAYS_WRITTEN.contains(&key.as_str()) + && !template.get(key).is_some_and(|shape| holds(shape, &PLACEHOLDERS)); + match existing.get(key) { + Some(mine) if chosen => (key.clone(), mine.clone()), + _ => (key.clone(), value.clone()), + } + }) + .collect(), + ) +} + +// Its members mean nothing to the other transport, so it is replaced. +pub(crate) fn transport_differs(existing: &JsonValue, template: &JsonValue) -> bool { + let names_any = |members: &[&str]| members.iter().any(|member| existing.get(member).is_some()); + match (holds(template, &["command"]), holds(template, &["url"])) { + (false, true) => names_any(&STDIO_MEMBERS), + (true, false) => names_any(&HTTP_MEMBERS), + _ => false, + } +} + +pub(crate) fn names_a_command(entry: &JsonValue) -> bool { + STDIO_MEMBERS.iter().any(|member| entry.get(member).is_some()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::clients::catalog::{ClientCatalog, ClientPlatform}; + + fn parse(text: &str) -> JsonValue { + serde_json::from_str(text).expect("JSON") + } + + #[test] + fn only_members_that_reach_tablepro_are_written_over() { + let template = parse( + r#"{"type": "http", "url": "{url}", "headers": {"Authorization": "{authorization}"}, + "tools": ["*"], "disabled": false, "args": []}"#, + ); + let rendered = parse( + r#"{"type": "http", "url": "http://new", "headers": {"Authorization": "Bearer tp_new"}, + "tools": ["*"], "disabled": false, "args": []}"#, + ); + let existing = parse( + r#"{"type": "sse", "url": "http://old", "headers": {"authorization": "Bearer tp_old"}, + "tools": ["list_connections"], "disabled": true, "args": ["-v"]}"#, + ); + + assert_eq!( + update_for(&existing, &rendered, &template), + parse( + r#"{"type": "http", "url": "http://new", "headers": {"Authorization": "Bearer tp_new"}, "args": []}"# + ) + ); + } + + #[test] + fn a_member_the_entry_lacks_comes_from_the_template_and_one_it_has_stays_whole() { + let template = parse(r#"{"url": "{url}", "tools": ["*"], "headers": {"X-Client": "tablepro"}}"#); + let rendered = parse(r#"{"url": "http://new", "tools": ["*"], "headers": {"X-Client": "tablepro"}}"#); + + assert_eq!( + update_for(&parse(r#"{"url": "http://old"}"#), &rendered, &template), + rendered + ); + assert_eq!( + update_for( + &parse(r#"{"url": "http://old", "headers": {"X-Team": "data"}}"#), + &rendered, + &template + ), + parse(r#"{"url": "http://new", "tools": ["*"]}"#) + ); + } + + #[test] + fn a_placeholder_with_a_filter_or_inside_text_still_counts() { + assert!(holds(&parse(r#"{"a": ["x {command|uri} y"]}"#), &PLACEHOLDERS)); + assert!(holds(&parse(r#""Bearer {authorization}""#), &PLACEHOLDERS)); + assert!(!holds(&parse(r#"{"a": "{other}", "b": "{url"}"#), &PLACEHOLDERS)); + } + + #[test] + fn an_entry_for_the_other_transport_is_told_apart() { + let http = parse(r#"{"url": "{url}", "headers": {"Authorization": "{authorization}"}}"#); + let stdio = parse(r#"{"command": "{command}", "args": []}"#); + + assert!(transport_differs(&parse(r#"{"command": "/x", "url": "u"}"#), &http)); + assert!(!transport_differs(&parse(r#"{"url": "u", "tools": []}"#), &http)); + assert!(transport_differs(&parse(r#"{"httpUrl": "u"}"#), &stdio)); + assert!(!transport_differs(&parse(r#"{"command": "/x"}"#), &stdio)); + } + + #[test] + fn every_catalog_entry_names_its_target_where_the_transport_check_looks() { + let catalog = ClientCatalog::bundled().expect("the bundled catalog"); + for platform in [ClientPlatform::Macos, ClientPlatform::Linux] { + for client in catalog.clients_on(platform) { + let Some(JsonValue::Object(members)) = client.spec(platform).and_then(|spec| spec.entry.as_ref()) + else { + continue; + }; + for (key, member) in members { + if holds(member, &["command"]) { + assert!(STDIO_MEMBERS.contains(&key.as_str()), "{} {key}", client.id); + } + if holds(member, &["url"]) { + assert!(HTTP_MEMBERS.contains(&key.as_str()), "{} {key}", client.id); + } + } + } + } + } +} diff --git a/core/crates/mcp/src/clients/mod.rs b/core/crates/mcp/src/clients/mod.rs new file mode 100644 index 0000000000..52cc43e569 --- /dev/null +++ b/core/crates/mcp/src/clients/mod.rs @@ -0,0 +1,25 @@ +// What it takes to set up an MCP client: the catalog both apps ship, the +// entry each client needs, edits to its config file, and whether the +// file already reaches this server. No sentences live here; each app +// words the codes and states itself. + +mod catalog; +mod config_edit; +mod json_value; +mod jsonc; +mod merge; +mod paths; +mod status; +mod template; +mod toml_table; + +pub use catalog::{ + Applies, CatalogError, CliInstall, CliUpdate, ClientCatalog, ClientDefinition, ClientInfoNames, ClientPlatform, + ConfigFormat, ConfigLocation, DeeplinkInstall, DetectRule, InstallMethod, PlatformSpec, SCHEMA_VERSION, + UnsupportedReason, +}; +pub use config_edit::{ConfigEditError, members_in_scope, read_member, remove_member, upsert_member}; +pub use json_value::JsonValue; +pub use paths::expand_path; +pub use status::{ClientConfigStatus, StaleReason, evaluate_status}; +pub use template::{ServerTarget, TemplateError, TemplateRenderer, command_line, snippet}; diff --git a/core/crates/mcp/src/clients/paths.rs b/core/crates/mcp/src/clients/paths.rs new file mode 100644 index 0000000000..53d102da54 --- /dev/null +++ b/core/crates/mcp/src/clients/paths.rs @@ -0,0 +1,80 @@ +// `${VAR:-default}` and `${VAR}` take the variable when it is set and not +// empty, as a shell does; a leading `~` then becomes `home`. +pub fn expand_path(path: &str, home: &str, variable: impl Fn(&str) -> Option) -> String { + let mut out = String::with_capacity(path.len()); + let mut rest = path; + while let Some(open) = rest.find("${") { + out.push_str(&rest[..open]); + let after = &rest[open + 2..]; + let Some(close) = after.find('}') else { + out.push_str(&rest[open..]); + rest = ""; + break; + }; + let (name, default) = match after[..close].split_once(":-") { + Some((name, default)) => (name, default), + None => (&after[..close], ""), + }; + match variable(name).filter(|value| !value.is_empty()) { + Some(value) => out.push_str(&value), + None => out.push_str(default), + } + rest = &after[close + 1..]; + } + out.push_str(rest); + let home = home.trim_end_matches('/'); + if out == "~" { + return if home.is_empty() { + "/".to_owned() + } else { + home.to_owned() + }; + } + match out.strip_prefix("~/") { + Some(below) => format!("{home}/{below}"), + None => out, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn none(_: &str) -> Option { + None + } + + #[test] + fn a_tilde_is_the_home_folder() { + assert_eq!( + expand_path("~/.cursor/mcp.json", "/home/ana", none), + "/home/ana/.cursor/mcp.json" + ); + assert_eq!(expand_path("~", "/home/ana/", none), "/home/ana"); + assert_eq!(expand_path("/etc/~x", "/home/ana", none), "/etc/~x"); + } + + #[test] + fn a_variable_wins_over_its_default_unless_empty() { + let set = |name: &str| (name == "XDG_CONFIG_HOME").then(|| "/cfg".to_owned()); + let empty = |_: &str| Some(String::new()); + + assert_eq!( + expand_path("${XDG_CONFIG_HOME:-~/.config}/zed/settings.json", "/home/ana", set), + "/cfg/zed/settings.json" + ); + assert_eq!( + expand_path("${XDG_CONFIG_HOME:-~/.config}/zed/settings.json", "/home/ana", empty), + "/home/ana/.config/zed/settings.json" + ); + assert_eq!( + expand_path("${CLAUDE_CONFIG_DIR:-~}/.claude.json", "/home/ana", none), + "/home/ana/.claude.json" + ); + } + + #[test] + fn an_unclosed_variable_is_left_as_written() { + assert_eq!(expand_path("/a/${B", "/home/ana", none), "/a/${B"); + } +} diff --git a/core/crates/mcp/src/clients/status.rs b/core/crates/mcp/src/clients/status.rs new file mode 100644 index 0000000000..373a7ade06 --- /dev/null +++ b/core/crates/mcp/src/clients/status.rs @@ -0,0 +1,492 @@ +use super::catalog::{ConfigFormat, ConfigLocation}; +use super::config_edit; +use super::json_value::JsonValue; +use super::merge; +use super::template::ServerTarget; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClientConfigStatus { + NotConfigured, + Current, + // Current, but turned off in the client. + Disabled, + Stale(StaleReason), + // Set up only where TablePro does not install, such as one project. + OtherScope, + Unreadable, + // The client keeps its setup where TablePro cannot read it. + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StaleReason { + CommandMissing, + OtherCommand, + OtherUrl, + OtherToken, + // The entry TablePro writes is current, but an entry in another + // scope, which the client prefers there, is not. + Shadowed, +} + +impl ClientConfigStatus { + pub fn is_configured(self) -> bool { + matches!(self, Self::Current | Self::Disabled | Self::Stale(_)) + } +} + +enum Step { + Key(String), + Index(usize), +} + +// `template` is the catalog's entry before rendering: where it puts a +// placeholder is where the file has to hold the value. `config_text` is +// None when the file does not exist. With no authorization known, as +// while the Linux server is off, only the address is compared. +pub fn evaluate_status( + config_text: Option<&str>, + location: Option<&ConfigLocation>, + server_name: &str, + template: &JsonValue, + target: &ServerTarget, + file_exists: impl Fn(&str) -> bool, +) -> ClientConfigStatus { + let Some(location) = location.filter(|location| location.format != ConfigFormat::Yaml) else { + return ClientConfigStatus::Unknown; + }; + let Some(text) = config_text else { + return ClientConfigStatus::NotConfigured; + }; + let (Ok(actual), Ok(scoped)) = ( + own_member(text, location, server_name), + scoped_members(text, location, server_name), + ) else { + return ClientConfigStatus::Unreadable; + }; + let stale = |entry: &JsonValue| match target { + ServerTarget::Stdio { command } => stdio_reason(template, entry, command, &file_exists), + ServerTarget::Http { url, authorization } => http_reason(template, entry, url, authorization.as_deref()), + }; + let Some(actual) = actual else { + return match scoped.is_empty() { + true => ClientConfigStatus::NotConfigured, + false => ClientConfigStatus::OtherScope, + }; + }; + // Before stale: the client does not use it, and an Update leaves it off. + if turned_off(&actual) { + return ClientConfigStatus::Disabled; + } + if let Some(reason) = stale(&actual) { + return ClientConfigStatus::Stale(reason); + } + match scoped.iter().any(|entry| stale(entry).is_some()) { + true => ClientConfigStatus::Stale(StaleReason::Shadowed), + false => ClientConfigStatus::Current, + } +} + +// The entry where TablePro writes it, or where an older layout of the +// same file kept it. +fn own_member( + text: &str, + location: &ConfigLocation, + server_name: &str, +) -> Result, config_edit::ConfigEditError> { + for key_path in std::iter::once(&location.key_path).chain(&location.alternate_key_paths) { + if let Some(found) = config_edit::read_member(location.format, text, key_path, server_name)? { + return Ok(Some(found)); + } + } + Ok(None) +} + +fn scoped_members( + text: &str, + location: &ConfigLocation, + server_name: &str, +) -> Result, config_edit::ConfigEditError> { + let mut found = Vec::new(); + for scope in &location.other_scopes { + found.extend(config_edit::members_in_scope( + location.format, + text, + scope, + server_name, + )?); + } + Ok(found) +} + +// Clients spell it either way; Codex's TOML as `enabled = false`. +fn turned_off(entry: &JsonValue) -> bool { + entry.get("disabled") == Some(&JsonValue::Bool(true)) || entry.get("enabled") == Some(&JsonValue::Bool(false)) +} + +fn stdio_reason( + template: &JsonValue, + actual: &JsonValue, + command: &str, + file_exists: &impl Fn(&str) -> bool, +) -> Option { + let written = locate(template, "{command}").and_then(|path| follow(actual, &path)); + match written.and_then(JsonValue::as_str) { + Some(written) if written == command => None, + Some(written) if !file_exists(written) => Some(StaleReason::CommandMissing), + _ => Some(StaleReason::OtherCommand), + } +} + +fn http_reason( + template: &JsonValue, + actual: &JsonValue, + url: &str, + authorization: Option<&str>, +) -> Option { + // A client may start the program and never read the url beside it. + if merge::names_a_command(actual) { + return Some(StaleReason::OtherCommand); + } + let written = locate(template, "{url}") + .and_then(|path| follow(actual, &path)) + .and_then(JsonValue::as_str); + if !written.is_some_and(|written| same_endpoint(written, url)) { + return Some(StaleReason::OtherUrl); + } + let (Some(authorization), Some(path)) = (authorization, locate(template, "{authorization}")) else { + return None; + }; + let expected = follow(template, &path) + .and_then(JsonValue::as_str) + .map(|shape| shape.replace("{authorization}", authorization)); + let written = follow(actual, &path).and_then(JsonValue::as_str).map(str::trim); + match (written, expected) { + (Some(written), Some(expected)) if written == expected.trim() => None, + _ => Some(StaleReason::OtherToken), + } +} + +// The port and path decide it: the server listens on the loopback only, +// and a client may spell it 127.0.0.1 or localhost. +fn same_endpoint(written: &str, expected: &str) -> bool { + endpoint(written).is_some_and(|written| Some(written) == endpoint(expected)) +} + +fn endpoint(url: &str) -> Option<(u16, String)> { + let rest = url.trim(); + let scheme_end = rest.find("://")?; + if !rest[..scheme_end].eq_ignore_ascii_case("http") { + return None; + } + let rest = &rest[scheme_end + 3..]; + let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); + let port = match authority.rsplit_once(':') { + Some((host, port)) if !host.ends_with(']') || authority.starts_with('[') => port.parse().ok()?, + _ => 80, + }; + let path = path.split(['?', '#']).next().unwrap_or_default().trim_end_matches('/'); + Some((port, path.to_owned())) +} + +fn locate(template: &JsonValue, placeholder: &str) -> Option> { + match template { + JsonValue::String(text) if text.contains(placeholder) => Some(Vec::new()), + JsonValue::Array(items) => items.iter().enumerate().find_map(|(index, item)| { + locate(item, placeholder).map(|mut path| { + path.insert(0, Step::Index(index)); + path + }) + }), + JsonValue::Object(members) => members.iter().find_map(|(name, member)| { + locate(member, placeholder).map(|mut path| { + path.insert(0, Step::Key(name.clone())); + path + }) + }), + _ => None, + } +} + +// Keys match exactly first, then ignoring case, since a header name is +// not case sensitive. A command written as a string where the template +// has a one-element list still counts. +fn follow<'v>(value: &'v JsonValue, path: &[Step]) -> Option<&'v JsonValue> { + let Some((step, rest)) = path.split_first() else { + return Some(value); + }; + let next = match (step, value) { + (Step::Key(key), JsonValue::Object(members)) => members + .iter() + .find(|(name, _)| name == key) + .or_else(|| members.iter().find(|(name, _)| name.eq_ignore_ascii_case(key))) + .map(|(_, member)| member)?, + (Step::Index(index), JsonValue::Array(items)) => items.get(*index)?, + (Step::Index(0), JsonValue::String(_)) if rest.is_empty() => value, + _ => return None, + }; + follow(next, rest) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::clients::catalog::{ClientCatalog, ClientPlatform}; + + const URL: &str = "http://127.0.0.1:23508/mcp"; + + fn http(authorization: Option<&str>) -> ServerTarget { + ServerTarget::Http { + url: URL.to_owned(), + authorization: authorization.map(str::to_owned), + } + } + + fn status(id: &str, text: Option<&str>, target: &ServerTarget, platform: ClientPlatform) -> ClientConfigStatus { + let catalog = ClientCatalog::bundled().expect("the bundled catalog"); + let client = catalog.client(id).expect("a client"); + let template = client + .spec(platform) + .and_then(|spec| spec.entry.clone()) + .expect("an entry"); + evaluate_status( + text, + catalog.location(client, platform), + "tablepro", + &template, + target, + |path| path == "/old/tablepro-mcp", + ) + } + + fn linux(id: &str, text: Option<&str>, authorization: Option<&str>) -> ClientConfigStatus { + status(id, text, &http(authorization), ClientPlatform::Linux) + } + + #[test] + fn the_port_and_the_header_decide_a_linux_entry() { + let current = r#"{"mcpServers": {"tablepro": {"url": "http://localhost:23508/mcp/", + "headers": {"authorization": "Bearer tp_a"}}}}"#; + let other_port = r#"{"mcpServers": {"tablepro": {"url": "http://127.0.0.1:9/mcp", + "headers": {"Authorization": "Bearer tp_a"}}}}"#; + + assert_eq!( + linux("cursor", Some(current), Some("Bearer tp_a")), + ClientConfigStatus::Current + ); + assert_eq!( + linux("cursor", Some(current), Some("Bearer tp_b")), + ClientConfigStatus::Stale(StaleReason::OtherToken) + ); + assert_eq!(linux("cursor", Some(current), None), ClientConfigStatus::Current); + assert_eq!( + linux("cursor", Some(other_port), Some("Bearer tp_a")), + ClientConfigStatus::Stale(StaleReason::OtherUrl) + ); + } + + #[test] + fn a_missing_or_empty_file_is_not_configured_and_a_broken_one_unreadable() { + assert_eq!(linux("cursor", None, None), ClientConfigStatus::NotConfigured); + assert_eq!(linux("cursor", Some(""), None), ClientConfigStatus::NotConfigured); + assert_eq!(linux("cursor", Some("{"), None), ClientConfigStatus::Unreadable); + } + + #[test] + fn a_server_in_one_project_only_is_another_scope() { + let text = r#"{"projects": {"/home/ana/app": {"mcpServers": {"tablepro": {"type": "http"}}}}}"#; + + assert_eq!(linux("claude-code", Some(text), None), ClientConfigStatus::OtherScope); + } + + #[test] + fn a_stale_entry_in_another_scope_shadows_a_current_one() { + let user = r#""mcpServers": {"tablepro": {"type": "http", "url": "http://127.0.0.1:23508/mcp", + "headers": {"Authorization": "Bearer tp_a"}}}"#; + let project = |token: &str| { + format!( + r#""projects": {{"/home/ana/app": {{"mcpServers": {{"tablepro": {{"type": "http", + "url": "http://127.0.0.1:23508/mcp", "headers": {{"Authorization": "Bearer {token}"}}}}}}}}}}"# + ) + }; + let stale = format!("{{{user}, {}}}", project("tp_old")); + let current = format!("{{{user}, {}}}", project("tp_a")); + + assert_eq!( + linux("claude-code", Some(&stale), Some("Bearer tp_a")), + ClientConfigStatus::Stale(StaleReason::Shadowed) + ); + assert_eq!( + linux("claude-code", Some(¤t), Some("Bearer tp_a")), + ClientConfigStatus::Current + ); + assert_eq!( + linux("claude-code", Some(&stale), Some("Bearer tp_z")), + ClientConfigStatus::Stale(StaleReason::OtherToken), + "the entry TablePro writes comes first" + ); + } + + #[test] + fn an_older_layout_of_the_file_is_read_like_the_current_one() { + let older = r#"{"mcp": {"tablepro": {"type": "remote", "url": "http://127.0.0.1:23508/mcp", + "headers": {"Authorization": "Bearer tp_a"}}}}"#; + + assert_eq!( + linux("opencode", Some(older), Some("Bearer tp_a")), + ClientConfigStatus::Current + ); + assert_eq!( + linux("opencode", Some(older), Some("Bearer tp_b")), + ClientConfigStatus::Stale(StaleReason::OtherToken) + ); + assert_eq!( + linux("opencode", Some(r#"{"mcp": {"servers": {}}}"#), None), + ClientConfigStatus::NotConfigured + ); + } + + #[test] + fn an_entry_turned_off_in_the_client_is_not_read_as_set_up() { + let json = |extra: &str| { + format!( + r#"{{"mcpServers": {{"tablepro": {{"url": "{URL}", + "headers": {{"Authorization": "Bearer tp_a"}}{extra}}}}}}}"# + ) + }; + let toml = "[mcp_servers.tablepro]\nurl = \"http://127.0.0.1:23508/mcp\"\n\ +http_headers = { Authorization = \"Bearer tp_a\" }\nenabled = false\n"; + + for (id, extra) in [ + ("cursor", r#", "disabled": true"#), + ("kiro", r#", "disabled": true"#), + ("warp", r#", "enabled": false"#), + ] { + let status = linux(id, Some(&json(extra)), Some("Bearer tp_a")); + assert_eq!(status, ClientConfigStatus::Disabled, "{id}"); + assert!(status != ClientConfigStatus::Current, "{id}"); + } + assert_eq!( + linux("codex", Some(toml), Some("Bearer tp_a")), + ClientConfigStatus::Disabled + ); + assert_eq!( + linux("kiro", Some(&json(r#", "disabled": false"#)), Some("Bearer tp_a")), + ClientConfigStatus::Current + ); + } + + #[test] + fn a_turned_off_entry_is_disabled_whatever_its_address_or_token() { + let old = |off: &str| { + format!( + r#"{{"mcpServers": {{"tablepro": {{"url": "http://127.0.0.1:9/mcp", + "headers": {{"Authorization": "Bearer tp_old"}}, {off}}}}}}}"# + ) + }; + let toml = "[mcp_servers.tablepro]\nurl = \"http://127.0.0.1:9/mcp\"\nenabled = false\n"; + + for id in ["cline", "kiro"] { + assert_eq!( + linux(id, Some(&old(r#""disabled": true"#)), Some("Bearer tp_a")), + ClientConfigStatus::Disabled, + "{id}" + ); + } + assert_eq!( + linux("warp", Some(&old(r#""enabled": false"#)), Some("Bearer tp_a")), + ClientConfigStatus::Disabled + ); + assert_eq!( + linux("codex", Some(toml), Some("Bearer tp_a")), + ClientConfigStatus::Disabled + ); + } + + #[test] + fn an_http_entry_that_still_names_a_command_is_stale() { + let current = r#""url": "http://127.0.0.1:23508/mcp", "headers": {"Authorization": "Bearer tp_a"}"#; + let both = format!(r#"{{"mcpServers": {{"tablepro": {{"command": "/x/tablepro-mcp", {current}}}}}}}"#); + let stdio = r#"{"mcpServers": {"tablepro": {"command": "/x/tablepro-mcp", "args": []}}}"#; + let codex = "[mcp_servers.tablepro]\ncommand = \"/x/tablepro-mcp\"\nurl = \"http://127.0.0.1:23508/mcp\"\n"; + + assert_eq!( + linux("cursor", Some(&both), Some("Bearer tp_a")), + ClientConfigStatus::Stale(StaleReason::OtherCommand) + ); + assert_eq!( + linux("cursor", Some(stdio), Some("Bearer tp_a")), + ClientConfigStatus::Stale(StaleReason::OtherCommand) + ); + assert_eq!( + linux("codex", Some(codex), None), + ClientConfigStatus::Stale(StaleReason::OtherCommand) + ); + } + + #[test] + fn codex_reads_its_toml_table() { + let text = "[mcp_servers.tablepro]\nurl = \"http://127.0.0.1:23508/mcp\"\n\ +http_headers = { Authorization = \"Bearer tp_a\" }\n"; + + assert_eq!( + linux("codex", Some(text), Some("Bearer tp_a")), + ClientConfigStatus::Current + ); + assert_eq!( + linux("codex", Some(text), Some("Bearer tp_z")), + ClientConfigStatus::Stale(StaleReason::OtherToken) + ); + } + + #[test] + fn a_client_whose_file_is_yaml_or_absent_is_unknown() { + assert_eq!( + linux("goose", Some("extensions: {}\n"), None), + ClientConfigStatus::Unknown + ); + assert_eq!(linux("jetbrains-ai", None, None), ClientConfigStatus::Unknown); + } + + #[test] + fn a_macos_entry_is_current_only_with_this_bridge() { + let bridge = ServerTarget::Stdio { + command: "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp".to_owned(), + }; + let entry = |command: &str| format!(r#"{{"mcpServers": {{"tablepro": {{"command": "{command}"}}}}}}"#); + let opencode = + |command: &str| format!(r#"{{"mcp": {{"servers": {{"tablepro": {{"command": ["{command}"]}}}}}}}}"#); + let macos = |id: &str, text: &str| status(id, Some(text), &bridge, ClientPlatform::Macos); + + assert_eq!( + macos( + "cursor", + &entry("/Applications/TablePro.app/Contents/MacOS/tablepro-mcp") + ), + ClientConfigStatus::Current + ); + assert_eq!( + macos("cursor", &entry("/gone/tablepro-mcp")), + ClientConfigStatus::Stale(StaleReason::CommandMissing) + ); + assert_eq!( + macos("cursor", &entry("/old/tablepro-mcp")), + ClientConfigStatus::Stale(StaleReason::OtherCommand) + ); + assert_eq!( + macos( + "opencode", + &opencode("/Applications/TablePro.app/Contents/MacOS/tablepro-mcp") + ), + ClientConfigStatus::Current + ); + } + + #[test] + fn an_endpoint_is_its_port_and_path() { + assert_eq!(endpoint("http://127.0.0.1:23508/mcp"), Some((23508, "/mcp".to_owned()))); + assert_eq!(endpoint("HTTP://localhost/mcp/?x=1"), Some((80, "/mcp".to_owned()))); + assert_eq!(endpoint("https://127.0.0.1:23508/mcp"), None); + assert_eq!(endpoint("127.0.0.1:23508/mcp"), None); + } +} diff --git a/core/crates/mcp/src/clients/template.rs b/core/crates/mcp/src/clients/template.rs new file mode 100644 index 0000000000..245733cc8b --- /dev/null +++ b/core/crates/mcp/src/clients/template.rs @@ -0,0 +1,504 @@ +use super::catalog::{ConfigFormat, ConfigLocation, PlatformSpec}; +use super::config_edit::{ConfigEditError, Upsert}; +use super::json_value::{JsonValue, quote}; +use super::toml_table; + +// How a client reaches TablePro: the macOS bridge it starts, or the +// Linux server's address with the header that carries the token. The +// header is unknown while the server is off and the keyring unread. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ServerTarget { + Stdio { command: String }, + Http { url: String, authorization: Option }, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum TemplateError { + #[error("the client has no entry to render")] + NoEntry, + #[error("unknown placeholder {0}")] + UnknownPlaceholder(String), + #[error("unknown filter {0}")] + UnknownFilter(String), + #[error("no value for {0}")] + MissingValue(&'static str), + #[error("a placeholder is not closed")] + Unterminated, + #[error("an entry placeholder needs the json filter")] + EntryNeedsJson, +} + +impl TemplateError { + pub fn code(&self) -> &'static str { + match self { + Self::NoEntry => "no_entry", + Self::UnknownPlaceholder(_) => "unknown_placeholder", + Self::UnknownFilter(_) => "unknown_filter", + Self::MissingValue(_) => "missing_value", + Self::Unterminated => "unterminated", + Self::EntryNeedsJson => "entry_needs_json", + } + } +} + +enum Piece { + Text(String), + Json(JsonValue), +} + +pub struct TemplateRenderer<'a> { + server_name: &'a str, + target: &'a ServerTarget, +} + +impl<'a> TemplateRenderer<'a> { + pub fn new(server_name: &'a str, target: &'a ServerTarget) -> Self { + Self { server_name, target } + } + + pub fn entry(&self, spec: &PlatformSpec) -> Result { + let template = spec.entry.as_ref().ok_or(TemplateError::NoEntry)?; + self.fill_value(template) + } + + pub fn arguments(&self, template: &[String], entry: &JsonValue) -> Result, TemplateError> { + template + .iter() + .map(|argument| self.fill(argument, Some(entry))) + .collect() + } + + pub fn url(&self, template: &str, entry: &JsonValue) -> Result { + self.fill(template, Some(entry)) + } + + fn fill_value(&self, template: &JsonValue) -> Result { + Ok(match template { + JsonValue::String(text) => JsonValue::String(self.fill(text, None)?), + JsonValue::Array(items) => JsonValue::Array( + items + .iter() + .map(|item| self.fill_value(item)) + .collect::>()?, + ), + JsonValue::Object(members) => JsonValue::Object( + members + .iter() + .map(|(name, member)| Ok((name.clone(), self.fill_value(member)?))) + .collect::>()?, + ), + scalar => scalar.clone(), + }) + } + + fn fill(&self, template: &str, entry: Option<&JsonValue>) -> Result { + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let after = &rest[open + 1..]; + let close = after.find('}').ok_or(TemplateError::Unterminated)?; + out.push_str(&self.expand(&after[..close], entry)?); + rest = &after[close + 1..]; + } + out.push_str(rest); + Ok(out) + } + + fn expand(&self, expression: &str, entry: Option<&JsonValue>) -> Result { + let mut parts = expression.split('|'); + let name = parts.next().unwrap_or_default(); + let mut piece = match name { + "name" => Piece::Text(self.server_name.to_owned()), + "url" | "authorization" | "command" => Piece::Text(self.value(name)?), + "entry" => Piece::Json(entry.ok_or(TemplateError::NoEntry)?.clone()), + "entryWithName" => Piece::Json(with_name(entry.ok_or(TemplateError::NoEntry)?, self.server_name)), + other => return Err(TemplateError::UnknownPlaceholder(other.to_owned())), + }; + for filter in parts { + piece = match (filter, piece) { + ("json", Piece::Json(value)) => Piece::Text(value.to_compact()), + ("base64", Piece::Text(text)) => Piece::Text(base64(text.as_bytes())), + ("uri", Piece::Text(text)) => Piece::Text(percent_encode(&text)), + (other, _) => return Err(TemplateError::UnknownFilter(other.to_owned())), + }; + } + match piece { + Piece::Text(text) => Ok(text), + Piece::Json(_) => Err(TemplateError::EntryNeedsJson), + } + } + + fn value(&self, name: &str) -> Result { + match (name, self.target) { + ("command", ServerTarget::Stdio { command }) => Ok(command.clone()), + ("url", ServerTarget::Http { url, .. }) => Ok(url.clone()), + ("authorization", ServerTarget::Http { authorization, .. }) => authorization + .clone() + .ok_or(TemplateError::MissingValue("authorization")), + ("command", _) => Err(TemplateError::MissingValue("command")), + ("url", _) => Err(TemplateError::MissingValue("url")), + _ => Err(TemplateError::MissingValue("authorization")), + } + } +} + +fn with_name(entry: &JsonValue, server_name: &str) -> JsonValue { + let mut members = vec![("name".to_owned(), JsonValue::String(server_name.to_owned()))]; + if let JsonValue::Object(existing) = entry { + members.extend(existing.iter().filter(|(name, _)| name != "name").cloned()); + } + JsonValue::Object(members) +} + +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let triple = chunk + .iter() + .enumerate() + .fold(0u32, |acc, (index, byte)| acc | (u32::from(*byte) << (16 - 8 * index))); + for index in 0..4 { + if index <= chunk.len() { + let sextet = (triple >> (18 - 6 * index)) & 0x3f; + out.push(char::from(ALPHABET[sextet as usize])); + } else { + out.push('='); + } + } + } + out +} + +// Everything outside RFC 3986's unreserved set is escaped. +fn percent_encode(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +// The text a user pastes: the entry under its key path, in the file's +// format. A client with no file takes the common `mcpServers` form. +pub fn snippet( + location: Option<&ConfigLocation>, + server_name: &str, + entry: &JsonValue, +) -> Result { + let Some(location) = location else { + let keyed = nest(&["mcpServers".to_owned()], server_name, entry); + return Ok(format!("{}\n", keyed.to_pretty(" ", ""))); + }; + match location.format { + ConfigFormat::Json | ConfigFormat::Jsonc => Ok(format!( + "{}\n", + nest(&location.key_path, server_name, entry).to_pretty(" ", "") + )), + ConfigFormat::Toml => toml_table::upserting("", &location.key_path, server_name, entry, Upsert::Merge), + ConfigFormat::Yaml => { + let mut out = String::new(); + write_yaml(&nest(&location.key_path, server_name, entry), "", &mut out); + Ok(out) + } + } +} + +fn nest(key_path: &[String], server_name: &str, entry: &JsonValue) -> JsonValue { + let inner = JsonValue::Object(vec![(server_name.to_owned(), entry.clone())]); + key_path + .iter() + .rev() + .fold(inner, |value, key| JsonValue::Object(vec![(key.clone(), value)])) +} + +// Block style for nested objects and lists, every string double-quoted, +// which YAML reads with JSON's escapes. +fn write_yaml(value: &JsonValue, indent: &str, out: &mut String) { + match value { + JsonValue::Object(members) => { + for (name, member) in members { + out.push_str(indent); + out.push_str(&yaml_key(name)); + out.push(':'); + write_yaml_child(member, indent, out); + } + } + JsonValue::Array(items) => { + for item in items { + out.push_str(indent); + out.push('-'); + write_yaml_child(item, indent, out); + } + } + scalar => { + out.push_str(indent); + out.push_str(&yaml_scalar(scalar)); + out.push('\n'); + } + } +} + +fn write_yaml_child(value: &JsonValue, indent: &str, out: &mut String) { + match value { + JsonValue::Object(members) if !members.is_empty() => { + out.push('\n'); + write_yaml(value, &format!("{indent} "), out); + } + JsonValue::Array(items) if !items.is_empty() => { + out.push('\n'); + write_yaml(value, &format!("{indent} "), out); + } + other => { + out.push(' '); + out.push_str(&yaml_scalar(other)); + out.push('\n'); + } + } +} + +fn yaml_key(name: &str) -> String { + match name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + && !name.is_empty() + { + true => name.to_owned(), + false => quote(name), + } +} + +fn yaml_scalar(value: &JsonValue) -> String { + match value { + JsonValue::Object(_) => "{}".to_owned(), + JsonValue::Array(_) => "[]".to_owned(), + JsonValue::String(text) => quote(text), + other => other.to_compact(), + } +} + +// A command a user can paste into a POSIX shell. The app itself never +// runs it through one. +pub fn command_line(binary: &str, arguments: &[String]) -> String { + std::iter::once(binary) + .chain(arguments.iter().map(String::as_str)) + .map(shell_word) + .collect::>() + .join(" ") +} + +fn shell_word(word: &str) -> String { + let plain = !word.is_empty() + && word + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"@%+=:,./_-".contains(&byte)); + match plain { + true => word.to_owned(), + false => format!("'{}'", word.replace('\'', r"'\''")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::clients::catalog::{ClientCatalog, ClientPlatform, InstallMethod}; + + fn http(authorization: Option<&str>) -> ServerTarget { + ServerTarget::Http { + url: "http://127.0.0.1:23508/mcp".to_owned(), + authorization: authorization.map(str::to_owned), + } + } + + fn catalog() -> ClientCatalog { + ClientCatalog::bundled().expect("the bundled catalog") + } + + #[test] + fn every_linux_entry_renders_with_the_address_and_header() { + let catalog = catalog(); + let target = http(Some("Bearer tp_abc")); + let renderer = TemplateRenderer::new(&catalog.server_name, &target); + + for client in catalog.clients_on(ClientPlatform::Linux) { + let spec = client.spec(ClientPlatform::Linux).expect("a spec"); + if spec.entry.is_none() { + continue; + } + let entry = renderer + .entry(spec) + .unwrap_or_else(|error| panic!("{}: {error}", client.id)); + let text = entry.to_compact(); + assert!(text.contains("http://127.0.0.1:23508/mcp"), "{}", client.id); + assert!(text.contains("\"Bearer tp_abc\""), "{}", client.id); + assert!( + !text.contains("{url}") && !text.contains("{authorization}"), + "{}", + client.id + ); + let location = catalog.location(client, ClientPlatform::Linux); + snippet(location, &catalog.server_name, &entry).unwrap_or_else(|error| panic!("{}: {error}", client.id)); + } + } + + #[test] + fn every_macos_entry_and_link_renders_with_the_bridge() { + let catalog = catalog(); + let target = ServerTarget::Stdio { + command: "/Applications/TablePro.app/Contents/MacOS/tablepro-mcp".to_owned(), + }; + let renderer = TemplateRenderer::new(&catalog.server_name, &target); + + for client in catalog.clients_on(ClientPlatform::Macos) { + let spec = client.spec(ClientPlatform::Macos).expect("a spec"); + let Ok(entry) = renderer.entry(spec) else { + assert!(spec.unsupported.is_some(), "{}", client.id); + continue; + }; + for method in &spec.install { + match method { + InstallMethod::Deeplink(link) => { + let url = renderer.url(&link.url, &entry).expect("a link"); + assert!(url.starts_with(&link.scheme), "{url}"); + } + InstallMethod::Cli(cli) => { + renderer.arguments(&cli.add, &entry).expect("arguments"); + } + InstallMethod::File => {} + } + } + } + } + + #[test] + fn the_claude_code_command_carries_the_whole_header_in_one_argument() { + let catalog = catalog(); + let target = http(Some("Bearer tp_abc")); + let renderer = TemplateRenderer::new(&catalog.server_name, &target); + let spec = catalog + .client("claude-code") + .and_then(|client| client.spec(ClientPlatform::Linux)) + .expect("Claude Code on Linux"); + let entry = renderer.entry(spec).expect("an entry"); + let Some(InstallMethod::Cli(cli)) = spec.install.first() else { + panic!("Claude Code installs through its CLI"); + }; + + let arguments = renderer.arguments(&cli.add, &entry).expect("arguments"); + + assert_eq!( + arguments, + [ + "mcp", + "add", + "--scope", + "user", + "--transport", + "http", + "tablepro", + "http://127.0.0.1:23508/mcp", + "--header", + "Authorization: Bearer tp_abc" + ] + ); + assert_eq!( + command_line("claude", &arguments), + "claude mcp add --scope user --transport http tablepro http://127.0.0.1:23508/mcp --header \ +'Authorization: Bearer tp_abc'" + ); + } + + #[test] + fn filters_encode_the_entry_for_a_link() { + let target = ServerTarget::Stdio { + command: "/A B/x".to_owned(), + }; + let renderer = TemplateRenderer::new("tablepro", &target); + let entry = JsonValue::Object(vec![("command".to_owned(), JsonValue::String("/A B/x".to_owned()))]); + + assert_eq!( + renderer.url("{entry|json}", &entry), + Ok(r#"{"command":"/A B/x"}"#.to_owned()) + ); + assert_eq!( + renderer.url("{entry|json|base64}", &entry), + Ok("eyJjb21tYW5kIjoiL0EgQi94In0=".to_owned()) + ); + assert_eq!( + renderer.url("{entry|json|base64|uri}", &entry), + Ok("eyJjb21tYW5kIjoiL0EgQi94In0%3D".to_owned()) + ); + assert_eq!( + renderer.url("x?{entryWithName|json|uri}", &entry), + Ok("x?%7B%22name%22%3A%22tablepro%22%2C%22command%22%3A%22%2FA%20B%2Fx%22%7D".to_owned()) + ); + assert_eq!(renderer.url("{command|uri}", &entry), Ok("%2FA%20B%2Fx".to_owned())); + assert_eq!(renderer.url("{entry}", &entry), Err(TemplateError::EntryNeedsJson)); + assert_eq!( + renderer.url("{nope}", &entry).map_err(|error| error.code()), + Err("unknown_placeholder") + ); + assert_eq!(renderer.url("{url}", &entry), Err(TemplateError::MissingValue("url"))); + } + + #[test] + fn base64_pads_to_whole_quads() { + assert_eq!(base64(b""), ""); + assert_eq!(base64(b"f"), "Zg=="); + assert_eq!(base64(b"fo"), "Zm8="); + assert_eq!(base64(b"foo"), "Zm9v"); + assert_eq!(base64(b"foob"), "Zm9vYg=="); + } + + #[test] + fn an_entry_without_the_token_cannot_be_rendered() { + let catalog = catalog(); + let target = http(None); + let spec = catalog + .client("cursor") + .and_then(|client| client.spec(ClientPlatform::Linux)) + .expect("Cursor on Linux"); + + let refused = TemplateRenderer::new(&catalog.server_name, &target).entry(spec); + + assert_eq!(refused, Err(TemplateError::MissingValue("authorization"))); + } + + #[test] + fn snippets_nest_the_entry_in_the_file_format() { + let catalog = catalog(); + let target = http(Some("Bearer tp_abc")); + let renderer = TemplateRenderer::new(&catalog.server_name, &target); + let render = |id: &str| { + let client = catalog.client(id).expect("a client"); + let spec = client.spec(ClientPlatform::Linux).expect("a spec"); + let entry = renderer.entry(spec).expect("an entry"); + snippet(catalog.location(client, ClientPlatform::Linux), "tablepro", &entry).expect("a snippet") + }; + + assert!(render("cursor").starts_with("{\n \"mcpServers\": {\n \"tablepro\": {\n \"url\"")); + assert_eq!( + render("codex"), + "[mcp_servers.tablepro]\nurl = \"http://127.0.0.1:23508/mcp\"\nhttp_headers = { Authorization = \ +\"Bearer tp_abc\" }\n" + ); + assert!(render("goose").starts_with( + "extensions:\n tablepro:\n type: \"streamable_http\"\n name: \"tablepro\"\n enabled: true\n" + )); + assert!(render("goose").contains(" headers:\n Authorization: \"Bearer tp_abc\"\n envs: {}\n")); + assert!(render("jetbrains-ai").starts_with("{\n \"mcpServers\": {\n \"tablepro\"")); + } + + #[test] + fn shell_words_are_quoted_only_when_needed() { + assert_eq!(shell_word("plain-word_1.2"), "plain-word_1.2"); + assert_eq!(shell_word("two words"), "'two words'"); + assert_eq!(shell_word("it's"), r"'it'\''s'"); + assert_eq!(shell_word(""), "''"); + } +} diff --git a/core/crates/mcp/src/clients/toml_table.rs b/core/crates/mcp/src/clients/toml_table.rs new file mode 100644 index 0000000000..ac773e2c74 --- /dev/null +++ b/core/crates/mcp/src/clients/toml_table.rs @@ -0,0 +1,365 @@ +use toml_edit::{Array, DocumentMut, InlineTable, Item, Table, TableLike, Value}; + +use super::config_edit::{ConfigEditError, Upsert}; +use super::json_value::JsonValue; + +// The server is a `[.]` table. A server written any other +// way, inline or with dotted keys, is read but never rewritten. +pub(crate) fn member(text: &str, key_path: &[String], name: &str) -> Result, ConfigEditError> { + let document = parse(text)?; + let mut table: &dyn TableLike = document.as_table(); + for (depth, key) in key_path.iter().enumerate() { + let Some(item) = table.get(key) else { + return Ok(None); + }; + table = item.as_table_like().ok_or_else(|| ConfigEditError::NotAnObject { + path: key_path[..=depth].to_vec(), + })?; + } + Ok(table.get(name).map(item_to_json)) +} + +pub(crate) fn upserting( + text: &str, + key_path: &[String], + name: &str, + value: &JsonValue, + mode: Upsert, +) -> Result { + let JsonValue::Object(members) = value else { + return Err(ConfigEditError::UnsupportedValue); + }; + let mut document = parse(text)?; + let mut table = document.as_table_mut(); + for (depth, key) in key_path.iter().enumerate() { + let current = table; + let item = current.entry(key).or_insert_with(|| { + let mut implicit = Table::new(); + implicit.set_implicit(true); + Item::Table(implicit) + }); + table = match item { + Item::Table(inner) if !inner.is_dotted() => inner, + _ => { + return Err(ConfigEditError::UnsupportedShape { + path: key_path[..=depth].to_vec(), + }); + } + }; + } + match table.get_mut(name) { + None => { + let mut server = Table::new(); + fill(&mut server, members)?; + table.insert(name, Item::Table(server)); + } + // Clearing the table keeps its header and the comments above it. + Some(Item::Table(server)) if !server.is_dotted() && mode == Upsert::Replace => { + server.clear(); + fill(server, members)?; + } + Some(Item::Table(server)) if !server.is_dotted() => merge(server, members, false)?, + Some(_) => return Err(unsupported(key_path, name)), + } + Ok(document.to_string()) +} + +pub(crate) fn removing(text: &str, key_path: &[String], name: &str) -> Result { + let mut document = parse(text)?; + let mut table = document.as_table_mut(); + for (depth, key) in key_path.iter().enumerate() { + let current = table; + table = match current.get_mut(key) { + None => return Ok(text.to_owned()), + Some(Item::Table(inner)) if !inner.is_dotted() => inner, + Some(_) => { + return Err(ConfigEditError::UnsupportedShape { + path: key_path[..=depth].to_vec(), + }); + } + }; + } + match table.get(name) { + None => return Ok(text.to_owned()), + Some(Item::Table(server)) if !server.is_dotted() => {} + Some(_) => return Err(unsupported(key_path, name)), + } + table.remove(name); + Ok(document.to_string()) +} + +pub(crate) fn members_in_scope(text: &str, scope: &[String], name: &str) -> Result, ConfigEditError> { + let document = parse(text)?; + let mut found = Vec::new(); + collect_in_scope(document.as_table(), scope, name, &mut found); + Ok(found) +} + +fn collect_in_scope(table: &dyn TableLike, scope: &[String], name: &str, found: &mut Vec) { + let Some((first, rest)) = scope.split_first() else { + found.extend(table.get(name).map(item_to_json)); + return; + }; + for (key, item) in table.iter() { + if (first == "*" || first.as_str() == key) + && let Some(inner) = item.as_table_like() + { + collect_in_scope(inner, rest, name, found); + } + } +} + +fn unsupported(key_path: &[String], name: &str) -> ConfigEditError { + let mut path = key_path.to_vec(); + path.push(name.to_owned()); + ConfigEditError::UnsupportedShape { path } +} + +fn parse(text: &str) -> Result { + text.parse::() + .map_err(|error| ConfigEditError::InvalidSyntax { + offset: error.span().map(|span| span.start), + }) +} + +fn fill(table: &mut Table, members: &[(String, JsonValue)]) -> Result<(), ConfigEditError> { + for (key, member) in members { + table.insert(key, Item::Value(to_toml(member)?)); + } + Ok(()) +} + +// Rewrites only the members given: the user's other keys and subtables +// stay, and a replaced value keeps its comment. Below the top of the +// entry, as in a header table, a key matches ignoring case. +fn merge(table: &mut dyn TableLike, members: &[(String, JsonValue)], nested: bool) -> Result<(), ConfigEditError> { + for (key, member) in members { + let Some(existing) = matching_key(table, key, nested) else { + table.insert(key, Item::Value(to_toml(member)?)); + continue; + }; + let Some(item) = table.get_mut(&existing) else { + continue; + }; + if let JsonValue::Object(inner) = member + && let Some(sub) = item.as_table_like_mut() + { + merge(sub, inner, true)?; + continue; + } + let mut value = to_toml(member)?; + if let Item::Value(old) = &*item { + *value.decor_mut() = old.decor().clone(); + } + *item = Item::Value(value); + } + Ok(()) +} + +fn matching_key(table: &dyn TableLike, key: &str, nested: bool) -> Option { + if table.contains_key(key) { + return Some(key.to_owned()); + } + nested + .then(|| { + table + .iter() + .map(|(name, _)| name) + .find(|name| name.eq_ignore_ascii_case(key)) + .map(str::to_owned) + }) + .flatten() +} + +fn to_toml(value: &JsonValue) -> Result { + Ok(match value { + JsonValue::String(text) => Value::from(text.as_str()), + JsonValue::Bool(flag) => Value::from(*flag), + JsonValue::Number(number) => match (number.as_i64(), number.as_f64()) { + (Some(integer), _) => Value::from(integer), + (None, Some(float)) => Value::from(float), + (None, None) => return Err(ConfigEditError::UnsupportedValue), + }, + JsonValue::Array(items) => Value::Array(items.iter().map(to_toml).collect::>()?), + JsonValue::Object(members) => { + let mut inline = InlineTable::new(); + for (key, member) in members { + inline.insert(key, to_toml(member)?); + } + Value::InlineTable(inline) + } + JsonValue::Null => return Err(ConfigEditError::UnsupportedValue), + }) +} + +fn item_to_json(item: &Item) -> JsonValue { + match item { + Item::Value(value) => value_to_json(value), + Item::Table(table) => table_to_json(table), + Item::ArrayOfTables(tables) => JsonValue::Array(tables.iter().map(table_to_json).collect()), + Item::None => JsonValue::Null, + } +} + +fn table_to_json(table: &Table) -> JsonValue { + JsonValue::Object( + table + .iter() + .map(|(key, item)| (key.to_owned(), item_to_json(item))) + .collect(), + ) +} + +fn value_to_json(value: &Value) -> JsonValue { + match value { + Value::String(text) => JsonValue::String(text.value().clone()), + Value::Integer(integer) => JsonValue::Number((*integer.value()).into()), + Value::Float(float) => serde_json::Number::from_f64(*float.value()).map_or(JsonValue::Null, JsonValue::Number), + Value::Boolean(flag) => JsonValue::Bool(*flag.value()), + Value::Datetime(datetime) => JsonValue::String(datetime.value().to_string()), + Value::Array(items) => JsonValue::Array(items.iter().map(value_to_json).collect()), + Value::InlineTable(table) => JsonValue::Object( + table + .iter() + .map(|(key, member)| (key.to_owned(), value_to_json(member))) + .collect(), + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn path() -> Vec { + vec!["mcp_servers".to_owned()] + } + + fn entry(url: &str) -> JsonValue { + JsonValue::Object(vec![ + ("url".to_owned(), JsonValue::String(url.to_owned())), + ( + "http_headers".to_owned(), + JsonValue::Object(vec![( + "Authorization".to_owned(), + JsonValue::String("Bearer tp_x".to_owned()), + )]), + ), + ]) + } + + #[test] + fn a_new_server_table_is_added_and_the_rest_is_kept() { + let text = "# Codex\nmodel = \"o4\"\n\n[mcp_servers.other]\ncommand = \"/bin/other\" # keep\n"; + + let edited = upserting( + text, + &path(), + "tablepro", + &entry("http://127.0.0.1:1/mcp"), + Upsert::Merge, + ) + .expect("an edit"); + + assert_eq!( + edited, + "# Codex\nmodel = \"o4\"\n\n[mcp_servers.other]\ncommand = \"/bin/other\" # keep\n\n\ +[mcp_servers.tablepro]\nurl = \"http://127.0.0.1:1/mcp\"\nhttp_headers = { Authorization = \"Bearer tp_x\" }\n" + ); + assert_eq!( + member(&edited, &path(), "tablepro").expect("readable"), + Some(entry("http://127.0.0.1:1/mcp")) + ); + } + + #[test] + fn an_update_rewrites_only_what_the_entry_renders() { + let text = "[mcp_servers.tablepro]\nurl = \"old\" # mine\nstartup_timeout_sec = 20\n\n\ +[mcp_servers.tablepro.env]\nA = \"1\"\n\n[profile]\nx = 1\n"; + + let edited = upserting(text, &path(), "tablepro", &entry("new"), Upsert::Merge).expect("an edit"); + + assert!( + edited.starts_with("[mcp_servers.tablepro]\nurl = \"new\" # mine\nstartup_timeout_sec = 20\n"), + "{edited}" + ); + assert!( + edited.contains("http_headers = { Authorization = \"Bearer tp_x\" }"), + "{edited}" + ); + assert!(edited.contains("[mcp_servers.tablepro.env]\nA = \"1\"\n"), "{edited}"); + assert!(edited.ends_with("[profile]\nx = 1\n"), "{edited}"); + let server = member(&edited, &path(), "tablepro") + .expect("readable") + .expect("the server"); + assert_eq!(server.get("url"), Some(&JsonValue::String("new".to_owned()))); + assert!(server.get("env").is_some() && server.get("startup_timeout_sec").is_some()); + } + + #[test] + fn an_update_keeps_other_headers_and_the_spelling_of_the_one_it_replaces() { + let text = "[mcp_servers.tablepro]\nurl = \"old\"\n\n[mcp_servers.tablepro.http_headers]\n\ +authorization = \"Bearer tp_old\"\nX-Team = \"data\"\n"; + + let edited = upserting(text, &path(), "tablepro", &entry("new"), Upsert::Merge).expect("an edit"); + + assert!( + edited + .contains("[mcp_servers.tablepro.http_headers]\nauthorization = \"Bearer tp_x\"\nX-Team = \"data\"\n"), + "{edited}" + ); + assert!( + !edited.contains("Authorization") && !edited.contains("tp_old"), + "{edited}" + ); + } + + #[test] + fn a_server_written_inline_or_dotted_is_read_but_not_rewritten() { + let inline = "[mcp_servers]\ntablepro = { url = \"x\" }\n"; + let dotted = "mcp_servers.tablepro.url = \"x\"\n"; + + assert!(member(inline, &path(), "tablepro").expect("readable").is_some()); + assert_eq!( + upserting(inline, &path(), "tablepro", &entry("y"), Upsert::Merge).map_err(|error| error.code()), + Err("unsupported_shape") + ); + assert_eq!( + upserting(dotted, &path(), "tablepro", &entry("y"), Upsert::Merge).map_err(|error| error.code()), + Err("unsupported_shape") + ); + assert_eq!( + removing(inline, &path(), "tablepro").map_err(|error| error.code()), + Err("unsupported_shape") + ); + } + + #[test] + fn removing_takes_only_the_server_table() { + let text = "a = 1\n\n[mcp_servers.tablepro]\nurl = \"x\"\n\n[mcp_servers.other]\ncommand = \"y\"\n"; + + let removed = removing(text, &path(), "tablepro").expect("an edit"); + + assert_eq!(removed, "a = 1\n\n[mcp_servers.other]\ncommand = \"y\"\n"); + assert_eq!(removing(&removed, &path(), "tablepro").expect("no edit"), removed); + } + + #[test] + fn every_server_in_a_scope_is_found() { + let text = "[projects.a.mcp_servers.tablepro]\nurl = \"x\"\n\n[projects.b.mcp_servers.other]\nurl = \"y\"\n"; + let scope: Vec = ["projects", "*", "mcp_servers"].map(str::to_owned).to_vec(); + + let found = members_in_scope(text, &scope, "tablepro").expect("readable"); + + assert_eq!(found.len(), 1); + assert_eq!(found[0].get("url"), Some(&JsonValue::String("x".to_owned()))); + } + + #[test] + fn a_broken_file_is_refused() { + assert_eq!( + upserting("[mcp_servers\n", &path(), "tablepro", &entry("y"), Upsert::Merge).map_err(|error| error.code()), + Err("invalid_syntax") + ); + } +} diff --git a/core/crates/mcp/src/lib.rs b/core/crates/mcp/src/lib.rs index 8a2390a60b..2f370582d6 100644 --- a/core/crates/mcp/src/lib.rs +++ b/core/crates/mcp/src/lib.rs @@ -6,13 +6,17 @@ mod access_token; mod browse_request; +pub mod clients; mod collected_results; mod connection_tools; mod export_tools; mod mcp_host; mod mcp_server; +#[cfg(any(target_os = "linux", test))] +mod peer_owner; mod query_tools; mod schema_tools; +mod seen_clients; mod token_vault; mod tool_args; mod tool_context; @@ -25,6 +29,7 @@ pub use export_tools::MAX_EXPORT_TABLES; pub use mcp_host::{McpHost, OpenOutcome, WriteApproval}; pub use mcp_server::{MCP_PATH, McpServer, StartError}; pub use query_tools::{DEFAULT_ROWS, DEFAULT_TIMEOUT_SECONDS, MAX_QUERY_BYTES, MAX_ROWS, MAX_TIMEOUT_SECONDS}; +pub use seen_clients::SeenClient; pub use token_vault::{ObtainError, TokenVault, obtain_token, replace_token}; pub use tool_context::ToolContext; pub use tool_server::catalog; diff --git a/core/crates/mcp/src/mcp_server.rs b/core/crates/mcp/src/mcp_server.rs index 71e0f691d6..5787faaaaa 100644 --- a/core/crates/mcp/src/mcp_server.rs +++ b/core/crates/mcp/src/mcp_server.rs @@ -1,5 +1,7 @@ use std::convert::Infallible; use std::net::{Ipv4Addr, SocketAddr}; +#[cfg(target_os = "linux")] +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, PoisonError, RwLock}; use std::time::Duration; @@ -16,11 +18,14 @@ use rmcp::transport::streamable_http_server::session::local::LocalSessionManager use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService}; use tablepro_session::runtime::Tasks; use tokio::net::{TcpListener, TcpStream}; -use tokio::sync::Semaphore; +use tokio::sync::{Semaphore, watch}; use tokio_util::sync::CancellationToken; use tokio_util::task::AbortOnDropHandle; use crate::access_token::AccessToken; +#[cfg(target_os = "linux")] +use crate::peer_owner::{self, PeerOwner}; +use crate::seen_clients::{SeenClient, SeenClients}; use crate::tool_context::ToolContext; use crate::tool_server::ToolServer; @@ -56,6 +61,7 @@ pub enum StartError { pub struct McpServer { address: SocketAddr, token: Arc>, + seen: SeenClients, cancel: CancellationToken, accept: Option>, } @@ -79,7 +85,8 @@ impl McpServer { .local_addr() .map_err(|source| StartError::Listen { port, source })?; let cancel = CancellationToken::new(); - let tools = ToolServer::new(context, version); + let seen = SeenClients::new(); + let tools = ToolServer::new(context, version, seen.clone()); // Stateless: a client keeps nothing on the server between calls, // and the answers are plain JSON with no stream to hold open. let config = StreamableHttpServerConfig::default() @@ -96,6 +103,7 @@ impl McpServer { Ok(Self { address, token, + seen, cancel, accept: Some(accept), }) @@ -105,6 +113,11 @@ impl McpServer { self.address } + // Each client that has started a session since the server started. + pub fn seen_clients(&self) -> watch::Receiver> { + self.seen.subscribe() + } + /// Stop, and return once the port is free again, so a restart on the /// same port can bind it. pub async fn shutdown(mut self) { @@ -155,18 +168,33 @@ async fn accept( } }, }; - let (service, token, cancel) = (service.clone(), token.clone(), cancel.clone()); + let (service, token, cancel, checks) = (service.clone(), token.clone(), cancel.clone(), tasks.clone()); drop(tasks.spawn_task(async move { - serve(stream, service, token, cancel).await; + serve(stream, service, token, cancel, &checks).await; drop(permit); })); } } -async fn serve(stream: TcpStream, service: Service, token: Arc>, cancel: CancellationToken) { +async fn serve( + stream: TcpStream, + service: Service, + token: Arc>, + cancel: CancellationToken, + tasks: &Tasks, +) { + let allowed = same_account(&stream, tasks).await; let handler = service_fn(move |request: Request| { let (service, token) = (service.clone(), token.clone()); - async move { Ok::<_, Infallible>(respond(&service, &token, request).await) } + async move { + Ok::<_, Infallible>(match allowed { + true => respond(&service, &token, request).await, + false => plain( + StatusCode::FORBIDDEN, + "TablePro serves only programs of the user it runs as", + ), + }) + } }); let mut builder = http1::Builder::new(); builder.timer(TokioTimer::new()).header_read_timeout(HEADER_TIMEOUT); @@ -185,6 +213,38 @@ async fn serve(stream: TcpStream, service: Service, token: Arc bool { + static UNKNOWN_LOGGED: AtomicBool = AtomicBool::new(false); + let owner = match (stream.local_addr(), stream.peer_addr()) { + (Ok(SocketAddr::V4(server)), Ok(SocketAddr::V4(peer))) => tasks + .spawn_blocking_task(move || peer_owner::owner_of(server, peer)) + .await + .unwrap_or(PeerOwner::Unknown), + _ => PeerOwner::Unknown, + }; + match owner { + PeerOwner::Same => true, + PeerOwner::Other => { + tracing::debug!("refused an MCP connection from another user"); + false + } + PeerOwner::Unknown => { + if !UNKNOWN_LOGGED.swap(true, Ordering::Relaxed) { + tracing::warn!("refused an MCP connection whose user could not be read from /proc/net/tcp"); + } + false + } + } +} + +#[cfg(not(target_os = "linux"))] +async fn same_account(_stream: &TcpStream, _tasks: &Tasks) -> bool { + true +} + /// Every request presents the token before anything reads its body. async fn respond(service: &Service, token: &RwLock, request: Request) -> Response { if request.uri().path() != MCP_PATH { diff --git a/core/crates/mcp/src/peer_owner.rs b/core/crates/mcp/src/peer_owner.rs new file mode 100644 index 0000000000..9838e9cdf0 --- /dev/null +++ b/core/crates/mcp/src/peer_owner.rs @@ -0,0 +1,222 @@ +// The uid owning each end of a loopback connection, from /proc/net/tcp, +// and /proc/net/tcp6 for a v4-mapped IPv6 socket such as Java's. + +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PeerOwner { + Same, + Other, + Unknown, +} + +// A socket in TIME_WAIT keeps its addresses but is listed with uid 0. +const TIME_WAIT: &str = "06"; + +#[cfg(target_os = "linux")] +const TABLES: [&str; 2] = ["/proc/net/tcp", "/proc/net/tcp6"]; + +// Blocking: reads the kernel's tables. +#[cfg(target_os = "linux")] +pub(crate) fn owner_of(server: SocketAddrV4, peer: SocketAddrV4) -> PeerOwner { + let tables: Vec = TABLES + .iter() + .filter_map(|path| std::fs::read_to_string(path).ok()) + .collect(); + let tables: Vec<&str> = tables.iter().map(String::as_str).collect(); + owner(&tables, server, peer) +} + +// The server's own end gives the uid to compare, mapped through the same +// user namespace as the peer's, as inside the Flatpak. +pub(crate) fn owner(tables: &[&str], server: SocketAddrV4, peer: SocketAddrV4) -> PeerOwner { + let mut ours = None; + let mut theirs = None; + for socket in tables.iter().flat_map(|table| table.lines()).filter_map(Socket::parse) { + if socket.state == TIME_WAIT { + continue; + } + if socket.local == server && socket.remote == peer { + ours = Some(socket.uid); + } else if socket.local == peer && socket.remote == server { + theirs = Some(socket.uid); + } + } + match (ours, theirs) { + (Some(ours), Some(theirs)) if ours == theirs => PeerOwner::Same, + (Some(_), Some(_)) => PeerOwner::Other, + _ => PeerOwner::Unknown, + } +} + +struct Socket<'a> { + local: SocketAddrV4, + remote: SocketAddrV4, + state: &'a str, + uid: u32, +} + +impl<'a> Socket<'a> { + // `sl local_address rem_address st tx:rx tr:when retrnsmt uid ...`; + // the header line and IPv6 sockets with no IPv4 address give None. + fn parse(line: &'a str) -> Option { + let fields: Vec<&str> = line.split_whitespace().collect(); + Some(Self { + local: address(fields.get(1)?)?, + remote: address(fields.get(2)?)?, + state: fields.get(3)?, + uid: fields.get(7)?.parse().ok()?, + }) + } +} + +// The kernel prints each 32-bit word of the address as the number its +// bytes make in the host's order, and the port as a plain number. +fn address(text: &str) -> Option { + let (host, port) = text.split_once(':')?; + let port = u16::from_str_radix(port, 16).ok()?; + let ip = match host.len() { + 8 => Ipv4Addr::from(word(host)?), + 32 => { + let mut bytes = [0u8; 16]; + for (index, chunk) in bytes.as_chunks_mut::<4>().0.iter_mut().enumerate() { + *chunk = word(host.get(index * 8..index * 8 + 8)?)?; + } + Ipv6Addr::from(bytes).to_ipv4_mapped()? + } + _ => return None, + }; + Some(SocketAddrV4::new(ip, port)) +} + +fn word(digits: &str) -> Option<[u8; 4]> { + if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + u32::from_str_radix(digits, 16).ok().map(u32::to_ne_bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEADER: &str = + " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode"; + + fn server() -> SocketAddrV4 { + SocketAddrV4::new(Ipv4Addr::LOCALHOST, 23508) + } + + fn peer() -> SocketAddrV4 { + SocketAddrV4::new(Ipv4Addr::LOCALHOST, 53924) + } + + fn hex_word(bytes: [u8; 4]) -> String { + format!("{:08X}", u32::from_ne_bytes(bytes)) + } + + fn v4(address: SocketAddrV4) -> String { + format!("{}:{:04X}", hex_word(address.ip().octets()), address.port()) + } + + fn mapped(address: SocketAddrV4) -> String { + format!( + "{}{}{}{}:{:04X}", + hex_word([0; 4]), + hex_word([0; 4]), + hex_word([0, 0, 0xff, 0xff]), + hex_word(address.ip().octets()), + address.port() + ) + } + + fn line(local: &str, remote: &str, state: &str, uid: u32) -> String { + format!( + " 3: {local} {remote} {state} 00000000:00000000 00:00000000 00000000 {uid} 0 48211 1 \ +0000000000000000 20 4 30 10 -1" + ) + } + + fn table(lines: &[String]) -> String { + std::iter::once(HEADER.to_owned()) + .chain(lines.iter().cloned()) + .collect::>() + .join("\n") + } + + #[test] + fn a_peer_of_the_same_account_is_the_same_owner() { + let tcp = table(&[ + line(&v4(server()), "00000000:0000", "0A", 1000), + line(&v4(server()), &v4(peer()), "01", 1000), + line(&v4(peer()), &v4(server()), "01", 1000), + ]); + + assert_eq!(owner(&[&tcp], server(), peer()), PeerOwner::Same); + } + + #[test] + fn a_peer_of_another_account_is_another_owner() { + let tcp = table(&[ + line(&v4(server()), &v4(peer()), "01", 1000), + line(&v4(peer()), &v4(server()), "01", 1001), + ]); + + assert_eq!(owner(&[&tcp], server(), peer()), PeerOwner::Other); + } + + #[test] + fn a_peer_missing_from_the_tables_is_unknown() { + let tcp = table(&[line(&v4(server()), &v4(peer()), "01", 1000)]); + let only_time_wait = table(&[ + line(&v4(server()), &v4(peer()), "01", 1000), + line(&v4(peer()), &v4(server()), TIME_WAIT, 0), + ]); + + assert_eq!(owner(&[&tcp], server(), peer()), PeerOwner::Unknown); + assert_eq!(owner(&[&only_time_wait], server(), peer()), PeerOwner::Unknown); + assert_eq!(owner(&[], server(), peer()), PeerOwner::Unknown); + assert_eq!(owner(&["garbage\n1: x y"], server(), peer()), PeerOwner::Unknown); + } + + #[test] + fn a_peer_on_an_ipv6_socket_is_found_through_its_mapped_address() { + let tcp = table(&[line(&v4(server()), &v4(peer()), "01", 1000)]); + let tcp6 = table(&[line(&mapped(peer()), &mapped(server()), "01", 1000)]); + let other6 = table(&[line(&mapped(peer()), &mapped(server()), "01", 65534)]); + + assert_eq!(owner(&[&tcp, &tcp6], server(), peer()), PeerOwner::Same); + assert_eq!(owner(&[&tcp, &other6], server(), peer()), PeerOwner::Other); + } + + #[cfg(target_endian = "little")] + #[test] + fn a_line_as_the_kernel_prints_it_is_read() { + let socket = Socket::parse( + " 0: 0100007F:5BD4 0100007F:D2A4 01 00000000:00000000 00:00000000 00000000 1000 0 9", + ) + .expect("a socket"); + + assert_eq!(socket.local, server()); + assert_eq!(socket.remote, peer()); + assert_eq!(socket.uid, 1000); + assert!(Socket::parse(HEADER).is_none()); + } + + #[cfg(target_os = "linux")] + #[test] + fn a_connection_from_this_process_is_the_same_owner() { + let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("a listener"); + let client = std::net::TcpStream::connect(listener.local_addr().expect("an address")).expect("a connection"); + let (accepted, _) = listener.accept().expect("the connection"); + let (std::net::SocketAddr::V4(server), std::net::SocketAddr::V4(peer)) = ( + accepted.local_addr().expect("an address"), + accepted.peer_addr().expect("an address"), + ) else { + panic!("an IPv4 connection"); + }; + + assert_eq!(owner_of(server, peer), PeerOwner::Same); + drop(client); + } +} diff --git a/core/crates/mcp/src/seen_clients.rs b/core/crates/mcp/src/seen_clients.rs new file mode 100644 index 0000000000..76fe6d5f61 --- /dev/null +++ b/core/crates/mcp/src/seen_clients.rs @@ -0,0 +1,168 @@ +use std::sync::Arc; +use std::time::SystemTime; + +use rmcp::model::Implementation; +use tokio::sync::watch; + +// Only a client holding the token gets this far, but its name is shown +// to the user, so the list and each text stay small. +const MAX_CLIENTS: usize = 32; +const MAX_TEXT_CHARS: usize = 120; + +// A client as it named itself, in `initialize` or in a request's +// `_meta`. The server is stateless, so this is the last time it started +// a session, not a live connection. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SeenClient { + pub name: String, + pub title: Option, + pub version: String, + pub seen_at: SystemTime, +} + +#[derive(Clone)] +pub(crate) struct SeenClients(Arc>>); + +impl SeenClients { + pub(crate) fn new() -> Self { + Self(Arc::new(watch::channel(Vec::new()).0)) + } + + pub(crate) fn subscribe(&self) -> watch::Receiver> { + self.0.subscribe() + } + + // A handshake: the latest one moves a client to the end of the list. + pub(crate) fn record(&self, client: &Implementation, at: SystemTime) { + let Some(seen) = sighting(client, at) else { + return; + }; + self.0.send_modify(|clients| { + clients.retain(|known| known.name != seen.name); + push(clients, seen); + }); + } + + // A client that names itself on every request, as one on the + // 2026-07-28 protocol does: only its first request counts, so a + // listener hears of it once rather than per call. + pub(crate) fn record_new(&self, client: &Implementation, at: SystemTime) { + let Some(seen) = sighting(client, at) else { + return; + }; + self.0.send_if_modified(|clients| { + if clients.iter().any(|known| known.name == seen.name) { + return false; + } + push(clients, seen); + true + }); + } +} + +fn sighting(client: &Implementation, at: SystemTime) -> Option { + let name = clip(&client.name); + if name.is_empty() { + return None; + } + Some(SeenClient { + title: client.title.as_deref().map(clip).filter(|title| !title.is_empty()), + version: clip(&client.version), + seen_at: at, + name, + }) +} + +fn push(clients: &mut Vec, seen: SeenClient) { + if clients.len() >= MAX_CLIENTS { + clients.remove(0); + } + clients.push(seen); +} + +fn clip(text: &str) -> String { + text.trim() + .chars() + .filter(|character| !character.is_control()) + .take(MAX_TEXT_CHARS) + .collect() +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[test] + fn a_client_seen_again_keeps_one_entry_at_the_end() { + let seen = SeenClients::new(); + let receiver = seen.subscribe(); + let start = SystemTime::UNIX_EPOCH; + + seen.record(&Implementation::new("claude-code", "2.1"), start); + seen.record(&Implementation::new("Zed", "1.27").with_title("Zed"), start); + seen.record( + &Implementation::new("claude-code", "2.2"), + start + Duration::from_secs(5), + ); + + let clients = receiver.borrow().clone(); + let names: Vec<&str> = clients.iter().map(|client| client.name.as_str()).collect(); + assert_eq!(names, ["Zed", "claude-code"]); + assert_eq!(clients[1].version, "2.2"); + assert_eq!(clients[1].seen_at, start + Duration::from_secs(5)); + assert_eq!(clients[0].title.as_deref(), Some("Zed")); + } + + #[test] + fn a_nameless_client_is_ignored_and_the_list_is_bounded() { + let seen = SeenClients::new(); + + seen.record(&Implementation::new(" ", "1"), SystemTime::UNIX_EPOCH); + for index in 0..MAX_CLIENTS + 5 { + seen.record(&Implementation::new(format!("c{index}"), "1"), SystemTime::UNIX_EPOCH); + } + + let clients = seen.subscribe().borrow().clone(); + assert_eq!(clients.len(), MAX_CLIENTS); + assert_eq!(clients[0].name, "c5"); + } + + #[test] + fn a_client_named_on_every_request_is_recorded_once() { + let seen = SeenClients::new(); + let mut receiver = seen.subscribe(); + let start = SystemTime::UNIX_EPOCH; + + seen.record_new(&Implementation::new("claude-code", "3.0"), start); + assert!(receiver.has_changed().expect("a sender")); + receiver.borrow_and_update(); + seen.record_new( + &Implementation::new("claude-code", "3.0"), + start + Duration::from_secs(5), + ); + + assert!( + !receiver.has_changed().expect("a sender"), + "a second call was announced" + ); + let clients = receiver.borrow().clone(); + assert_eq!(clients.len(), 1); + assert_eq!(clients[0].seen_at, start); + } + + #[test] + fn names_lose_control_characters_and_excess_length() { + let seen = SeenClients::new(); + + seen.record( + &Implementation::new(format!("a\u{1b}[31m{}", "x".repeat(500)), "1"), + SystemTime::UNIX_EPOCH, + ); + + let name = seen.subscribe().borrow()[0].name.clone(); + assert!(name.starts_with("a[31m")); + assert_eq!(name.chars().count(), MAX_TEXT_CHARS); + } +} diff --git a/core/crates/mcp/src/tool_server.rs b/core/crates/mcp/src/tool_server.rs index 0035a7c2c2..d7143353aa 100644 --- a/core/crates/mcp/src/tool_server.rs +++ b/core/crates/mcp/src/tool_server.rs @@ -1,15 +1,18 @@ use std::sync::Arc; +use std::time::SystemTime; use rmcp::handler::server::common::schema_for_type; use rmcp::model::{ - CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation, ListToolsResult, - PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool, ToolAnnotations, + CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, DiscoverResult, Implementation, + InitializeRequestParams, InitializeResult, ListToolsResult, PaginatedRequestParams, ServerCapabilities, + ServerConfig, Tool, ToolAnnotations, }; use rmcp::service::RequestContext; use rmcp::{ErrorData, RoleServer, ServerHandler}; use schemars::JsonSchema; use serde::de::DeserializeOwned; +use crate::seen_clients::SeenClients; use crate::tool_args::{ BrowseArgs, ConnectionArgs, CountArgs, DatabaseArgs, ExportArgs, NoArgs, QueryArgs, SchemaArgs, TableArgs, }; @@ -32,13 +35,24 @@ statement's or a browse's answer cuts a value longer than 64 KB; its notes say w pub struct ToolServer { context: ToolContext, version: Arc, + seen: SeenClients, } impl ToolServer { - pub fn new(context: ToolContext, version: &str) -> Self { + pub(crate) fn new(context: ToolContext, version: &str, seen: SeenClients) -> Self { Self { context, version: Arc::from(version), + seen, + } + } + + // A client on the 2026-07-28 protocol never sends `initialize`; it + // names itself in each request's `_meta`. Only that is read: rmcp's + // fallback for a stateless request is a placeholder, not the client. + fn note_client(&self, context: &RequestContext) { + if let Some(client) = context.meta.client_info() { + self.seen.record_new(&client, SystemTime::now()); } } @@ -78,11 +92,30 @@ impl ServerHandler for ToolServer { .with_instructions(INSTRUCTIONS) } + async fn initialize( + &self, + request: InitializeRequestParams, + context: RequestContext, + ) -> Result { + self.seen.record(&request.client_info, SystemTime::now()); + context.peer.set_peer_info(request.clone()); + self.negotiate_initialize(&request) + } + + async fn discover(&self, context: RequestContext) -> Result { + self.note_client(&context); + Ok(DiscoverResult::from_server_info( + self.supported_protocol_versions().into_owned(), + self.get_info(), + )) + } + async fn list_tools( &self, _request: Option, - _context: RequestContext, + context: RequestContext, ) -> Result { + self.note_client(&context); Ok(ListToolsResult::with_all_items(catalog())) } @@ -95,6 +128,7 @@ impl ServerHandler for ToolServer { request: CallToolRequestParams, context: RequestContext, ) -> Result { + self.note_client(&context); let name = request.name.clone(); let result = match self.dispatch(request, &context).await { Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]), diff --git a/core/crates/mcp/tests/mcp_server.rs b/core/crates/mcp/tests/mcp_server.rs index 3e4a7b807e..1ccc1c9fb4 100644 --- a/core/crates/mcp/tests/mcp_server.rs +++ b/core/crates/mcp/tests/mcp_server.rs @@ -475,6 +475,116 @@ async fn initialize_names_the_server_and_lists_every_tool() { } } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_client_that_initializes_is_seen_once_by_its_own_name() { + let harness = harness().await; + let port = harness.server.address().port(); + let mut seen = harness.server.seen_clients(); + let initialize = |name: &str, version: &str| { + json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": { "name": name, "title": "Claude Code", "version": version }, + }, + }) + .to_string() + }; + + let anonymous = send(port, "/mcp", &MCP_HEADERS[1..], &initialize("intruder", "1")).await; + assert_eq!(anonymous.status, 401); + assert!( + seen.borrow_and_update().is_empty(), + "a client without the token was recorded" + ); + + for version in ["2.1.321", "2.1.322"] { + let reply = send(port, "/mcp", &MCP_HEADERS, &initialize("claude-code", version)).await; + assert_eq!(reply.status, 200, "{}", reply.body); + } + + tokio::time::timeout(Duration::from_secs(10), seen.changed()) + .await + .expect("a sighting in time") + .expect("the server still running"); + let clients = seen.borrow().clone(); + assert_eq!(clients.len(), 1, "{clients:?}"); + assert_eq!(clients[0].name, "claude-code"); + assert_eq!(clients[0].title.as_deref(), Some("Claude Code")); + assert_eq!(clients[0].version, "2.1.322"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_client_that_never_initializes_is_seen_once_from_its_requests() { + let harness = harness().await; + let port = harness.server.address().port(); + let mut seen = harness.server.seen_clients(); + let request = |method: &str, mut params: Json| { + params["_meta"] = json!({ + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": { "name": "claude-code", "title": "Claude Code", "version": "3.0.0" }, + }); + json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params }).to_string() + }; + let headers = |method: &'static str, name: Option<&'static str>| { + let mut headers = vec![ + MCP_HEADERS[0], + MCP_HEADERS[1], + MCP_HEADERS[2], + ("MCP-Protocol-Version", "2026-07-28"), + ("Mcp-Method", method), + ]; + headers.extend(name.map(|name| ("Mcp-Name", name))); + headers + }; + let answered = |reply: Reply| { + assert_eq!(reply.status, 200, "{}", reply.body); + assert!(reply.body.contains("\"result\""), "{}", reply.body); + }; + + answered( + send( + port, + "/mcp", + &headers("server/discover", None), + &request("server/discover", json!({})), + ) + .await, + ); + + assert!(seen.has_changed().expect("the server running"), "discover was not seen"); + let clients = seen.borrow_and_update().clone(); + assert_eq!(clients.len(), 1, "{clients:?}"); + assert_eq!(clients[0].name, "claude-code"); + assert_eq!(clients[0].title.as_deref(), Some("Claude Code")); + answered( + send( + port, + "/mcp", + &headers("tools/list", None), + &request("tools/list", json!({})), + ) + .await, + ); + answered( + send( + port, + "/mcp", + &headers("tools/call", Some("list_connections")), + &request("tools/call", json!({ "name": "list_connections", "arguments": {} })), + ) + .await, + ); + assert!( + !seen.has_changed().expect("the server running"), + "every call announced the client again" + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_blocked_connection_is_not_listed_and_does_not_exist() { let harness = harness().await; diff --git a/core/docs/decisions/0023-mcp-client-setup-from-one-catalog.md b/core/docs/decisions/0023-mcp-client-setup-from-one-catalog.md new file mode 100644 index 0000000000..ddc93884ff --- /dev/null +++ b/core/docs/decisions/0023-mcp-client-setup-from-one-catalog.md @@ -0,0 +1,60 @@ +# 0023: Both apps set up MCP clients from one catalog + +- **Status**: Accepted +- **Date**: 2026-11-12 + +## Context + +Both apps run a local MCP server, and each AI client needs an entry that points at it. The macOS app printed a snippet for four clients from two hand-written lists and read nothing back; the Linux app offered the address and the token to copy ([#4196](https://github.com/TableProApp/TablePro/issues/4196)). Each client keeps its servers its own way: a JSON, JSON with comments, TOML or YAML file, a command of its own, or a deeplink. Paths differ by OS, and some clients run on one OS only. + +## Decision + +Both apps read one catalog, `core/crates/mcp/clients.json`, and set a client up through the first method it offers: its deeplink, its CLI, a merge into its config file, else a copy to paste. + +### The catalog + +- Bundled with each app, never fetched. The Rust crates take it through `include_str!` in `tablepro_mcp::clients`; the macOS app ships it as a resource and decodes it in `TableProMCPClients`. +- Each client has an id, its brand name, an icon slug, the `clientInfo` names it connects with, and per OS its detect rules, entry template, install methods in priority order and when the change applies. A client with no entry for an OS is not listed there. +- No sentences: a status or a reason is a code, which each app words in its own catalog. + +### Install order + +1. **Deeplink**, offered only when an app handles its scheme. The Linux app offers none. +2. **The client's CLI**, such as `claude mcp add`, run argument by argument, never through a shell, and never inside the Flatpak, which cannot start host programs. On Linux the token goes through argv only for Claude Code, which takes a header no other non-interactive way. +3. **A merge into the client's config file**: a text splice that keeps comments, key order and indentation and touches only TablePro's entry; Codex's TOML only as a `[mcp_servers.tablepro]` table. In an entry already there it writes over only what reaches TablePro: the members whose catalog value holds a placeholder at any depth, such as `headers.Authorization`, plus `type` and `args`. Any other member the catalog names, such as `tools` or `disabled`, is written only where the entry lacks it, so an update never widens a restriction the user set. An entry for the other transport, a `command` where a `url` goes or the reverse, is replaced whole. A symlink is written through and stays a link. The file as it was is kept as `.tablepro-backup`, replaced on each write. A new file is created 0600. Refused when the file cannot be read or parsed, names a key twice, or the catalog marks it not writable, as for YAML and the files a client's own CLI manages. +4. **Copy**, always offered: the command or the fragment, with the token where the entry needs one. + +### What counts as set up + +- The entry at the catalog's key path, or at an `alternateKeyPaths` one, an older layout of the same file, compared with what TablePro would write: the bridge on macOS, the port and the token on Linux. +- An entry the client turned off, with `"disabled": true`, `"enabled": false` or TOML `enabled = false`, is set up but off whatever its command, address or token, and offers no install or update. +- An entry where an HTTP one goes that still names a `command` is stale, since the client may start that program and never read the address. +- A stale entry in an `otherScopes` scope, such as a Claude Code project's own, makes the client stale even when the user's entry is current, since the client uses it there first. + +### What the entry holds + +- macOS: every entry starts the app's stdio bridge, so no token is written anywhere. +- Linux: there is no bridge ([Linux 0022](../../../linux/docs/decisions/0022-ai-assistant-and-mcp-server.md)), so the entry holds the URL and an `Authorization` header with the token, in a file only the user can read. TablePro narrows `~/.claude.json` to the user too after `claude mcp add` writes it. +- The Linux server serves a connection only when the socket at its other end belongs to the user TablePro runs as, read from `/proc/net/tcp` and `/proc/net/tcp6`, and refuses it with 403 when it belongs to another account or cannot be found. So a token another account reads, from a file or from a command line, does not work from that account. + +### Brand marks + +- Simple Icons files, published under CC0, or, where it has none, the brand's own published file, used as shipped and never redrawn. +- They stay their owners' trademarks and only name the client. A file under another license is listed with its notice in the app's third-party notices. + +## Consequences + +- A new client or a moved path is one edit to the catalog, and each app's tests render every entry for its OS. +- TablePro writes other apps' files. A file it cannot edit without losing something is left alone, and the copy still works. +- A client that changes its file layout or its CLI breaks the install until the catalog follows. +- On Linux the token is in the client's file, as it was when pasted by hand, and in Claude Code's argv while `claude mcp add` runs, where another account can read it. It works only from the user's own account. Regenerate leaves every written copy stale; while the server runs, the page offers Update. +- Where `/proc/net/tcp` cannot be read, the Linux server refuses every client, and logs it once. +- A client the server cannot reach, such as Claude Desktop on Linux, which starts only stdio servers, is listed with the reason and no action. + +## Alternatives considered + +- **A list in each app.** The paths and the entries are the same facts on both, and two lists drift. +- **A catalog fetched from the network.** What TablePro writes into another app's file would change without a release. +- **Parsing and rewriting the file with a JSON or TOML library.** It drops comments and reorders keys in a file the user owns. +- **Running the CLI through a login shell to find it.** The user's profile runs on every install and every argument needs quoting; the macOS process launcher refuses an app-authored shell. +- **Writing `~/.claude.json` for Claude Code on Linux.** The CLI owns that file and rewrites it while it runs. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index 999d23906b..153e454636 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -30,3 +30,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0020](0020-a-run-keeps-a-byte-limit-of-rows.md) | A run keeps a byte limit of rows | Accepted | `RunOptions::byte_limit`, 256 MB by default, bounds the rows an editor run keeps, measured by `Value::retained_bytes`; the session wraps every editor session in `ByteLimitSink`, which keeps whole rows, never stops the statement and finishes a cut set as `Truncation::ByteLimit`; MongoDB stops reading itself; table pages are exempt. | | [0021](0021-an-int32-keeps-its-width.md) | An int32 keeps its width, and an edited number keeps its type | Accepted | `Value::Int32` holds MongoDB's int32, equal to the `Int` of the same number; a save carries each edited cell's read value, and a number binds in the read's BSON type when it is exactly one, else the column's. | | [0022](0022-browsing-through-the-ffi.md) | A table page is read on the session with its filter bound, and structure, definitions, export and history cross the FFI | Accepted | `read_table_page` builds the page with the filter, binds its values and reads it with `read_page` on a pooled connection as run events; `table_structure`, `object_definition`, `export_rows`, `export_table` and `Core::history` give the Linux app's reads to an app on the FFI. | +| [0023](0023-mcp-client-setup-from-one-catalog.md) | Both apps set up MCP clients from one catalog | Accepted | `core/crates/mcp/clients.json`, bundled, lists each client per OS; install by deeplink, then the client's CLI by argv, then a comment-keeping splice into its config file with a `.tablepro-backup`, else copy; macOS writes the stdio bridge and no token, Linux the URL and token, and the Linux server serves only the user's own account; brand marks from Simple Icons or the brand, still their owners' trademarks. | diff --git a/linux/README.md b/linux/README.md index 7a6c45eca7..4e17741bbf 100644 --- a/linux/README.md +++ b/linux/README.md @@ -560,16 +560,25 @@ The assistant reads no rows: the structure comes from the catalog, and a stateme ## MCP server -MCP clients on this computer, such as Claude Code, can use your saved connections through TablePro ([ADR 0022](docs/decisions/0022-ai-assistant-and-mcp-server.md)). The server is off until you turn on **Preferences > MCP > Enable MCP Server**, and runs while TablePro is open. It listens on `127.0.0.1` only, on port 23508 unless you change it there. +MCP clients on this computer, such as Claude Code, can use your saved connections through TablePro ([ADR 0022](docs/decisions/0022-ai-assistant-and-mcp-server.md)). The server is off until you turn on **Preferences > MCP > Enable MCP Server**, and runs while TablePro is open. It listens on `127.0.0.1` only, on port 23508 unless you change it there, and answers only programs running as your user: another account on the computer is refused even with the access token. -Copy the address and the access token from the same page into the client. With Claude Code: +**Clients** on that page lists the clients TablePro knows, the ones set up or found on this computer first, each with its state, such as Not set up, Set up, or set up with an old access token: + +- **Install** and **Update** write TablePro's entry into the client's own configuration file and keep the rest of it, comments included. **Update** changes only what TablePro sets in its entry and keeps your other settings there. The file as it was is kept beside it as `.tablepro-backup`, and a file that holds the token is readable only by you. +- Claude Code is set up through its own `claude mcp add` command, which TablePro runs without a shell. The Flatpak cannot start it, so there you copy the command instead. +- Select a client for its configuration file, the setup to paste by hand with **Copy**, and **Remove**. The page shows the access token masked; **Copy** includes it. +- A toast says when a client connects. + +A client that only starts programs on this computer, such as Claude Desktop, cannot use the server, which is reached at an address. + +To set up a client by hand, copy the address and the authorization header from the same page. With Claude Code: ```bash -claude mcp add --transport http tablepro http://127.0.0.1:23508/mcp \ +claude mcp add --scope user --transport http tablepro http://127.0.0.1:23508/mcp \ --header "Authorization: Bearer " ``` -**Regenerate Access Token** on that page turns the old token away from the next request. +**Regenerate Access Token** on that page, with the server on or off, turns the old token away from the next request. While the server runs, the clients set up with the old token show **Update**. Each connection's **External Clients** level, under Options in its connect dialog, decides what a client may do there: @@ -583,7 +592,7 @@ Read Only stops statements that write. A function the connection's login may cal A client works on a connection open in a TablePro window; its `connect` tool opens one there, and anything the connect needs, such as a password, is asked in that window. A read runs on a read-only connection. A write runs one statement per call, never under Safe Mode Read-Only, and only after you click **Run** in Safe Mode's dialog in the connection's window, whatever the Safe Mode level. What a client runs with `execute_query` goes into the query history as the editor's runs do. -The tools are `list_connections`, `connect`, `list_schemas`, `list_tables`, `describe_table`, `get_table_ddl`, `browse_table`, `count_rows` and `execute_query`. An answer keeps at most 20 result sets of 1,000 rows each, and a statement stops at 300 seconds. +The 11 tools are `list_connections`, `connect`, `list_databases`, `list_schemas`, `list_tables`, `describe_table`, `get_table_ddl`, `browse_table`, `count_rows`, `execute_query` and `export_data`. An answer keeps at most 20 result sets of 1,000 rows each and about 4 MB, a value longer than 64 KB is cut, a statement stops at 300 seconds, and an export takes at most 20 tables. ## TablePro account diff --git a/linux/build-aux/about/THIRD-PARTY-NOTICE.md.hbs b/linux/build-aux/about/THIRD-PARTY-NOTICE.md.hbs index 3937641d9c..f501db5453 100644 --- a/linux/build-aux/about/THIRD-PARTY-NOTICE.md.hbs +++ b/linux/build-aux/about/THIRD-PARTY-NOTICE.md.hbs @@ -4,6 +4,8 @@ TablePro is licensed under the GNU Affero General Public License, version 3 or l `build-aux/update-third-party-licenses.sh` writes this file from `Cargo.lock`. Do not edit it by hand. +The MCP client marks under `data/resources/icons/scalable/actions` name each client and stay their owners' trademarks. Claude, Claude Code, Cline, Cursor, Google Gemini, JetBrains, LM Studio, OpenCode, Warp, Windsurf and Zed are Simple Icons 16.37.0 files, under CC0-1.0. GitHub Copilot is the Simple Icons copy of Primer Octicons' copilot-24, under MIT, Copyright (c) 2026 GitHub Inc. goose is `documentation/static/img/goose.svg` from github.com/aaif-goose/goose, under Apache-2.0, Copyright 2024 Block, Inc. OpenAI is `client/assets/openai-logomark.svg` from github.com/openai/openai-realtime-console, under MIT, Copyright (c) 2024 OpenAI. Kiro is the icon kiro.dev publishes, and Visual Studio Code the icon in its brand kit at code.visualstudio.com/brand. Each file is used as published. The MIT and Apache 2.0 texts are under License texts. + ## Overview {{#each overview}} diff --git a/linux/changelog.d/4211.added.md b/linux/changelog.d/4211.added.md new file mode 100644 index 0000000000..bed879386f --- /dev/null +++ b/linux/changelog.d/4211.added.md @@ -0,0 +1 @@ +Preferences > MCP lists AI clients, shows whether each one reaches TablePro, and sets it up or copies its setup. diff --git a/linux/changelog.d/4211.fixed.md b/linux/changelog.d/4211.fixed.md new file mode 100644 index 0000000000..fd74521579 --- /dev/null +++ b/linux/changelog.d/4211.fixed.md @@ -0,0 +1 @@ +The MCP page copied the access token without its Bearer scheme, and offered no Regenerate while the server was off. diff --git a/linux/changelog.d/4211.security.md b/linux/changelog.d/4211.security.md new file mode 100644 index 0000000000..4599f15c30 --- /dev/null +++ b/linux/changelog.d/4211.security.md @@ -0,0 +1 @@ +The MCP server answers only programs running as your user, so a leaked access token does not work from another account. diff --git a/linux/crates/app/src/services/mcp_clients.rs b/linux/crates/app/src/services/mcp_clients.rs new file mode 100644 index 0000000000..a89f27b227 --- /dev/null +++ b/linux/crates/app/src/services/mcp_clients.rs @@ -0,0 +1,1153 @@ +use std::collections::HashMap; +use std::ffi::OsString; +use std::io::Write as _; +use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _, PermissionsExt as _}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::LazyLock; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use tablepro_mcp::clients::{ + Applies, CliInstall, CliUpdate, ClientCatalog, ClientConfigStatus, ClientDefinition, ClientPlatform, + ConfigEditError, ConfigFormat, ConfigLocation, DetectRule, InstallMethod, JsonValue, PlatformSpec, ServerTarget, + StaleReason, TemplateError, TemplateRenderer, UnsupportedReason, command_line, evaluate_status, expand_path, + read_member, remove_member, snippet, upsert_member, +}; + +const PLATFORM: ClientPlatform = ClientPlatform::Linux; +const FLATPAK_INFO: &str = "/.flatpak-info"; +const BACKUP_SUFFIX: &str = ".tablepro-backup"; +// A client's CLI writes one entry and exits; one that waits on input +// never will. +const COMMAND_LIMIT: Duration = Duration::from_secs(30); + +static CATALOG: LazyLock> = LazyLock::new(|| match ClientCatalog::bundled() { + Ok(catalog) => Some(catalog), + Err(error) => { + tracing::error!(code = error.code(), %error, "the MCP client catalog does not parse"); + None + } +}); + +pub fn catalog() -> Option<&'static ClientCatalog> { + CATALOG.as_ref() +} + +pub fn linux_clients() -> impl Iterator { + catalog().into_iter().flat_map(|catalog| catalog.clients_on(PLATFORM)) +} + +pub fn location(client: &ClientDefinition) -> Option<&'static ConfigLocation> { + catalog().and_then(|catalog| catalog.location(client, PLATFORM)) +} + +fn spec(client: &ClientDefinition) -> Option<&PlatformSpec> { + client.spec(PLATFORM) +} + +fn server_name() -> &'static str { + catalog().map_or("tablepro", |catalog| catalog.server_name.as_str()) +} + +// Where other apps keep their files. Inside the Flatpak the XDG +// directories are the sandbox's, so the host's come from the platform +// crate, and no host program can be found or run. +#[derive(Debug, Clone)] +pub struct ClientHost { + pub home: PathBuf, + pub config: PathBuf, + pub sandboxed: bool, + search_path: Vec, + variables: HashMap, + command_env: Vec<(OsString, OsString)>, +} + +impl ClientHost { + pub fn current() -> Self { + let dirs = tablepro_linux_platform::foreign_app_dirs(); + let sandboxed = Path::new(FLATPAK_INFO).exists(); + let search_path = match sandboxed { + true => Vec::new(), + false => std::env::var_os("PATH") + .map(|path| std::env::split_paths(&path).collect()) + .unwrap_or_default(), + }; + Self { + home: dirs.home, + config: dirs.config, + sandboxed, + search_path, + // `vars()` panics on a variable that is not UTF-8; no catalog path names one. + variables: std::env::vars_os() + .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?))) + .collect(), + command_env: Vec::new(), + } + } + + pub fn expand(&self, path: &str) -> PathBuf { + let home = self.home.to_string_lossy(); + PathBuf::from(expand_path(path, &home, |name| match name { + "XDG_CONFIG_HOME" => Some(self.config.to_string_lossy().into_owned()), + "HOME" => Some(home.clone().into_owned()), + other => self.variables.get(other).cloned(), + })) + } + + fn find_binary(&self, name: &str, paths: &[String]) -> Option { + paths + .iter() + .map(|path| self.expand(path)) + .chain(self.search_path.iter().map(|dir| dir.join(name))) + .find(|path| is_executable(path)) + } + + fn detects(&self, rules: &[DetectRule]) -> bool { + rules.iter().any(|rule| match rule { + DetectRule::Binary { name, paths } => self.find_binary(name, paths).is_some(), + DetectRule::Path(path) => self.expand(path).exists(), + DetectRule::BundleId(_) => false, + }) + } + + // A CLI the catalog names, found where its detect rule looks or on + // PATH. Never inside the Flatpak, which cannot start host programs. + fn find_cli(&self, cli: &CliInstall, spec: &PlatformSpec) -> Option { + if self.sandboxed { + return None; + } + let paths = spec + .detect + .iter() + .find_map(|rule| match rule { + DetectRule::Binary { name, paths } if *name == cli.binary => Some(paths.as_slice()), + _ => None, + }) + .unwrap_or_default(); + self.find_binary(&cli.binary, paths) + } +} + +fn is_executable(path: &Path) -> bool { + std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0) +} + +#[derive(Debug, Clone)] +enum Installer { + File(&'static ConfigLocation), + Cli { cli: CliInstall, binary: PathBuf }, +} + +fn installer(host: &ClientHost, client: &'static ClientDefinition) -> Option { + let spec = spec(client)?; + let location = location(client); + spec.install.iter().find_map(|method| match method { + InstallMethod::File => location + .filter(|location| location.writable && location.format != ConfigFormat::Yaml) + .map(Installer::File), + InstallMethod::Cli(cli) => host.find_cli(cli, spec).map(|binary| Installer::Cli { + cli: cli.clone(), + binary, + }), + InstallMethod::Deeplink(_) => None, + }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClientAction { + Install, + Update, + Copy, + None, +} + +#[derive(Debug, Clone)] +pub struct ClientState { + pub client: &'static ClientDefinition, + pub detected: bool, + pub status: ClientConfigStatus, + pub config_path: Option, + pub action: ClientAction, + pub removable: bool, + // Remove goes through the client's own CLI, not a file TablePro edits. + pub removes_with_command: bool, +} + +impl ClientState { + pub fn unsupported(&self) -> Option { + spec(self.client).and_then(|spec| spec.unsupported) + } + + pub fn applies(&self) -> Option { + spec(self.client).and_then(|spec| spec.applies) + } + + // The order the page lists clients in: set up first, then found on + // this computer, then the rest, each in catalog order. + pub fn rank(&self) -> u8 { + match ( + self.status.is_configured() || self.status == ClientConfigStatus::OtherScope, + self.detected, + ) { + (true, _) => 0, + (false, true) => 1, + (false, false) => 2, + } + } +} + +// Shadowed and Disabled have nothing an install could fix: the entry +// TablePro writes is current, and the client keeps the rest. +fn action(status: ClientConfigStatus, installer: Option<&Installer>, has_entry: bool) -> ClientAction { + match (status, installer) { + (_, _) if !has_entry => ClientAction::None, + (_, _) if entry_is_current(status) => ClientAction::None, + (ClientConfigStatus::Unreadable, Some(Installer::File(_))) | (_, None) => ClientAction::Copy, + (ClientConfigStatus::Unknown, _) => ClientAction::Copy, + (ClientConfigStatus::Stale(_), Some(_)) => ClientAction::Update, + (_, Some(_)) => ClientAction::Install, + } +} + +fn entry_is_current(status: ClientConfigStatus) -> bool { + matches!( + status, + ClientConfigStatus::Current | ClientConfigStatus::Disabled | ClientConfigStatus::Stale(StaleReason::Shadowed) + ) +} + +// Reads every client's file. Blocking: run it off the GTK thread. +pub fn survey(host: &ClientHost, url: &str, authorization: Option<&str>) -> Vec { + let target = ServerTarget::Http { + url: url.to_owned(), + authorization: authorization.map(str::to_owned), + }; + linux_clients().map(|client| state(host, client, &target)).collect() +} + +fn state(host: &ClientHost, client: &'static ClientDefinition, target: &ServerTarget) -> ClientState { + let spec = spec(client); + let location = location(client); + let config_path = location.map(|location| host.expand(&location.path)); + let template = spec.and_then(|spec| spec.entry.as_ref()); + let status = match (template, spec.and_then(|spec| spec.unsupported)) { + (Some(template), None) => match config_path.as_deref().map_or(ConfigText::Missing, read_config) { + ConfigText::Unreadable => ClientConfigStatus::Unreadable, + ConfigText::Missing => evaluate_status(None, location, server_name(), template, target, |_| true), + ConfigText::Text(text) => evaluate_status(Some(&text), location, server_name(), template, target, |_| true), + }, + _ => ClientConfigStatus::Unknown, + }; + let installer = installer(host, client); + let removable = status.is_configured() + && match &installer { + Some(Installer::File(_)) => true, + Some(Installer::Cli { cli, .. }) => cli.remove.is_some(), + None => false, + }; + ClientState { + client, + detected: spec.is_some_and(|spec| host.detects(&spec.detect)), + status, + action: action(status, installer.as_ref(), template.is_some()), + removes_with_command: matches!(installer, Some(Installer::Cli { .. })), + removable, + config_path, + } +} + +enum ConfigText { + Missing, + Text(String), + Unreadable, +} + +fn read_config(path: &Path) -> ConfigText { + match std::fs::read(path) { + Ok(bytes) => String::from_utf8(bytes).map_or(ConfigText::Unreadable, ConfigText::Text), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => ConfigText::Missing, + Err(error) => { + tracing::debug!(%error, path = %path.display(), "a client's config could not be read"); + ConfigText::Unreadable + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ClientSetupError { + #[error("the client is not in the catalog")] + UnknownClient, + #[error("there is no way to set up this client from TablePro")] + NoInstaller, + #[error(transparent)] + Template(#[from] TemplateError), + #[error("{}: {}", .path.display(), .error.code())] + Edit { path: PathBuf, error: ConfigEditError }, + #[error("{}: {source}", .path.display())] + Io { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("{} is not text", .0.display())] + NotText(PathBuf), + #[error("{} changed while it was being written", .0.display())] + ChangedDuringWrite(PathBuf), + #[error("{} did not hold the change after it was written", .0.display())] + VerificationFailed(PathBuf), + #[error("the client's command exited with {0:?}")] + CommandFailed(Option), + #[error("the client's command did not finish")] + CommandTimedOut, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SetupOutcome { + Written { path: PathBuf, backup: Option }, + Unchanged, + Ran, +} + +fn client_by_id(id: &str) -> Result<&'static ClientDefinition, ClientSetupError> { + linux_clients() + .find(|client| client.id == id) + .ok_or(ClientSetupError::UnknownClient) +} + +fn rendered_entry(client: &ClientDefinition, target: &ServerTarget) -> Result { + let spec = spec(client).ok_or(ClientSetupError::UnknownClient)?; + Ok(TemplateRenderer::new(server_name(), target).entry(spec)?) +} + +// The setup to paste is the client's own command rather than a file. +pub fn setup_is_command(client: &ClientDefinition) -> bool { + spec(client).is_some_and(|spec| { + spec.install + .iter() + .any(|method| matches!(method, InstallMethod::Cli(_))) + }) +} + +// What a user pastes: the client's own command where TablePro would run +// it, otherwise the fragment for its config file. +pub fn setup_text(id: &str, url: &str, authorization: &str) -> Result { + let client = client_by_id(id)?; + let target = ServerTarget::Http { + url: url.to_owned(), + authorization: Some(authorization.to_owned()), + }; + let entry = rendered_entry(client, &target)?; + let cli = spec(client).and_then(|spec| { + spec.install.iter().find_map(|method| match method { + InstallMethod::Cli(cli) => Some(cli), + _ => None, + }) + }); + if let Some(cli) = cli { + let arguments = TemplateRenderer::new(server_name(), &target).arguments(&cli.add, &entry)?; + return Ok(command_line(&cli.binary, &arguments)); + } + let location = location(client); + snippet(location, server_name(), &entry).map_err(|error| ClientSetupError::Edit { + path: location + .map(|location| PathBuf::from(&location.path)) + .unwrap_or_default(), + error, + }) +} + +// The command Remove runs, for the confirmation to name. +pub fn remove_command(host: &ClientHost, id: &str) -> Option { + let client = client_by_id(id).ok()?; + let Some(Installer::Cli { cli, .. }) = installer(host, client) else { + return None; + }; + Some(command_line(&cli.binary, &arguments_for(cli.remove.as_deref()?))) +} + +fn arguments_for(template: &[String]) -> Vec { + template + .iter() + .map(|argument| argument.replace("{name}", server_name())) + .collect() +} + +// Install and Update. Blocking: run it off the GTK thread. +pub fn install(host: &ClientHost, id: &str, url: &str, authorization: &str) -> Result { + let client = client_by_id(id)?; + let target = ServerTarget::Http { + url: url.to_owned(), + authorization: Some(authorization.to_owned()), + }; + let entry = rendered_entry(client, &target)?; + match installer(host, client).ok_or(ClientSetupError::NoInstaller)? { + Installer::File(location) => { + let template = spec(client) + .and_then(|spec| spec.entry.as_ref()) + .ok_or(TemplateError::NoEntry)?; + let path = host.expand(&location.path); + let edit = |error| ClientSetupError::Edit { + path: path.clone(), + error, + }; + update_file( + &path, + |text| { + let text = text.unwrap_or_default(); + upsert_member( + location.format, + text, + &location.key_path, + server_name(), + &entry, + template, + ) + .map_err(&edit) + }, + |text| { + entry_is_current(evaluate_status( + Some(text), + Some(location), + server_name(), + template, + &target, + |_| true, + )) + }, + ) + } + Installer::Cli { cli, binary } => { + let renderer = TemplateRenderer::new(server_name(), &target); + let add = renderer.arguments(&cli.add, &entry)?; + let configured = state(host, client, &target).status.is_configured(); + if configured + && cli.update == CliUpdate::RemoveThenAdd + && let Some(remove) = &cli.remove + { + // Fails when there is nothing to remove, which is fine. + let _ = run(host, &binary, &arguments_for(remove)); + } + run(host, &binary, &add)?; + let path = location(client).map(|location| host.expand(&location.path)); + // The CLI writes the token into its file under the user's umask. + if let Some(path) = &path { + keep_private(path); + } + match entry_is_current(state(host, client, &target).status) { + true => Ok(SetupOutcome::Ran), + false => Err(ClientSetupError::VerificationFailed(path.unwrap_or_default())), + } + } + } +} + +// Blocking: run it off the GTK thread. +pub fn remove(host: &ClientHost, id: &str) -> Result { + let client = client_by_id(id)?; + match installer(host, client).ok_or(ClientSetupError::NoInstaller)? { + Installer::File(location) => { + let path = host.expand(&location.path); + let edit = |error| ClientSetupError::Edit { + path: path.clone(), + error, + }; + update_file( + &path, + |text| match text { + None => Ok(String::new()), + Some(text) => { + remove_member(location.format, text, &location.key_path, server_name()).map_err(&edit) + } + }, + |text| { + text.is_empty() + || read_member(location.format, text, &location.key_path, server_name()) + .is_ok_and(|found| found.is_none()) + }, + ) + } + Installer::Cli { cli, binary } => { + let template = cli.remove.as_deref().ok_or(ClientSetupError::NoInstaller)?; + run(host, &binary, &arguments_for(template))?; + Ok(SetupOutcome::Ran) + } + } +} + +fn keep_private(path: &Path) { + let Ok(metadata) = std::fs::metadata(path) else { + return; + }; + let mode = metadata.permissions().mode(); + if mode & 0o077 == 0 { + return; + } + if let Err(error) = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode & 0o700)) { + tracing::warn!(%error, path = %path.display(), "a client's file holding the token stays readable by others"); + } +} + +// Where Install and Remove keep the file as it was: beside the file a +// link points to, since the write goes through the link. +pub fn backup_path(config: &Path) -> PathBuf { + let target = std::fs::canonicalize(config).unwrap_or_else(|_| config.to_owned()); + sibling(&target, BACKUP_SUFFIX) +} + +// Argument by argument, never through a shell. +fn run(host: &ClientHost, binary: &Path, arguments: &[String]) -> Result<(), ClientSetupError> { + let mut child = Command::new(binary) + .args(arguments) + .envs(host.command_env.iter().cloned()) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map_err(|source| ClientSetupError::Io { + path: binary.to_owned(), + source, + })?; + let started = Instant::now(); + loop { + let finished = child.try_wait().map_err(|source| ClientSetupError::Io { + path: binary.to_owned(), + source, + })?; + match finished { + Some(status) if status.success() => return Ok(()), + Some(status) => { + tracing::warn!(?status, binary = %binary.display(), "a client's command failed"); + return Err(ClientSetupError::CommandFailed(status.code())); + } + None if started.elapsed() > COMMAND_LIMIT => { + let _ = child.kill(); + let _ = child.wait(); + return Err(ClientSetupError::CommandTimedOut); + } + None => std::thread::sleep(Duration::from_millis(50)), + } + } +} + +// Writes through a symlink to the file it names, never replacing the +// link. Re-reads before replacing and gives up if another program keeps +// changing the file; keeps the previous bytes beside it; checks the +// result before reporting success. +fn update_file( + path: &Path, + transform: impl Fn(Option<&str>) -> Result, + verify: impl Fn(&str) -> bool, +) -> Result { + let target = resolve(path)?; + let mut before = read_bytes(&target)?; + let mut attempts = 0; + let (original, updated) = loop { + let original = before.as_deref().map(|bytes| as_text(&target, bytes)).transpose()?; + let updated = transform(original.as_deref())?; + let now = read_bytes(&target)?; + if now == before { + break (original, updated); + } + attempts += 1; + if attempts > 1 { + return Err(ClientSetupError::ChangedDuringWrite(target)); + } + before = now; + }; + if original.as_deref() == Some(updated.as_str()) || (original.is_none() && updated.is_empty()) { + return Ok(SetupOutcome::Unchanged); + } + let io = |source| ClientSetupError::Io { + path: target.clone(), + source, + }; + let backup = match &before { + Some(bytes) => { + let backup = backup_path(&target); + replace(&backup, bytes, 0o600).map_err(io)?; + Some(backup) + } + None => None, + }; + // A token goes into the file, so nobody but the user may read it. + let mode = match std::fs::metadata(&target) { + Ok(metadata) => metadata.permissions().mode() & 0o700, + Err(_) => 0o600, + }; + if let Some(parent) = target.parent() { + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(parent) + .map_err(io)?; + } + replace(&target, updated.as_bytes(), mode).map_err(io)?; + let written = std::fs::read(&target).map_err(io)?; + if !verify(&as_text(&target, &written)?) { + return Err(ClientSetupError::VerificationFailed(target)); + } + Ok(SetupOutcome::Written { path: target, backup }) +} + +fn resolve(path: &Path) -> Result { + match std::fs::canonicalize(path) { + Ok(resolved) => Ok(resolved), + Err(error) if error.kind() == std::io::ErrorKind::NotFound && path.symlink_metadata().is_err() => { + Ok(path.to_owned()) + } + // A link to nothing: writing would create a file wherever it points. + Err(source) => Err(ClientSetupError::Io { + path: path.to_owned(), + source, + }), + } +} + +fn read_bytes(path: &Path) -> Result>, ClientSetupError> { + match std::fs::read(path) { + Ok(bytes) => Ok(Some(bytes)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(source) => Err(ClientSetupError::Io { + path: path.to_owned(), + source, + }), + } +} + +fn as_text(path: &Path, bytes: &[u8]) -> Result { + String::from_utf8(bytes.to_vec()).map_err(|_| ClientSetupError::NotText(path.to_owned())) +} + +fn sibling(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.file_name().map(OsString::from).unwrap_or_default(); + name.push(suffix); + path.with_file_name(name) +} + +// Written beside the file and renamed over it, so a reader sees the old +// bytes or the new ones, never half of either. +fn replace(path: &Path, bytes: &[u8], mode: u32) -> std::io::Result<()> { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let temporary = sibling( + path, + &format!( + ".tablepro-{}-{}.tmp", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + ), + ); + let written = write_new(&temporary, bytes, mode).and_then(|()| std::fs::rename(&temporary, path)); + if written.is_err() { + let _ = std::fs::remove_file(&temporary); + } + written +} + +fn write_new(path: &Path, bytes: &[u8], mode: u32) -> std::io::Result<()> { + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(mode) + .open(path)?; + file.write_all(bytes)?; + file.sync_all() +} + +#[cfg(test)] +mod tests { + use std::os::unix::fs::symlink; + + use super::*; + + const URL: &str = "http://127.0.0.1:23508/mcp"; + const HEADER: &str = "Bearer tp_test"; + + impl ClientHost { + pub(crate) fn under(home: &Path) -> Self { + Self { + home: home.to_owned(), + config: home.join(".config"), + sandboxed: false, + search_path: vec![home.join("bin")], + variables: HashMap::new(), + command_env: vec![("HOME".into(), home.as_os_str().to_owned())], + } + } + } + + fn find(states: &[ClientState], id: &str) -> ClientState { + states + .iter() + .find(|state| state.client.id == id) + .cloned() + .expect("a client") + } + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().expect("a parent")).expect("a folder"); + std::fs::write(path, text).expect("a file"); + } + + fn mode(path: &Path) -> u32 { + std::fs::metadata(path).expect("metadata").permissions().mode() & 0o777 + } + + #[test] + fn every_linux_client_is_surveyed_and_a_missing_file_is_not_set_up() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + + let states = survey(&host, URL, Some(HEADER)); + + assert_eq!(states.len(), linux_clients().count()); + let cursor = find(&states, "cursor"); + assert_eq!(cursor.status, ClientConfigStatus::NotConfigured); + assert_eq!(cursor.action, ClientAction::Install); + assert_eq!(cursor.config_path, Some(home.path().join(".cursor/mcp.json"))); + let desktop = find(&states, "claude-desktop"); + assert_eq!(desktop.unsupported(), Some(UnsupportedReason::StdioOnly)); + assert_eq!(desktop.action, ClientAction::None); + assert_eq!(find(&states, "goose").action, ClientAction::Copy); + assert_eq!(find(&states, "opencode").action, ClientAction::Copy); + } + + #[test] + fn a_client_is_found_by_its_binary_or_its_folder() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + write(&home.path().join("bin/zed"), "#!/bin/sh\n"); + std::fs::set_permissions(home.path().join("bin/zed"), std::fs::Permissions::from_mode(0o755)).expect("chmod"); + std::fs::create_dir_all(home.path().join(".lmstudio")).expect("a folder"); + write(&home.path().join("bin/cursor"), "not executable"); + + let states = survey(&host, URL, None); + + assert!(find(&states, "zed").detected); + assert!(find(&states, "lmstudio").detected); + assert!(!find(&states, "cursor").detected); + assert_eq!(find(&states, "zed").rank(), 1); + } + + #[test] + fn install_creates_a_private_file_that_reads_as_set_up() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + + let outcome = install(&host, "cursor", URL, HEADER).expect("installed"); + + let path = home.path().join(".cursor/mcp.json"); + assert_eq!( + outcome, + SetupOutcome::Written { + path: path.clone(), + backup: None + } + ); + assert_eq!(mode(&path), 0o600); + assert_eq!(mode(home.path().join(".cursor").as_path()), 0o700); + let states = survey(&host, URL, Some(HEADER)); + assert_eq!(find(&states, "cursor").status, ClientConfigStatus::Current); + assert_eq!(find(&states, "cursor").action, ClientAction::None); + assert!(find(&states, "cursor").removable); + assert_eq!( + install(&host, "cursor", URL, HEADER).expect("again"), + SetupOutcome::Unchanged + ); + } + + #[test] + fn install_keeps_other_servers_and_a_backup_of_the_old_file() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let path = home.path().join(".config/zed/settings.json"); + let original = "// mine\n{\n \"theme\": \"x\",\n \"context_servers\": {\n \"other\": {}\n }\n}\n"; + write(&path, original); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).expect("chmod"); + + let outcome = install(&host, "zed", URL, HEADER).expect("installed"); + + let written = std::fs::canonicalize(&path).expect("the file"); + let backup = sibling(&written, BACKUP_SUFFIX); + assert_eq!( + outcome, + SetupOutcome::Written { + path: written, + backup: Some(backup.clone()) + } + ); + assert_eq!(std::fs::read_to_string(&backup).expect("the backup"), original); + let edited = std::fs::read_to_string(&path).expect("the file"); + assert!(edited.starts_with("// mine\n{\n \"theme\": \"x\",\n \"context_servers\": {\n \"other\": {},\n")); + assert_eq!(mode(&path), 0o600, "the token is readable by others"); + } + + #[test] + fn a_symlinked_config_is_written_through_and_stays_a_link() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let real = home.path().join("dotfiles/mcp.json"); + write(&real, "{}"); + std::fs::create_dir_all(home.path().join(".cursor")).expect("a folder"); + let link = home.path().join(".cursor/mcp.json"); + symlink(&real, &link).expect("a link"); + + install(&host, "cursor", URL, HEADER).expect("installed"); + + assert!(link.symlink_metadata().expect("the link").file_type().is_symlink()); + assert!(std::fs::read_to_string(&real).expect("the target").contains("tablepro")); + assert!(home.path().join("dotfiles/mcp.json.tablepro-backup").exists()); + } + + #[test] + fn the_backup_named_for_a_linked_config_is_the_one_written() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let real = home.path().join("dotfiles/mcp.json"); + write(&real, "{}"); + std::fs::create_dir_all(home.path().join(".cursor")).expect("a folder"); + let link = home.path().join(".cursor/mcp.json"); + symlink(&real, &link).expect("a link"); + + let outcome = install(&host, "cursor", URL, HEADER).expect("installed"); + + let SetupOutcome::Written { + backup: Some(written), .. + } = outcome + else { + panic!("a backup of {outcome:?}"); + }; + assert_eq!(backup_path(&link), written); + assert_eq!( + written, + std::fs::canonicalize(home.path().join("dotfiles")) + .expect("the folder") + .join("mcp.json.tablepro-backup") + ); + } + + #[test] + fn an_update_keeps_the_users_own_settings_in_the_entry() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let path = home.path().join(".cursor/mcp.json"); + write( + &path, + "{\n \"mcpServers\": {\n \"tablepro\": {\n \"url\": \"http://127.0.0.1:1/mcp\",\n \ +\"timeout\": 30,\n \"headers\": {\n \"Authorization\": \"Bearer tp_old\",\n \ +\"X-Team\": \"data\"\n }\n }\n }\n}\n", + ); + assert_eq!( + find(&survey(&host, URL, Some(HEADER)), "cursor").action, + ClientAction::Update + ); + + install(&host, "cursor", URL, HEADER).expect("updated"); + + let edited = std::fs::read_to_string(&path).expect("the file"); + assert!(edited.contains("\"timeout\": 30"), "{edited}"); + assert!(edited.contains("\"X-Team\": \"data\""), "{edited}"); + assert!(edited.contains("\"Authorization\": \"Bearer tp_test\""), "{edited}"); + assert_eq!( + find(&survey(&host, URL, Some(HEADER)), "cursor").status, + ClientConfigStatus::Current + ); + } + + #[test] + fn an_entry_turned_off_in_the_client_offers_no_install() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + install(&host, "kiro", URL, HEADER).expect("installed"); + let path = home.path().join(".kiro/settings/mcp.json"); + let text = std::fs::read_to_string(&path).expect("the file"); + write(&path, &text.replace("\"disabled\": false", "\"disabled\": true")); + + let kiro = find(&survey(&host, URL, Some(HEADER)), "kiro"); + + assert_eq!(kiro.status, ClientConfigStatus::Disabled); + assert_eq!(kiro.action, ClientAction::None); + assert!(kiro.removable); + assert_eq!(kiro.rank(), 0); + } + + #[test] + fn an_entry_turned_off_with_an_old_token_offers_no_update() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + install(&host, "cline", URL, "Bearer tp_old").expect("installed"); + let path = home.path().join(".cline/data/settings/cline_mcp_settings.json"); + let text = std::fs::read_to_string(&path).expect("the file"); + write(&path, &text.replace("\"disabled\": false", "\"disabled\": true")); + + let cline = find(&survey(&host, URL, Some(HEADER)), "cline"); + + assert_eq!(cline.status, ClientConfigStatus::Disabled); + assert_eq!(cline.action, ClientAction::None); + } + + #[test] + fn an_update_keeps_the_tools_the_user_allowed() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let path = home.path().join(".copilot/mcp-config.json"); + write( + &path, + r#"{"mcpServers": {"tablepro": {"type": "http", "url": "http://127.0.0.1:1/mcp", +"headers": {"Authorization": "Bearer tp_old"}, "tools": ["list_connections"]}}}"#, + ); + assert_eq!( + find(&survey(&host, URL, Some(HEADER)), "copilot-cli").action, + ClientAction::Update + ); + + install(&host, "copilot-cli", URL, HEADER).expect("updated"); + + let written = read_member( + ConfigFormat::Json, + &std::fs::read_to_string(&path).expect("the file"), + &["mcpServers".to_owned()], + "tablepro", + ) + .expect("readable") + .expect("the entry"); + assert_eq!( + written.get("tools"), + Some(&JsonValue::Array(vec![JsonValue::String( + "list_connections".to_owned() + )])) + ); + assert_eq!(written.get("url"), Some(&JsonValue::String(URL.to_owned()))); + assert_eq!( + find(&survey(&host, URL, Some(HEADER)), "copilot-cli").status, + ClientConfigStatus::Current + ); + } + + #[test] + fn an_update_replaces_a_stdio_entry_whole() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let path = home.path().join(".cursor/mcp.json"); + write( + &path, + "{\n \"mcpServers\": {\n \"tablepro\": {\n \"command\": \"/opt/TablePro/tablepro-mcp\",\n \ +\"args\": [\"--verbose\"]\n }\n }\n}\n", + ); + let before = find(&survey(&host, URL, Some(HEADER)), "cursor"); + assert_eq!(before.status, ClientConfigStatus::Stale(StaleReason::OtherCommand)); + assert_eq!(before.action, ClientAction::Update); + + install(&host, "cursor", URL, HEADER).expect("updated"); + + let edited = std::fs::read_to_string(&path).expect("the file"); + assert!(!edited.contains("command") && !edited.contains("args"), "{edited}"); + assert_eq!( + find(&survey(&host, URL, Some(HEADER)), "cursor").status, + ClientConfigStatus::Current + ); + } + + #[test] + fn the_host_reads_an_environment_that_is_not_utf8() { + use std::os::unix::ffi::OsStrExt as _; + + const MARKER: &str = "TABLEPRO_TEST_NOT_UTF8"; + if std::env::var_os(MARKER).is_some() { + let host = ClientHost::current(); + assert_eq!( + host.expand("${CODEX_HOME:-~/.codex}/config.toml"), + PathBuf::from("/srv/codex/config.toml") + ); + return; + } + let name = format!( + "{}::the_host_reads_an_environment_that_is_not_utf8", + module_path!().split_once("::").map_or(module_path!(), |(_, rest)| rest) + ); + let child = Command::new(std::env::current_exe().expect("the test binary")) + .args([name.as_str(), "--exact", "--test-threads=1"]) + .env(MARKER, std::ffi::OsStr::from_bytes(b"caf\xe9")) + .env("CODEX_HOME", "/srv/codex") + .output() + .expect("the test binary runs"); + + let stdout = String::from_utf8_lossy(&child.stdout); + assert!( + child.status.success(), + "{stdout}{}", + String::from_utf8_lossy(&child.stderr) + ); + assert!(stdout.contains("1 passed"), "{stdout}"); + } + + #[test] + fn a_project_with_an_old_claude_code_setup_shadows_the_current_one() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let entry = |token: &str| { + format!(r#"{{"type": "http", "url": "{URL}", "headers": {{"Authorization": "Bearer {token}"}}}}"#) + }; + write( + &home.path().join(".claude.json"), + &format!( + r#"{{"mcpServers": {{"tablepro": {}}}, "projects": {{"/home/ana/app": {{"mcpServers": {{"tablepro": {}}}}}}}}}"#, + entry("tp_test"), + entry("tp_old") + ), + ); + + let claude = find(&survey(&host, URL, Some(HEADER)), "claude-code"); + + assert_eq!(claude.status, ClientConfigStatus::Stale(StaleReason::Shadowed)); + assert_eq!( + claude.action, + ClientAction::None, + "Update would not reach the project's entry" + ); + } + + #[test] + fn a_new_token_or_port_asks_for_an_update() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + install(&host, "codex", URL, HEADER).expect("installed"); + + let token = find(&survey(&host, URL, Some("Bearer tp_new")), "codex"); + let port = find(&survey(&host, "http://127.0.0.1:40000/mcp", None), "codex"); + + assert_eq!(token.action, ClientAction::Update); + assert_eq!(port.action, ClientAction::Update); + assert_eq!( + find(&survey(&host, URL, None), "codex").status, + ClientConfigStatus::Current + ); + } + + #[test] + fn remove_takes_only_the_tablepro_entry() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let path = home.path().join(".gemini/settings.json"); + write(&path, "{\n \"mcpServers\": {\n \"other\": {}\n }\n}\n"); + install(&host, "gemini", URL, HEADER).expect("installed"); + + remove(&host, "gemini").expect("removed"); + + assert_eq!( + std::fs::read_to_string(&path).expect("the file"), + "{\n \"mcpServers\": {\n \"other\": {}\n }\n}\n" + ); + assert_eq!( + find(&survey(&host, URL, None), "gemini").status, + ClientConfigStatus::NotConfigured + ); + } + + #[test] + fn a_file_that_is_not_json_is_left_alone() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + let path = home.path().join(".cursor/mcp.json"); + write(&path, "{ not json"); + + let refused = install(&host, "cursor", URL, HEADER); + + assert!(matches!(refused, Err(ClientSetupError::Edit { .. })), "{refused:?}"); + assert_eq!(std::fs::read_to_string(&path).expect("the file"), "{ not json"); + assert_eq!(find(&survey(&host, URL, None), "cursor").action, ClientAction::Copy); + } + + fn fake_claude(home: &Path) { + let script = "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$HOME/argv.log\"\n\ +if [ \"$2\" = add ]; then\n header=\"${10#Authorization: }\"\n \ +printf '{\"mcpServers\": {\"tablepro\": {\"type\": \"http\", \"url\": \"%s\", \"headers\": {\"Authorization\": \"%s\"}}}}' \ +\"$8\" \"$header\" > \"$HOME/.claude.json\"\n chmod 644 \"$HOME/.claude.json\"\nfi\n"; + let path = home.join(".local/bin/claude"); + write(&path, script); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod"); + } + + #[test] + fn claude_code_is_set_up_through_its_cli_one_argument_at_a_time() { + let home = tempfile::tempdir().expect("tempdir"); + let host = ClientHost::under(home.path()); + fake_claude(home.path()); + + assert_eq!( + install(&host, "claude-code", URL, HEADER).expect("installed"), + SetupOutcome::Ran + ); + + let argv = std::fs::read_to_string(home.path().join("argv.log")).expect("the arguments"); + assert_eq!( + argv, + "mcp\nadd\n--scope\nuser\n--transport\nhttp\ntablepro\nhttp://127.0.0.1:23508/mcp\n--header\n\ +Authorization: Bearer tp_test\n" + ); + assert_eq!( + mode(&home.path().join(".claude.json")), + 0o600, + "the token in the CLI's file is readable by others" + ); + let states = survey(&host, URL, Some(HEADER)); + assert_eq!(find(&states, "claude-code").status, ClientConfigStatus::Current); + assert!(find(&states, "claude-code").removes_with_command); + assert_eq!( + remove_command(&host, "claude-code").as_deref(), + Some("claude mcp remove --scope user tablepro") + ); + } + + #[test] + fn the_flatpak_never_runs_a_client_command() { + let home = tempfile::tempdir().expect("tempdir"); + let mut host = ClientHost::under(home.path()); + host.sandboxed = true; + fake_claude(home.path()); + + let state = find(&survey(&host, URL, None), "claude-code"); + + assert_eq!(state.action, ClientAction::Copy); + assert!(matches!( + install(&host, "claude-code", URL, HEADER), + Err(ClientSetupError::NoInstaller) + )); + assert!(!home.path().join("argv.log").exists()); + } + + #[test] + fn the_setup_to_copy_is_the_command_or_the_whole_fragment() { + let claude = setup_text("claude-code", URL, HEADER).expect("a command"); + let cursor = setup_text("cursor", URL, HEADER).expect("a fragment"); + + assert_eq!( + claude, + "claude mcp add --scope user --transport http tablepro http://127.0.0.1:23508/mcp --header \ +'Authorization: Bearer tp_test'" + ); + assert!(cursor.contains("\"mcpServers\"") && cursor.contains("\"Authorization\": \"Bearer tp_test\"")); + assert!(matches!( + setup_text("claude-desktop", URL, HEADER), + Err(ClientSetupError::Template(_)) + )); + } + + #[test] + fn host_paths_follow_xdg_and_client_variables() { + let home = tempfile::tempdir().expect("tempdir"); + let mut host = ClientHost::under(home.path()); + host.variables.insert("CODEX_HOME".to_owned(), "/srv/codex".to_owned()); + host.variables + .insert("XDG_CONFIG_HOME".to_owned(), "/sandbox/config".to_owned()); + + assert_eq!( + host.expand("${CODEX_HOME:-~/.codex}/config.toml"), + PathBuf::from("/srv/codex/config.toml") + ); + assert_eq!( + host.expand("${XDG_CONFIG_HOME:-~/.config}/zed/settings.json"), + home.path().join(".config/zed/settings.json") + ); + } +} diff --git a/linux/crates/app/src/services/mcp_service.rs b/linux/crates/app/src/services/mcp_service.rs index 417c834d31..d97ec86d97 100644 --- a/linux/crates/app/src/services/mcp_service.rs +++ b/linux/crates/app/src/services/mcp_service.rs @@ -8,7 +8,7 @@ use gtk4::prelude::ObjectExt; use secrecy::{ExposeSecret, SecretString}; use tablepro_linux_platform::AppSettings; use tablepro_linux_platform::settings::keys; -use tablepro_mcp::{AccessToken, McpServer, TokenVault, ToolContext}; +use tablepro_mcp::{AccessToken, McpServer, SeenClient, TokenVault, ToolContext}; use tablepro_session::runtime::Tasks; use tokio::sync::{Mutex, watch}; @@ -27,6 +27,9 @@ struct Inner { tokens: Arc, context: ToolContext, status: watch::Sender, + // The clients the running server has seen; empty while it is off. + seen: watch::Sender>, + forwarding: RefCell>>, // Every start, stop and token change takes this lock in turn, so a // stop has freed the port before the next start binds it. slot: Arc>>, @@ -39,7 +42,7 @@ struct Live { server: McpServer, } -type Started = Option>; +type Started = Option>), McpFailure>>; impl McpService { pub fn start(settings: Rc, tasks: Tasks, tokens: Arc, context: ToolContext) -> Self { @@ -50,6 +53,8 @@ impl McpService { tokens, context, status: watch::channel(McpStatus::Off).0, + seen: watch::channel(Vec::new()).0, + forwarding: RefCell::new(None), slot: Arc::new(Mutex::new(None)), generation: Arc::new(AtomicU64::new(0)), token: RefCell::new(None), @@ -74,6 +79,31 @@ impl McpService { self.inner.status.subscribe() } + pub fn seen_clients(&self) -> watch::Receiver> { + self.inner.seen.subscribe() + } + + pub(crate) fn tasks(&self) -> Tasks { + self.inner.tasks.clone() + } + + // The token whether or not the server runs. While it is off this reads + // the keyring, and makes and stores a token if it holds none. + pub async fn access_token(&self) -> Result { + if let Some(token) = self.token() { + return Ok(token); + } + let (slot, tokens) = (self.inner.slot.clone(), self.inner.tokens.clone()); + let reading = self.inner.tasks.spawn_task(async move { + let _serialized = slot.lock().await; + let token = tablepro_mcp::obtain_token(&*tokens).await?; + Ok::<_, McpFailure>(SecretString::from(token.secret().expose_secret().to_owned())) + }); + reading + .await + .map_err(|failure| McpFailure::Interrupted(failure.to_string()))? + } + /// The token clients present, while the server runs. pub fn token(&self) -> Option { self.inner @@ -120,6 +150,7 @@ impl McpService { self.inner.generation.fetch_add(1, Ordering::SeqCst); self.inner.token.replace(None); self.inner.status.send_replace(McpStatus::Off); + forget_clients(&self.inner); let slot = self.inner.slot.clone(); drop(self.inner.tasks.spawn_task(async move { if let Some(live) = slot.lock().await.take() { @@ -134,6 +165,7 @@ impl McpService { let enabled = inner.settings.mcp_server_enabled(); let port = inner.settings.mcp_server_port(); inner.token.replace(None); + forget_clients(inner); inner.status.send_replace(match enabled { true => McpStatus::Starting, false => McpStatus::Off, @@ -181,11 +213,36 @@ async fn restart( .await; Some(started.map(|(server, token)| { let bound = server.address().port(); + let sightings = server.seen_clients(); *live = Some(Live { server }); - (bound, token) + (bound, token, sightings) })) } +fn forget_clients(inner: &Inner) { + if let Some(forwarding) = inner.forwarding.take() { + forwarding.abort(); + } + inner.seen.send_replace(Vec::new()); +} + +// Ends with the server, whose sender then drops. +fn forward_clients(inner: &Rc, mut sightings: watch::Receiver>) { + let weak = Rc::downgrade(inner); + let forwarding = glib::spawn_future_local(async move { + while sightings.changed().await.is_ok() { + let clients = sightings.borrow_and_update().clone(); + let Some(inner) = weak.upgrade() else { + return; + }; + inner.seen.send_replace(clients); + } + }); + if let Some(previous) = inner.forwarding.replace(Some(forwarding)) { + previous.abort(); + } +} + fn deliver( inner: &Weak, generation: u64, @@ -200,8 +257,9 @@ fn deliver( } match outcome { Ok(None) => {} - Ok(Some(Ok((port, token)))) => { + Ok(Some(Ok((port, token, sightings)))) => { inner.token.replace(Some(token)); + forward_clients(&inner, sightings); inner.status.send_replace(McpStatus::Running { port }); } Ok(Some(Err(failure))) => { @@ -419,7 +477,7 @@ pub(crate) mod tests { let newer = crate::test_support::finish_on_main(WAIT, start(3, newer_port)).expect("the newer start"); let stale = crate::test_support::finish_on_main(WAIT, start(2, stale_port)).expect("the stale start"); - assert!(matches!(newer, Ok(Some(Ok((port, _)))) if port == newer_port)); + assert!(matches!(newer, Ok(Some(Ok((port, _, _)))) if port == newer_port)); assert!(matches!(stale, Ok(None))); assert!( std::net::TcpListener::bind(("127.0.0.1", newer_port)).is_err(), @@ -429,6 +487,76 @@ pub(crate) mod tests { runtime.shutdown(); } + // An initialize as a client sends it, on a connection of its own. + fn initialize(port: u16, token: &str, name: &str) { + use std::io::{Read as _, Write as _}; + + let body = format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18","capabilities":{{}},"clientInfo":{{"name":"{name}","version":"1"}}}}}}"# + ); + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).expect("a connection"); + write!( + stream, + "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\nAuthorization: Bearer {token}\r\n\ +Content-Type: application/json\r\nAccept: application/json, text/event-stream\r\nMCP-Protocol-Version: 2025-06-18\r\n\ +Content-Length: {}\r\n\r\n{body}", + body.len() + ) + .expect("the request"); + let mut reply = String::new(); + stream.read_to_string(&mut reply).expect("the reply"); + assert!(reply.starts_with("HTTP/1.1 200"), "{reply}"); + } + + #[gtk4::test] + fn a_client_that_initializes_is_seen_until_the_server_stops() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let root = tempfile::tempdir().expect("tempdir"); + let port = free_port(); + settings.get().set_mcp_server_port(port).expect("the port"); + settings.get().set_mcp_server_enabled(true).expect("the switch"); + let service = McpService::start( + settings.get().clone(), + runtime.tasks(), + Arc::new(MemoryTokens::default()), + context(root.path()), + ); + wait_until(WAIT, || status(&service) == McpStatus::Running { port }).expect("the server to run"); + let token = service.token().expect("the token"); + + initialize(port, token.expose_secret(), "claude-code"); + + let seen = service.seen_clients(); + wait_until(WAIT, || !seen.borrow().is_empty()).expect("the client seen"); + assert_eq!(seen.borrow()[0].name, "claude-code"); + settings.get().set_mcp_server_enabled(false).expect("the switch"); + assert!(seen.borrow().is_empty(), "a stopped server still lists its clients"); + runtime.shutdown(); + } + + #[gtk4::test] + fn the_token_is_read_from_the_keyring_while_the_server_is_off() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let root = tempfile::tempdir().expect("tempdir"); + let tokens = Arc::new(MemoryTokens(StdMutex::new(Some("tp_stored".to_owned())))); + let service = McpService::start(settings.get().clone(), runtime.tasks(), tokens, context(root.path())); + assert_eq!(status(&service), McpStatus::Off); + + let read = Rc::new(RefCell::new(None)); + let (sink, reading) = (read.clone(), service.clone()); + glib::spawn_future_local(async move { + let token = reading.access_token().await; + sink.replace(Some(token.map(|token| token.expose_secret().to_owned()))); + }); + wait_until(WAIT, || read.borrow().is_some()).expect("the token"); + + assert!(matches!(read.borrow().as_ref(), Some(Ok(token)) if token == "tp_stored")); + assert!(service.token().is_none(), "reading the token started nothing"); + runtime.shutdown(); + } + #[gtk4::test] fn a_regenerated_token_replaces_the_one_shown_and_stored() { let settings = MemorySettings::new(); diff --git a/linux/crates/app/src/services/mod.rs b/linux/crates/app/src/services/mod.rs index 43992b67cf..ea2d997613 100644 --- a/linux/crates/app/src/services/mod.rs +++ b/linux/crates/app/src/services/mod.rs @@ -23,6 +23,7 @@ pub mod history_service; pub mod import_file; pub(crate) mod library_outline; pub(crate) mod license_ask; +pub mod mcp_clients; pub mod mcp_service; pub mod mcp_status; pub mod pending_structure; diff --git a/linux/crates/app/src/ui/icons.rs b/linux/crates/app/src/ui/icons.rs index c4fa788d9a..88aa93761c 100644 --- a/linux/crates/app/src/ui/icons.rs +++ b/linux/crates/app/src/ui/icons.rs @@ -8,6 +8,24 @@ pub const APPLICATIONS_SCIENCE: &str = "applications-science-symbolic"; /// Bundled: a speech bubble, for the AI assistant. pub const ASSISTANT: &str = "assistant-symbolic"; pub const CHANGES_ALLOW: &str = "changes-allow-symbolic"; +// MCP client marks, bundled. Simple Icons draws them in one colour, so +// they follow the theme; a brand kit's own colours keep the plain name. +pub const CLIENT_CLAUDE: &str = "claude-symbolic"; +pub const CLIENT_CLAUDE_CODE: &str = "claudecode-symbolic"; +pub const CLIENT_CLINE: &str = "cline-symbolic"; +pub const CLIENT_CURSOR: &str = "cursor-symbolic"; +pub const CLIENT_GITHUB_COPILOT: &str = "githubcopilot-symbolic"; +pub const CLIENT_GOOGLE_GEMINI: &str = "googlegemini-symbolic"; +pub const CLIENT_GOOSE: &str = "goose"; +pub const CLIENT_JETBRAINS: &str = "jetbrains-symbolic"; +pub const CLIENT_KIRO: &str = "kiro"; +pub const CLIENT_LM_STUDIO: &str = "lmstudio-symbolic"; +pub const CLIENT_OPENAI: &str = "openai-symbolic"; +pub const CLIENT_OPENCODE: &str = "opencode-symbolic"; +pub const CLIENT_VSCODE: &str = "vscode"; +pub const CLIENT_WARP: &str = "warp-symbolic"; +pub const CLIENT_WINDSURF: &str = "windsurf-symbolic"; +pub const CLIENT_ZED: &str = "zed-symbolic"; pub const CHANGES_PREVENT: &str = "changes-prevent-symbolic"; pub const COMPUTER: &str = "computer-symbolic"; pub const DIALOG_ERROR: &str = "dialog-error-symbolic"; @@ -93,6 +111,22 @@ pub const ALL: &[&str] = &[ ASSISTANT, CHANGES_ALLOW, CHANGES_PREVENT, + CLIENT_CLAUDE, + CLIENT_CLAUDE_CODE, + CLIENT_CLINE, + CLIENT_CURSOR, + CLIENT_GITHUB_COPILOT, + CLIENT_GOOGLE_GEMINI, + CLIENT_GOOSE, + CLIENT_JETBRAINS, + CLIENT_KIRO, + CLIENT_LM_STUDIO, + CLIENT_OPENAI, + CLIENT_OPENCODE, + CLIENT_VSCODE, + CLIENT_WARP, + CLIENT_WINDSURF, + CLIENT_ZED, COMPUTER, DIALOG_ERROR, DIALOG_WARNING, @@ -181,10 +215,46 @@ pub fn connection_icon(icon: tablepro_storage::ConnectionIcon) -> &'static str { } } +// The icon for a catalog client's `icon` slug. A slug with no bundled +// mark falls back to a generic one rather than a missing image. +pub fn client_icon(slug: &str) -> &'static str { + match slug { + "claude" => CLIENT_CLAUDE, + "claudecode" => CLIENT_CLAUDE_CODE, + "cline" => CLIENT_CLINE, + "cursor" => CLIENT_CURSOR, + "githubcopilot" => CLIENT_GITHUB_COPILOT, + "googlegemini" => CLIENT_GOOGLE_GEMINI, + "goose" => CLIENT_GOOSE, + "jetbrains" => CLIENT_JETBRAINS, + "kiro" => CLIENT_KIRO, + "lmstudio" => CLIENT_LM_STUDIO, + "openai" => CLIENT_OPENAI, + "opencode" => CLIENT_OPENCODE, + "vscode" => CLIENT_VSCODE, + "warp" => CLIENT_WARP, + "windsurf" => CLIENT_WINDSURF, + "zed" => CLIENT_ZED, + _ => APPLICATIONS_ENGINEERING, + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn every_linux_client_has_its_own_bundled_mark() { + for client in crate::services::mcp_clients::linux_clients() { + let icon = client_icon(&client.icon); + assert_ne!(icon, APPLICATIONS_ENGINEERING, "{} has no mark", client.id); + assert!( + ALL.contains(&icon), + "{icon} is not in ALL, so nothing checks it resolves" + ); + } + } + /// A name the icon theme cannot resolve renders as a blank square at /// runtime with no warning, so the whole set is checked here. #[gtk4::test] diff --git a/linux/crates/app/src/ui/preferences_dialog/mcp_page.rs b/linux/crates/app/src/ui/preferences_dialog/mcp_page.rs index ea77fd3664..3a24c6ff81 100644 --- a/linux/crates/app/src/ui/preferences_dialog/mcp_page.rs +++ b/linux/crates/app/src/ui/preferences_dialog/mcp_page.rs @@ -1,5 +1,8 @@ -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; use std::sync::OnceLock; +use std::time::SystemTime; use gio::prelude::SettingsExtManual; use glib::subclass::Signal; @@ -12,14 +15,24 @@ use secrecy::ExposeSecret; use tablepro_core::credentials::SecretError; use tablepro_linux_platform::AppSettings; use tablepro_linux_platform::settings::keys; +use tablepro_mcp::SeenClient; +use tablepro_mcp::clients::{ + Applies, ClientConfigStatus, ClientDefinition, ClientPlatform, ConfigEditError, StaleReason, UnsupportedReason, +}; use tokio::sync::watch; +use crate::i18n::{gettext, gettext_f}; +use crate::services::mcp_clients::{self, ClientAction, ClientHost, ClientSetupError, ClientState, SetupOutcome}; use crate::services::mcp_service::McpService; use crate::services::mcp_status::{McpFailure, McpStatus}; use crate::services::secret_save_report::SecretSaveReport; const CANCEL: &str = "cancel"; const REGENERATE: &str = "regenerate"; +const REMOVE: &str = "remove"; +// What the page shows in place of the token. Copy puts the real one on +// the clipboard. +const MASKED_AUTHORIZATION: &str = "Bearer tp_••••••••••••••••"; mod imp { use libadwaita::subclass::prelude::*; @@ -49,9 +62,20 @@ mod imp { pub copy_token_button: TemplateChild, #[template_child] pub regenerate_row: TemplateChild, + #[template_child] + pub clients_group: TemplateChild, pub service: RefCell>, pub status: RefCell>, pub following: RefCell>>, + pub following_clients: RefCell>>, + pub surveying: RefCell>>, + pub survey_generation: Cell, + pub host: RefCell>, + pub states: RefCell>, + pub client_rows: RefCell>, + pub rows_placed: Cell, + pub subpage: RefCell>, + pub sightings: RefCell>, pub(super) unsaved_token: crate::ui::UnsavedSecretToasts, } @@ -72,8 +96,10 @@ mod imp { impl ObjectImpl for McpPage { fn dispose(&self) { - if let Some(following) = self.following.take() { - following.abort(); + for handle in [&self.following, &self.following_clients, &self.surveying] { + if let Some(running) = handle.take() { + running.abort(); + } } } @@ -94,8 +120,6 @@ mod imp { } glib::wrapper! { - /// The MCP page: the server's switch, status and port, and what a - /// client needs to reach it. pub struct McpPage(ObjectSubclass) @extends adw::PreferencesPage, gtk4::Widget, @implements gtk4::Accessible, gtk4::Buildable, gtk4::ConstraintTarget; @@ -107,10 +131,55 @@ impl Default for McpPage { } } +// The client page pushed over the dialog, rebuilt when a survey changes +// what it shows. +pub struct OpenSubpage { + id: String, + view: adw::ToolbarView, + page: glib::WeakRef, + shown: Shown, +} + +// Everything a client's page is built from. A survey that changes none +// of it leaves the page alone, and with it the focus inside. +#[derive(Debug, Clone, PartialEq)] +struct Shown { + status: ClientConfigStatus, + config_path: Option, + action: ClientAction, + removable: bool, + port: u16, +} + +impl Shown { + fn of(state: &ClientState, port: u16) -> Self { + Self { + status: state.status, + config_path: state.config_path.clone(), + action: state.action, + removable: state.removable, + port, + } + } +} + +// A client's row lives as long as the page: a survey rewrites its text +// and its button in place, so the keyboard focus stays on it. +#[derive(Clone)] +pub struct ClientRow { + id: String, + row: adw::ActionRow, + button: gtk4::Button, +} + impl McpPage { - /// `service` is `None` where no server can run, such as a test that - /// brings none; the page then only edits the preferences. + // `service` is `None` where no server can run, such as a test that + // brings none; the page then only edits the preferences. pub(super) fn bind(&self, settings: &AppSettings, service: Option) { + self.bind_on(settings, service, ClientHost::current()); + } + + fn bind_on(&self, settings: &AppSettings, service: Option, host: ClientHost) { let imp = self.imp(); let gio_settings = settings.gio(); gio_settings @@ -119,11 +188,35 @@ impl McpPage { gio_settings .bind(keys::MCP_SERVER_PORT, &imp.port_row.get(), "value") .build(); + imp.token_row.set_subtitle(MASKED_AUTHORIZATION); + self.connect_controls(); + imp.clients_group.set_visible(service.is_some()); + match &service { + Some(service) => { + imp.host.replace(Some(host)); + self.follow(service.status()); + self.follow_clients(service.seen_clients()); + } + None => self.show_status(McpStatus::Off), + } + let surveyed = service.is_some(); + imp.service.replace(service); + if surveyed { + self.show_clients(Vec::new()); + self.refresh_clients(); + } + // Another program may have changed a client's file since. + self.connect_map(|page| page.refresh_clients()); + } + + fn connect_controls(&self) { + let imp = self.imp(); let page = self.downgrade(); imp.port_row.connect_value_notify(move |_| { if let Some(page) = page.upgrade() { page.refresh(); + page.refresh_clients(); } }); let page = self.downgrade(); @@ -135,7 +228,7 @@ impl McpPage { let page = self.downgrade(); imp.copy_token_button.connect_clicked(move |_| { if let Some(page) = page.upgrade() { - page.copy_token(); + page.copy_authorization(); } }); let page = self.downgrade(); @@ -150,16 +243,10 @@ impl McpPage { service.retry(); } }); - - match &service { - Some(service) => self.follow(service.status()), - None => self.show_status(McpStatus::Off), - } - imp.service.replace(service); } - /// AdwPreferencesDialog owns the toast overlay, so the page hands its - /// toasts up rather than looking for one. + // AdwPreferencesDialog owns the toast overlay, so the page hands its + // toasts up rather than looking for one. pub(super) fn connect_toast(&self, f: F) -> glib::SignalHandlerId { self.connect_closure( "toast", @@ -181,6 +268,7 @@ impl McpPage { return; }; page.show_status(shown); + page.refresh_clients(); drop(page); if status.changed().await.is_err() { return; @@ -197,39 +285,57 @@ impl McpPage { self.refresh(); } + // The address and the token are known while the server is off, and a + // token that leaked has to be replaceable without serving it first. fn refresh(&self) { let imp = self.imp(); let status = imp.status.borrow().clone().unwrap_or(McpStatus::Off); imp.status_row.set_subtitle(&status_text(&status)); imp.retry_button.set_visible(matches!(status, McpStatus::Failed(_))); - imp.client_group.set_sensitive(status.port().is_some()); - let port = status.port().unwrap_or(imp.port_row.value() as u16); - imp.address_row.set_subtitle(&address(port)); + imp.address_row.set_subtitle(&address(self.port())); + } + + fn port(&self) -> u16 { + let imp = self.imp(); + let running = imp.status.borrow().as_ref().and_then(McpStatus::port); + running.unwrap_or(imp.port_row.value() as u16) } fn copy_address(&self) { - let Some(port) = self.imp().status.borrow().as_ref().and_then(McpStatus::port) else { - return; - }; - crate::ui::clipboard::copy_text(self, address(port), |message| self.toast(message)); + crate::ui::clipboard::copy_text(self, address(self.port()), |message| self.toast(message)); } - fn copy_token(&self) { - let Some(token) = self.service().and_then(|service| service.token()) else { - return; - }; - crate::ui::clipboard::copy_text(self, token.expose_secret().to_owned(), |message| self.toast(message)); + fn copy_authorization(&self) { + let page = self.clone(); + glib::spawn_future_local(async move { + if let Some(header) = page.authorization().await { + crate::ui::clipboard::copy_text(&page, header, |message| page.toast(message)); + } + }); + } + + // The header value with the token, read from the keyring if the + // server is off. A failure has been shown when this is None. + async fn authorization(&self) -> Option { + let service = self.service()?; + match service.access_token().await { + Ok(token) => Some(authorization_header(token.expose_secret())), + Err(failure) => { + self.toast(&failure_text(&failure)); + None + } + } } fn confirm_regenerate(&self) { let alert = adw::AlertDialog::new( - Some(&crate::i18n::gettext("Regenerate Access Token?")), - Some(&crate::i18n::gettext( + Some(&gettext("Regenerate Access Token?")), + Some(&gettext( "Clients that use the current token are refused until you give them the new one.", )), ); - alert.add_response(CANCEL, &crate::i18n::gettext("_Cancel")); - alert.add_response(REGENERATE, &crate::i18n::gettext("_Regenerate")); + alert.add_response(CANCEL, &gettext("_Cancel")); + alert.add_response(REGENERATE, &gettext("_Regenerate")); alert.set_response_appearance(REGENERATE, adw::ResponseAppearance::Destructive); alert.set_default_response(Some(CANCEL)); alert.set_close_response(CANCEL); @@ -245,7 +351,8 @@ impl McpPage { match service.regenerate_token().await { Ok(()) => { page.imp().unsaved_token.dismiss(); - page.toast(&crate::i18n::gettext("New access token made. Copy it to your clients.")); + page.toast(&gettext("New access token made. Copy it to your clients.")); + page.refresh_clients(); } Err(McpFailure::Keyring(error)) => { let toast = page @@ -262,74 +369,787 @@ impl McpPage { fn toast(&self, message: &str) { self.emit_by_name::<()>("toast", &[&crate::ui::plain_toast(message)]); } + + // Reads every client's file off the GTK thread. The token is compared + // only while the server runs, so an off server never opens the keyring. + fn refresh_clients(&self) { + let imp = self.imp(); + let (Some(service), Some(host)) = (self.service(), imp.host.borrow().clone()) else { + return; + }; + let generation = imp.survey_generation.get() + 1; + imp.survey_generation.set(generation); + let url = address(self.port()); + let authorization = service.token().map(|token| authorization_header(token.expose_secret())); + let surveying = service + .tasks() + .spawn_blocking_task(move || mcp_clients::survey(&host, &url, authorization.as_deref())); + let page = self.downgrade(); + let delivering = glib::spawn_future_local(async move { + let surveyed = surveying.await; + let Some(page) = page.upgrade() else { + return; + }; + if page.imp().survey_generation.get() != generation { + return; + } + match surveyed { + Ok(states) => page.show_clients(states), + Err(failure) => tracing::warn!(%failure, "reading the MCP clients' files failed"), + } + }); + if let Some(previous) = imp.surveying.replace(Some(delivering)) { + previous.abort(); + } + } + + fn show_clients(&self, states: Vec) { + let imp = self.imp(); + let order = self.client_order(&states); + imp.states.replace(states); + let shown: Vec = imp.client_rows.borrow().iter().map(|row| row.id.clone()).collect(); + let mut kept: HashMap = imp + .client_rows + .take() + .into_iter() + .map(|row| (row.id.clone(), row)) + .collect(); + let rows: Vec = order + .into_iter() + .map(|client| kept.remove(&client.id).unwrap_or_else(|| self.client_row(client))) + .collect(); + for row in &rows { + self.update_row(row); + } + if rows.iter().map(|row| &row.id).ne(shown.iter()) { + let focus = self.focus_in_clients(); + let placed = rows.iter().filter(|row| shown.contains(&row.id)); + for row in kept.values().chain(placed) { + imp.clients_group.remove(&row.row); + } + for row in &rows { + imp.clients_group.add(&row.row); + } + // Taking a row out of the group takes the focus with it. + if let Some(widget) = focus + && widget.is_visible() + && widget.is_ancestor(&*imp.clients_group) + { + widget.grab_focus(); + } + } + imp.client_rows.replace(rows); + self.refresh_subpage(); + } + + // The first survey sorts the rows, set up first. Later ones keep that + // order, so no row moves while the user is on it; the next dialog + // sorts again. + fn client_order(&self, states: &[ClientState]) -> Vec<&'static ClientDefinition> { + let imp = self.imp(); + if states.is_empty() { + return mcp_clients::linux_clients().collect(); + } + let shown: Vec = imp.client_rows.borrow().iter().map(|row| row.id.clone()).collect(); + let same_clients = shown.len() == states.len() && states.iter().all(|state| shown.contains(&state.client.id)); + let mut surveyed: Vec<&ClientState> = states.iter().collect(); + match imp.rows_placed.get() && same_clients { + true => surveyed.sort_by_key(|state| shown.iter().position(|id| *id == state.client.id)), + false => { + surveyed.sort_by_key(|state| state.rank()); + imp.rows_placed.set(true); + } + } + surveyed.into_iter().map(|state| state.client).collect() + } + + fn focus_in_clients(&self) -> Option { + let focus = gtk4::prelude::RootExt::focus(&self.root()?)?; + focus.is_ancestor(&*self.imp().clients_group).then_some(focus) + } + + fn client_row(&self, client: &ClientDefinition) -> ClientRow { + let row = adw::ActionRow::builder() + .title(client.name.as_str()) + .use_markup(false) + .activatable(true) + .build(); + row.add_prefix(>k4::Image::from_icon_name(crate::ui::icons::client_icon( + &client.icon, + ))); + let button = gtk4::Button::builder() + .valign(gtk4::Align::Center) + .visible(false) + .build(); + let (page, id) = (self.downgrade(), client.id.clone()); + button.connect_clicked(move |_| { + if let Some(page) = page.upgrade() + && let Some(state) = page.state(&id) + { + page.run_action(&id, state.action); + } + }); + row.add_suffix(&button); + row.add_suffix(>k4::Image::from_icon_name(crate::ui::icons::GO_NEXT)); + let (page, id) = (self.downgrade(), client.id.clone()); + row.connect_activated(move |_| { + if let Some(page) = page.upgrade() { + page.open_client(&id); + } + }); + ClientRow { + id: client.id.clone(), + row, + button, + } + } + + fn update_row(&self, row: &ClientRow) { + let state = self.state(&row.id); + let status = state.as_ref().map_or_else(|| gettext("Checking…"), row_status_text); + row.row.set_subtitle(&status); + match state.as_ref().and_then(action_labels) { + Some((label, described)) => { + row.button.set_label(&label); + row.button + .update_property(&[gtk4::accessible::Property::Label(&described)]); + row.button.set_visible(true); + } + None => { + // A hidden button that keeps the focus leaves the keyboard + // nowhere, so the row takes it. + if row.button.is_focus() { + row.row.grab_focus(); + } + row.button.set_visible(false); + } + } + } + + fn state(&self, id: &str) -> Option { + self.imp() + .states + .borrow() + .iter() + .find(|state| state.client.id == id) + .cloned() + } + + fn run_action(&self, id: &str, action: ClientAction) { + match action { + ClientAction::Install | ClientAction::Update => self.install_client(id), + ClientAction::Copy => self.copy_setup(id), + ClientAction::None => {} + } + } + + fn copy_setup(&self, id: &str) { + let (page, id) = (self.clone(), id.to_owned()); + glib::spawn_future_local(async move { + let Some(header) = page.authorization().await else { + return; + }; + match mcp_clients::setup_text(&id, &address(page.port()), &header) { + Ok(setup) => crate::ui::clipboard::copy_text(&page, setup, |message| page.toast(message)), + Err(error) => page.toast(&setup_error_text(&error, &page.home())), + } + }); + } + + fn sandboxed(&self) -> bool { + self.imp().host.borrow().as_ref().is_some_and(|host| host.sandboxed) + } + + fn home(&self) -> std::path::PathBuf { + self.imp() + .host + .borrow() + .as_ref() + .map(|host| host.home.clone()) + .unwrap_or_default() + } + + fn install_client(&self, id: &str) { + let (page, id) = (self.clone(), id.to_owned()); + glib::spawn_future_local(async move { + let (Some(service), Some(host)) = (page.service(), page.imp().host.borrow().clone()) else { + return; + }; + let Some(header) = page.authorization().await else { + return; + }; + let (client, url) = (id.clone(), address(page.port())); + let installing = service + .tasks() + .spawn_blocking_task(move || mcp_clients::install(&host, &client, &url, &header)); + let outcome = installing.await; + page.report(&id, outcome, Done::Installed); + }); + } + + fn remove_client(&self, id: &str) { + let (page, id) = (self.clone(), id.to_owned()); + glib::spawn_future_local(async move { + let (Some(service), Some(host), Some(state)) = + (page.service(), page.imp().host.borrow().clone(), page.state(&id)) + else { + return; + }; + let alert = removal_alert(&state, &host); + let parent: gtk4::Widget = page.clone().upcast(); + if crate::workspace::respond(&alert, &parent).await != REMOVE { + return; + } + let client = id.clone(); + let removing = service + .tasks() + .spawn_blocking_task(move || mcp_clients::remove(&host, &client)); + let outcome = removing.await; + page.report(&id, outcome, Done::Removed); + }); + } + + fn report( + &self, + id: &str, + outcome: Result, tablepro_session::runtime::TaskFailure>, + done: Done, + ) { + let name = self + .state(id) + .map(|state| state.client.name.clone()) + .unwrap_or_default(); + match outcome { + Ok(Ok(_)) => { + let message = match done { + Done::Installed => { + let applies = self.state(id).and_then(|state| state.applies()); + let mut message = gettext_f("{client} is set up.", &[("client", &name)]); + if let Some(applies) = applies { + message = format!("{message} {}", applies_text(applies, &name)); + } + message + } + Done::Removed => gettext_f("TablePro was removed from {client}.", &[("client", &name)]), + }; + self.toast(&message); + } + Ok(Err(error)) => { + tracing::warn!(%error, client = id, "setting up an MCP client failed"); + self.toast(&setup_error_text(&error, &self.home())); + } + Err(failure) => { + tracing::warn!(%failure, client = id, "setting up an MCP client was interrupted"); + self.toast(&gettext("The change to the client stopped unexpectedly.")); + } + } + self.refresh_clients(); + } + + fn open_client(&self, id: &str) { + let Some(state) = self.state(id) else { + return; + }; + let view = adw::ToolbarView::new(); + view.add_top_bar(&adw::HeaderBar::new()); + view.set_content(Some(&self.client_content(&state))); + let subpage = adw::NavigationPage::new(&view, &state.client.name); + let page = self.downgrade(); + subpage.connect_hidden(move |hidden| { + let Some(page) = page.upgrade() else { + return; + }; + let open = page + .imp() + .subpage + .borrow() + .as_ref() + .and_then(|open| open.page.upgrade()); + if open.as_ref() == Some(hidden) { + page.imp().subpage.replace(None); + } + }); + self.imp().subpage.replace(Some(OpenSubpage { + id: id.to_owned(), + view, + page: subpage.downgrade(), + shown: Shown::of(&state, self.port()), + })); + if let Some(dialog) = self + .ancestor(adw::PreferencesDialog::static_type()) + .and_downcast::() + { + dialog.push_subpage(&subpage); + } + } + + fn refresh_subpage(&self) { + let open = self + .imp() + .subpage + .borrow() + .as_ref() + .map(|open| (open.id.clone(), open.view.clone(), open.shown.clone())); + let Some((id, view, shown)) = open else { + return; + }; + let Some(state) = self.state(&id) else { + return; + }; + let now = Shown::of(&state, self.port()); + if now == shown { + return; + } + view.set_content(Some(&self.client_content(&state))); + if let Some(open) = self.imp().subpage.borrow_mut().as_mut() { + open.shown = now; + } + } + + fn client_content(&self, state: &ClientState) -> adw::PreferencesPage { + let content = adw::PreferencesPage::new(); + content.add(&self.connection_group(state)); + if state.unsupported().is_none() { + content.add(&self.manual_group(state)); + if let Some(actions) = self.actions_group(state) { + content.add(&actions); + } + } + content + } + + fn connection_group(&self, state: &ClientState) -> adw::PreferencesGroup { + let name = state.client.name.as_str(); + let group = adw::PreferencesGroup::builder().title(gettext("Connection")).build(); + let description = match state.status { + ClientConfigStatus::Disabled => Some(gettext_f( + "TablePro is turned off in {client}. Turn it on there to use it.", + &[("client", name)], + )), + ClientConfigStatus::Stale(StaleReason::Shadowed) => Some(gettext_f( + "A project in {client} has its own TablePro setup with an old address or access token, and uses it in place of this one.", + &[("client", name)], + )), + _ => state + .applies() + .filter(|_| state.unsupported().is_none()) + .map(|applies| applies_text(applies, name)), + }; + // A group's description is markup. + if let Some(description) = description { + group.set_description(Some(&glib::markup_escape_text(&description))); + } + group.add(&property_row(&gettext("Status"), &row_status_text(state))); + if let Some(reason) = state.unsupported() { + let row = property_row(&gettext("Reason"), &reason_text(reason, name)); + row.set_subtitle_lines(0); + group.add(&row); + } + if let Some(path) = &state.config_path { + let row = property_row(&gettext("Configuration File"), &display_path(path, &self.home())); + row.set_subtitle_selectable(true); + group.add(&row); + } + group + } + + fn manual_group(&self, state: &ClientState) -> adw::PreferencesGroup { + let id = state.client.id.as_str(); + let group = adw::PreferencesGroup::builder() + .title(gettext("Manual Setup")) + .description(glib::markup_escape_text(&manual_text( + state, + self.sandboxed(), + &self.home(), + ))) + .build(); + let copy = gtk4::Button::with_label(&gettext("Copy")); + copy.set_valign(gtk4::Align::Center); + copy.add_css_class("flat"); + copy.update_property(&[gtk4::accessible::Property::Label(&gettext("Copy the Setup"))]); + let (page, client) = (self.downgrade(), id.to_owned()); + copy.connect_clicked(move |_| { + if let Some(page) = page.upgrade() { + page.copy_setup(&client); + } + }); + group.set_header_suffix(Some(©)); + let shown = mcp_clients::setup_text(id, &address(self.port()), MASKED_AUTHORIZATION).unwrap_or_default(); + group.add(&code_card(&shown)); + let note = gtk4::Label::builder() + .label(gettext("The access token is hidden here. Copy includes it.")) + .xalign(0.0) + .wrap(true) + .margin_top(6) + .build(); + note.add_css_class("caption"); + note.add_css_class("dim-label"); + group.add(¬e); + group + } + + fn actions_group(&self, state: &ClientState) -> Option { + let group = adw::PreferencesGroup::new(); + let mut any = false; + let label = match state.action { + ClientAction::Install => Some(gettext("Install")), + ClientAction::Update => Some(gettext("Update")), + ClientAction::Copy | ClientAction::None => None, + }; + if let Some(label) = label { + let row = adw::ButtonRow::builder().title(label).build(); + row.add_css_class("suggested-action"); + let (page, id, action) = (self.downgrade(), state.client.id.clone(), state.action); + row.connect_activated(move |_| { + if let Some(page) = page.upgrade() { + page.run_action(&id, action); + } + }); + group.add(&row); + any = true; + } + if state.removable { + let row = adw::ButtonRow::builder().title(gettext("Remove…")).build(); + row.add_css_class("destructive-action"); + let (page, id) = (self.downgrade(), state.client.id.clone()); + row.connect_activated(move |_| { + if let Some(page) = page.upgrade() { + page.remove_client(&id); + } + }); + group.add(&row); + any = true; + } + any.then_some(group) + } + + fn follow_clients(&self, mut seen: watch::Receiver>) { + let known = seen + .borrow_and_update() + .iter() + .map(|client| (client.name.clone(), client.seen_at)) + .collect(); + self.imp().sightings.replace(known); + let page = self.downgrade(); + let following = glib::spawn_future_local(async move { + while seen.changed().await.is_ok() { + let clients = seen.borrow_and_update().clone(); + let Some(page) = page.upgrade() else { + return; + }; + page.announce(clients); + } + }); + if let Some(previous) = self.imp().following_clients.replace(Some(following)) { + previous.abort(); + } + } + + fn announce(&self, clients: Vec) { + let fresh: Vec = { + let known = self.imp().sightings.borrow(); + clients + .iter() + .filter(|client| known.get(&client.name) != Some(&client.seen_at)) + .cloned() + .collect() + }; + self.imp().sightings.replace( + clients + .into_iter() + .map(|client| (client.name, client.seen_at)) + .collect(), + ); + let states = self.imp().states.borrow().clone(); + for client in fresh { + let name = connected_name(&client, &states); + self.toast(&gettext_f("{client} just connected", &[("client", &name)])); + } + } +} + +#[derive(Debug, Clone, Copy)] +enum Done { + Installed, + Removed, +} + +// The row button's label and the longer name a screen reader says. +fn action_labels(state: &ClientState) -> Option<(String, String)> { + let client = [("client", state.client.name.as_str())]; + match state.action { + ClientAction::Install => Some((gettext("Install"), gettext_f("Install in {client}", &client))), + ClientAction::Update => Some((gettext("Update"), gettext_f("Update {client}", &client))), + ClientAction::Copy => Some((gettext("Copy"), gettext_f("Copy the Setup for {client}", &client))), + ClientAction::None => None, + } +} + +fn property_row(title: &str, subtitle: &str) -> adw::ActionRow { + let row = adw::ActionRow::builder() + .title(title) + .subtitle(subtitle) + .use_markup(false) + .build(); + row.add_css_class("property"); + row +} + +fn code_card(text: &str) -> gtk4::Box { + let label = gtk4::Label::builder() + .label(text) + .xalign(0.0) + .wrap(true) + .wrap_mode(gtk4::pango::WrapMode::WordChar) + .selectable(true) + .margin_top(10) + .margin_bottom(10) + .margin_start(12) + .margin_end(12) + .build(); + label.add_css_class("monospace"); + let card = gtk4::Box::new(gtk4::Orientation::Vertical, 0); + card.add_css_class("card"); + card.append(&label); + card +} + +fn removal_alert(state: &ClientState, host: &ClientHost) -> adw::AlertDialog { + let name = state.client.name.as_str(); + let body = match (state.removes_with_command, &state.config_path) { + (true, _) => mcp_clients::remove_command(host, &state.client.id).map(|command| { + gettext_f( + "TablePro runs “{command}” to remove its entry.", + &[("command", &command)], + ) + }), + (false, Some(path)) => Some(gettext_f( + "TablePro removes its entry from {file}. The file as it was is kept as {backup}.", + &[ + ("file", &display_path(path, &host.home)), + ("backup", &display_path(&mcp_clients::backup_path(path), &host.home)), + ], + )), + (false, None) => None, + }; + let alert = adw::AlertDialog::new( + Some(&gettext_f("Remove TablePro From {client}?", &[("client", name)])), + body.as_deref(), + ); + alert.add_response(CANCEL, &gettext("_Cancel")); + alert.add_response(REMOVE, &gettext("_Remove")); + alert.set_response_appearance(REMOVE, adw::ResponseAppearance::Destructive); + alert.set_default_response(Some(CANCEL)); + alert.set_close_response(CANCEL); + alert } pub(crate) fn address(port: u16) -> String { format!("http://127.0.0.1:{port}{}", tablepro_mcp::MCP_PATH) } +// A client that sends the token without the scheme is refused, so the +// header value is what gets copied. +fn authorization_header(token: &str) -> String { + format!("Bearer {token}") +} + +fn display_path(path: &Path, home: &Path) -> String { + match path.strip_prefix(home) { + Ok(below) if !home.as_os_str().is_empty() => format!("~/{}", below.display()), + _ => path.display().to_string(), + } +} + +// Several clients share an engine, as ChatGPT and Codex do, so the one +// found on this computer names a sighting. +fn connected_name(seen: &SeenClient, states: &[ClientState]) -> String { + let matches = mcp_clients::catalog() + .map(|catalog| catalog.clients_for_client_info(&seen.name, ClientPlatform::Linux)) + .unwrap_or_default(); + let found = matches.iter().find(|client| { + states + .iter() + .any(|state| state.client.id == client.id && (state.detected || state.status.is_configured())) + }); + match found.or(matches.first()) { + Some(client) => client.name.clone(), + None => seen.title.clone().unwrap_or_else(|| seen.name.clone()), + } +} + +fn row_status_text(state: &ClientState) -> String { + match state.unsupported() { + Some(UnsupportedReason::StdioOnly) => gettext("Cannot connect to an address"), + Some(UnsupportedReason::RemoteOnly) => gettext("Connects only to servers on the internet"), + None => client_status_text(state.status), + } +} + +fn client_status_text(status: ClientConfigStatus) -> String { + match status { + ClientConfigStatus::NotConfigured => gettext("Not set up"), + ClientConfigStatus::Current => gettext("Set up"), + ClientConfigStatus::Disabled => gettext("Set up but turned off in the client"), + ClientConfigStatus::Stale(StaleReason::Shadowed) => gettext("Set up, but a project uses an old setup"), + ClientConfigStatus::Stale(StaleReason::OtherUrl) => gettext("Set up for another address"), + ClientConfigStatus::Stale(StaleReason::OtherToken) => gettext("Set up with an old access token"), + ClientConfigStatus::Stale(StaleReason::OtherCommand | StaleReason::CommandMissing) => { + gettext("Set up for another server") + } + ClientConfigStatus::OtherScope => gettext("Set up for one project only"), + ClientConfigStatus::Unreadable => gettext("Its configuration file cannot be read"), + ClientConfigStatus::Unknown => gettext("Set up by hand in the client"), + } +} + +fn reason_text(reason: UnsupportedReason, client: &str) -> String { + match reason { + UnsupportedReason::StdioOnly => gettext_f( + "{client} runs only servers it starts itself, and TablePro on Linux serves MCP at an address.", + &[("client", client)], + ), + UnsupportedReason::RemoteOnly => gettext_f( + "{client} connects to MCP servers from the internet, so it cannot reach TablePro on this computer.", + &[("client", client)], + ), + } +} + +fn applies_text(applies: Applies, client: &str) -> String { + let client = [("client", client)]; + match applies { + Applies::Live => gettext_f("{client} picks up the change on its own.", &client), + Applies::NewSession => gettext_f("Start a new session in {client} to use it.", &client), + Applies::RestartApp => gettext_f("Quit and reopen {client} to use it.", &client), + Applies::Reload => gettext_f("Reload the MCP servers in {client} to use it.", &client), + } +} + +fn manual_text(state: &ClientState, sandboxed: bool, home: &Path) -> String { + let name = [("client", state.client.name.as_str())]; + if mcp_clients::setup_is_command(state.client) { + return match sandboxed { + true => gettext_f( + "Run this command in a terminal. TablePro runs in a sandbox and cannot start {client} itself.", + &name, + ), + false => gettext("Run this command in a terminal."), + }; + } + match &state.config_path { + Some(path) => gettext_f("Add this to {file}.", &[("file", &display_path(path, home))]), + None => gettext_f("Add this in the MCP settings of {client}.", &name), + } +} + +fn setup_error_text(error: &ClientSetupError, home: &Path) -> String { + let path = match error { + ClientSetupError::Edit { path, .. } + | ClientSetupError::Io { path, .. } + | ClientSetupError::NotText(path) + | ClientSetupError::ChangedDuringWrite(path) + | ClientSetupError::VerificationFailed(path) => display_path(path, home), + _ => String::new(), + }; + let file = [("file", path.as_str())]; + match error { + ClientSetupError::UnknownClient | ClientSetupError::NoInstaller => { + gettext("TablePro cannot set up this client. Copy the setup instead.") + } + ClientSetupError::Template(_) => gettext("The setup for this client could not be made."), + ClientSetupError::Edit { + error: ConfigEditError::InvalidSyntax { .. }, + .. + } => gettext_f("{file} is not valid, so TablePro left it as it is.", &file), + ClientSetupError::Edit { + error: ConfigEditError::DuplicateKey { .. }, + .. + } => gettext_f("{file} names a setting twice, so TablePro left it as it is.", &file), + ClientSetupError::Edit { .. } => gettext_f( + "{file} is written in a way TablePro does not edit. Copy the setup instead.", + &file, + ), + ClientSetupError::Io { source, .. } => gettext_f( + "{file} could not be written: {detail}", + &[("file", &path), ("detail", &source.to_string())], + ), + ClientSetupError::NotText(_) => gettext_f("{file} is not a text file, so TablePro left it as it is.", &file), + ClientSetupError::ChangedDuringWrite(_) => { + gettext_f("{file} kept changing while TablePro wrote it. Try again.", &file) + } + ClientSetupError::VerificationFailed(_) => gettext_f( + "{file} did not keep the change. Check whether the client rewrote it.", + &file, + ), + ClientSetupError::CommandFailed(_) => gettext("The client’s command failed."), + ClientSetupError::CommandTimedOut => gettext("The client’s command did not finish."), + } +} + pub(crate) fn status_text(status: &McpStatus) -> String { match status { - McpStatus::Off => crate::i18n::gettext("Off"), - McpStatus::Starting => crate::i18n::gettext("Starting…"), - McpStatus::Running { port } => crate::i18n::gettext_f("Running on port {port}", &[("port", &port.to_string())]), + McpStatus::Off => gettext("Off"), + McpStatus::Starting => gettext("Starting…"), + McpStatus::Running { port } => gettext_f("Running on port {port}", &[("port", &port.to_string())]), McpStatus::Failed(failure) => failure_text(failure), } } pub(crate) fn failure_text(failure: &McpFailure) -> String { match failure { - McpFailure::PortInUse(port) => crate::i18n::gettext_f( + McpFailure::PortInUse(port) => gettext_f( "Port {port} is in use by another program. Choose another port.", &[("port", &port.to_string())], ), McpFailure::Listen { port, kind } => match kind { - std::io::ErrorKind::PermissionDenied => crate::i18n::gettext_f( + std::io::ErrorKind::PermissionDenied => gettext_f( "The system does not let TablePro listen on port {port}. Choose another port.", &[("port", &port.to_string())], ), - _ => crate::i18n::gettext_f( + _ => gettext_f( "TablePro could not listen on port {port}.", &[("port", &port.to_string())], ), }, McpFailure::Keyring(error) => keyring_text(error), McpFailure::NoRandomness => { - crate::i18n::gettext("The system’s random number source failed, so no access token could be made.") + gettext("The system’s random number source failed, so no access token could be made.") } - McpFailure::Interrupted(_) => crate::i18n::gettext("The server stopped unexpectedly."), + McpFailure::Interrupted(_) => gettext("The server stopped unexpectedly."), } } -/// The token is not a password, so the keyring sentences say what the -/// server cannot do without it. +// The token is not a password, so the keyring sentences say what the +// server cannot do without it. fn keyring_text(error: &SecretError) -> String { match error { SecretError::Locked | SecretError::UnlockDismissed => { - crate::i18n::gettext("The keyring is locked, so the access token cannot be read. Unlock it and try again.") + gettext("The keyring is locked, so the access token cannot be read. Unlock it and try again.") } - SecretError::ServiceUnavailable { .. } => crate::i18n::gettext( - "No keyring is running, so the access token cannot be kept. Start a keyring and try again.", - ), - SecretError::PortalUnavailable { .. } => crate::i18n::gettext( + SecretError::ServiceUnavailable { .. } => { + gettext("No keyring is running, so the access token cannot be kept. Start a keyring and try again.") + } + SecretError::PortalUnavailable { .. } => gettext( "The secret portal is unavailable, so the access token cannot be kept. Check that xdg-desktop-portal and a keyring are running.", ), - SecretError::InvalidEncoding => crate::i18n::gettext("The stored access token is not readable text."), + SecretError::InvalidEncoding => gettext("The stored access token is not readable text."), SecretError::Backend { service_message, .. } => match service_message { - Some(message) => crate::i18n::gettext_f("The keyring reported: {detail}", &[("detail", message)]), - None => crate::i18n::gettext("The keyring failed without giving a reason."), + Some(message) => gettext_f("The keyring reported: {detail}", &[("detail", message)]), + None => gettext("The keyring failed without giving a reason."), }, } } #[cfg(test)] mod tests { + use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use super::*; use crate::services::mcp_service::tests::{MemoryTokens, context, free_port}; - use crate::test_support::{MemorySettings, test_runtime, wait_until}; + use crate::test_support::{MemorySettings, OwnedWindow, assert_labelled, descendants, test_runtime, wait_until}; const WAIT: Duration = Duration::from_secs(10); @@ -340,6 +1160,49 @@ mod tests { page } + fn page_on(settings: &MemorySettings, service: McpService, home: &Path) -> McpPage { + crate::register_test_resources(); + let page = McpPage::default(); + page.bind_on(settings.get(), Some(service), ClientHost::under(home)); + page + } + + fn subtitle(page: &McpPage, name: &str) -> Option { + page.imp() + .client_rows + .borrow() + .iter() + .find(|client| client.row.title() == name) + .and_then(|client| client.row.subtitle()) + .map(|text| text.to_string()) + } + + fn client_row(page: &McpPage, id: &str) -> ClientRow { + page.imp() + .client_rows + .borrow() + .iter() + .find(|client| client.id == id) + .cloned() + .expect("the client's row") + } + + fn shown_on_a_window(page: &McpPage) -> OwnedWindow { + let window = OwnedWindow::presented(adw::Window::builder().default_width(900).default_height(700).build()); + window.set_content(Some(page)); + window + } + + fn stopped_service(settings: &MemorySettings, runtime: &crate::runtime::AppRuntime, root: &Path) -> McpService { + settings.get().set_mcp_server_port(free_port()).expect("the port"); + McpService::start( + settings.get().clone(), + runtime.tasks(), + Arc::new(MemoryTokens::default()), + context(root), + ) + } + #[gtk4::test] fn the_switch_and_port_edit_the_preferences() { let settings = MemorySettings::new(); @@ -350,7 +1213,12 @@ mod tests { assert!(!imp.enabled_row.is_active(), "the server starts off"); assert_eq!(imp.port_row.value(), 23508.0); assert_eq!(imp.status_row.subtitle().as_deref(), Some("Off")); - assert!(!imp.client_group.is_sensitive()); + assert!( + imp.client_group.is_sensitive(), + "the address, the header and Regenerate work while the server is off" + ); + assert_eq!(imp.token_row.subtitle().as_deref(), Some(MASKED_AUTHORIZATION)); + assert!(!imp.clients_group.is_visible(), "no server, so no client to set up"); imp.enabled_row.set_active(true); imp.port_row.set_value(40_000.0); @@ -368,15 +1236,10 @@ mod tests { let settings = MemorySettings::new(); let runtime = test_runtime(); let root = tempfile::tempdir().expect("tempdir"); - let port = free_port(); - settings.get().set_mcp_server_port(port).expect("the port"); - let service = McpService::start( - settings.get().clone(), - runtime.tasks(), - Arc::new(MemoryTokens::default()), - context(root.path()), - ); - let page = bound_page(&settings, Some(service.clone())); + let home = tempfile::tempdir().expect("tempdir"); + let service = stopped_service(&settings, &runtime, root.path()); + let port = settings.get().mcp_server_port(); + let page = page_on(&settings, service.clone(), home.path()); let imp = page.imp(); imp.enabled_row.set_active(true); @@ -395,6 +1258,435 @@ mod tests { runtime.shutdown(); } + #[gtk4::test] + fn the_clients_are_listed_set_up_first_with_their_state() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let service = stopped_service(&settings, &runtime, root.path()); + let cursor = format!( + r#"{{"mcpServers": {{"tablepro": {{"url": "{}", "headers": {{"Authorization": "Bearer tp_x"}}}}}}}}"#, + address(settings.get().mcp_server_port()) + ); + std::fs::create_dir_all(home.path().join(".cursor")).expect("a folder"); + std::fs::write(home.path().join(".cursor/mcp.json"), cursor).expect("a config"); + + let page = page_on(&settings, service.clone(), home.path()); + + wait_until(WAIT, || subtitle(&page, "Cursor").as_deref() == Some("Set up")).expect("Cursor read as set up"); + let rows: Vec = page + .imp() + .client_rows + .borrow() + .iter() + .map(|client| client.row.clone()) + .collect(); + assert_eq!(rows.len(), mcp_clients::linux_clients().count()); + assert_eq!(rows[0].title(), "Cursor"); + assert_eq!( + subtitle(&page, "Claude Desktop").as_deref(), + Some("Cannot connect to an address") + ); + assert_eq!(subtitle(&page, "Zed").as_deref(), Some("Not set up")); + for row in &rows { + assert_labelled(row).unwrap_or_else(|problem| panic!("{}: {problem}", row.title())); + } + assert_eq!( + crate::test_support::unlabelled_icon_buttons(&page), + Vec::::new() + ); + service.stop(); + runtime.shutdown(); + } + + #[gtk4::test] + fn a_refresh_keeps_the_focus_on_the_row_it_changes() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let service = stopped_service(&settings, &runtime, root.path()); + let page = page_on(&settings, service.clone(), home.path()); + let window = shown_on_a_window(&page); + wait_until(WAIT, || subtitle(&page, "Cursor").as_deref() == Some("Not set up")).expect("the survey"); + let order = |page: &McpPage| -> Vec { + page.imp() + .client_rows + .borrow() + .iter() + .map(|client| client.id.clone()) + .collect() + }; + let before = order(&page); + let cursor = client_row(&page, "cursor"); + cursor.row.grab_focus(); + assert!(cursor.row.is_focus(), "the row takes the focus"); + + let host = ClientHost::under(home.path()); + mcp_clients::install(&host, "cursor", &address(page.port()), "Bearer tp_x").expect("installed"); + page.refresh_clients(); + + wait_until(WAIT, || subtitle(&page, "Cursor").as_deref() == Some("Set up")).expect("Cursor set up"); + assert_eq!(client_row(&page, "cursor").row, cursor.row, "the row was built again"); + assert!(cursor.row.is_focus(), "the refresh took the focus off the row"); + assert_eq!(order(&page), before, "a row moved while the page was open"); + drop(window); + service.stop(); + runtime.shutdown(); + } + + #[gtk4::test] + fn sorting_the_rows_keeps_the_focus_on_the_row_that_had_it() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let service = stopped_service(&settings, &runtime, root.path()); + let page = page_on(&settings, service.clone(), home.path()); + let window = shown_on_a_window(&page); + wait_until(WAIT, || subtitle(&page, "Zed").as_deref() == Some("Not set up")).expect("the survey"); + let zed = client_row(&page, "zed"); + zed.row.grab_focus(); + // As before the first survey, which sorts the rows. + page.imp().rows_placed.set(false); + + let host = ClientHost::under(home.path()); + mcp_clients::install(&host, "cursor", &address(page.port()), "Bearer tp_x").expect("installed"); + page.refresh_clients(); + + wait_until(WAIT, || { + page.imp() + .client_rows + .borrow() + .first() + .is_some_and(|first| first.id == "cursor") + }) + .expect("Cursor sorted first once set up"); + assert!(zed.row.is_focus(), "sorting took the focus off the row"); + drop(window); + service.stop(); + runtime.shutdown(); + } + + #[gtk4::test] + fn a_button_a_refresh_hides_hands_the_focus_to_its_row() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let service = stopped_service(&settings, &runtime, root.path()); + let page = page_on(&settings, service.clone(), home.path()); + let window = shown_on_a_window(&page); + wait_until(WAIT, || subtitle(&page, "Zed").as_deref() == Some("Not set up")).expect("Zed listed"); + let zed = client_row(&page, "zed"); + assert_eq!(zed.button.label().as_deref(), Some("Install")); + zed.button.grab_focus(); + assert!(zed.button.is_focus(), "Install takes the focus"); + + page.install_client("zed"); + + wait_until(WAIT, || subtitle(&page, "Zed").as_deref() == Some("Set up")).expect("Zed set up"); + assert!(!zed.button.is_visible(), "a set up client has nothing to install"); + assert!(zed.row.is_focus(), "the focus went with the hidden button"); + drop(window); + service.stop(); + runtime.shutdown(); + } + + #[gtk4::test] + fn a_client_page_is_built_again_only_when_what_it_shows_changes() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let service = stopped_service(&settings, &runtime, root.path()); + let page = page_on(&settings, service.clone(), home.path()); + wait_until(WAIT, || subtitle(&page, "Zed").as_deref() == Some("Not set up")).expect("Zed listed"); + page.open_client("zed"); + let view = page + .imp() + .subpage + .borrow() + .as_ref() + .map(|open| open.view.clone()) + .expect("Zed's page"); + let content = view.content(); + + let host = ClientHost::under(home.path()); + mcp_clients::install(&host, "cursor", &address(page.port()), "Bearer tp_x").expect("installed"); + page.refresh_clients(); + wait_until(WAIT, || subtitle(&page, "Cursor").as_deref() == Some("Set up")).expect("Cursor set up"); + + assert_eq!(view.content(), content, "a change to another client rebuilt Zed's page"); + page.imp().port_row.set_value(40_000.0); + wait_until(WAIT, || view.content() != content).expect("a new port shows a new address"); + service.stop(); + runtime.shutdown(); + } + + #[gtk4::test] + fn install_writes_the_client_file_while_the_server_is_off() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let tokens = Arc::new(MemoryTokens::default()); + settings.get().set_mcp_server_port(free_port()).expect("the port"); + let service = McpService::start( + settings.get().clone(), + runtime.tasks(), + tokens.clone(), + context(root.path()), + ); + let page = page_on(&settings, service.clone(), home.path()); + wait_until(WAIT, || subtitle(&page, "Zed").as_deref() == Some("Not set up")).expect("Zed listed"); + + page.install_client("zed"); + + wait_until(WAIT, || subtitle(&page, "Zed").as_deref() == Some("Set up")).expect("Zed set up"); + let written = std::fs::read_to_string(home.path().join(".config/zed/settings.json")).expect("the file"); + let token = tokens + .0 + .lock() + .expect("tokens") + .clone() + .expect("a token kept for the client"); + assert!( + written.contains(&format!("\"Authorization\": \"Bearer {token}\"")), + "{written}" + ); + service.stop(); + runtime.shutdown(); + } + + #[gtk4::test] + fn a_client_page_shows_its_file_a_masked_setup_and_remove() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let service = stopped_service(&settings, &runtime, root.path()); + let page = page_on(&settings, service.clone(), home.path()); + wait_until(WAIT, || { + subtitle(&page, "Cursor").is_some_and(|text| text != "Checking…") + }) + .expect("the survey"); + let host = ClientHost::under(home.path()); + mcp_clients::install(&host, "cursor", &address(page.port()), "Bearer tp_secret").expect("installed"); + page.refresh_clients(); + wait_until(WAIT, || subtitle(&page, "Cursor").as_deref() == Some("Set up")).expect("Cursor set up"); + + let content = page.client_content(&page.state("cursor").expect("Cursor")); + + let labels: Vec = descendants(&content) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .map(|label| label.label().to_string()) + .collect(); + assert!( + labels.iter().any(|text| text.contains(MASKED_AUTHORIZATION)), + "{labels:?}" + ); + assert!( + !labels.iter().any(|text| text.contains("tp_secret")), + "the token is on screen" + ); + assert!(labels.iter().any(|text| text == "~/.cursor/mcp.json"), "{labels:?}"); + let titles: Vec = descendants(&content) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .map(|row| row.title().to_string()) + .collect(); + assert!(titles.contains(&"Remove…".to_owned()), "{titles:?}"); + assert!(!titles.contains(&"Install".to_owned()), "{titles:?}"); + service.stop(); + runtime.shutdown(); + } + + #[gtk4::test] + fn a_client_that_connects_is_announced_once_by_its_catalog_name() { + let settings = MemorySettings::new(); + let page = bound_page(&settings, None); + let toasts = Rc::new(RefCell::new(Vec::::new())); + let sink = toasts.clone(); + page.connect_toast(move |_, toast| { + sink.borrow_mut() + .push(toast.title().map(|title| title.to_string()).unwrap_or_default()); + }); + let seen = |name: &str, second: u64| SeenClient { + name: name.to_owned(), + title: None, + version: "1".to_owned(), + seen_at: SystemTime::UNIX_EPOCH + Duration::from_secs(second), + }; + + page.announce(vec![seen("claude-code", 1)]); + page.announce(vec![seen("claude-code", 1), seen("my-agent", 2)]); + page.announce(vec![seen("my-agent", 2), seen("claude-code", 3)]); + + assert_eq!( + *toasts.borrow(), + [ + "Claude Code just connected", + "my-agent just connected", + "Claude Code just connected" + ] + ); + } + + #[gtk4::test] + fn a_client_turned_off_says_so_and_offers_no_button() { + let settings = MemorySettings::new(); + let runtime = test_runtime(); + let (root, home) = ( + tempfile::tempdir().expect("tempdir"), + tempfile::tempdir().expect("tempdir"), + ); + let service = stopped_service(&settings, &runtime, root.path()); + let kiro = format!( + r#"{{"mcpServers": {{"tablepro": {{"url": "{}", "headers": {{"Authorization": "Bearer tp_x"}}, "disabled": true}}}}}}"#, + address(settings.get().mcp_server_port()) + ); + std::fs::create_dir_all(home.path().join(".kiro/settings")).expect("a folder"); + std::fs::write(home.path().join(".kiro/settings/mcp.json"), kiro).expect("a config"); + + let page = page_on(&settings, service.clone(), home.path()); + + wait_until(WAIT, || { + subtitle(&page, "Kiro").as_deref() == Some("Set up but turned off in the client") + }) + .expect("Kiro read as turned off"); + assert!(!client_row(&page, "kiro").button.is_visible()); + let content = page.client_content(&page.state("kiro").expect("Kiro")); + let descriptions: Vec = descendants(&content) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter_map(|group| group.description().map(|text| text.to_string())) + .collect(); + assert!( + descriptions.iter().any(|text| text.contains("turned off in Kiro")), + "{descriptions:?}" + ); + service.stop(); + runtime.shutdown(); + } + + fn cursor_state(config_path: PathBuf) -> ClientState { + ClientState { + client: mcp_clients::linux_clients() + .find(|client| client.id == "cursor") + .expect("Cursor"), + detected: false, + status: ClientConfigStatus::Current, + config_path: Some(config_path), + action: ClientAction::None, + removable: true, + removes_with_command: false, + } + } + + #[gtk4::test] + fn a_file_path_with_markup_characters_is_shown_as_written() { + let settings = MemorySettings::new(); + let page = bound_page(&settings, None); + + let group = page.manual_group(&cursor_state(PathBuf::from("/srv/Tom & /mcp.json"))); + + let description = group.description().expect("a description"); + let (_, text, _) = gtk4::pango::parse_markup(&description, '\0').expect("valid markup"); + assert_eq!(text.as_str(), "Add this to /srv/Tom & /mcp.json."); + } + + #[gtk4::test] + fn the_remove_dialog_names_the_backup_beside_the_file_a_link_points_to() { + let home = tempfile::tempdir().expect("tempdir"); + let real = home.path().join("dotfiles/mcp.json"); + std::fs::create_dir_all(real.parent().expect("a folder")).expect("a folder"); + std::fs::write(&real, "{}").expect("a config"); + std::fs::create_dir_all(home.path().join(".cursor")).expect("a folder"); + let link = home.path().join(".cursor/mcp.json"); + std::os::unix::fs::symlink(&real, &link).expect("a link"); + + let alert = removal_alert(&cursor_state(link), &ClientHost::under(home.path())); + + let body = alert.body().to_string(); + assert!(body.contains("dotfiles/mcp.json.tablepro-backup"), "{body}"); + assert!(!body.contains(".cursor/mcp.json.tablepro-backup"), "{body}"); + } + + #[test] + fn a_shared_engine_is_named_after_the_client_found_here() { + let codex = mcp_clients::linux_clients() + .find(|client| client.id == "codex") + .expect("Codex CLI"); + let found = ClientState { + client: codex, + detected: true, + status: ClientConfigStatus::NotConfigured, + config_path: None, + action: ClientAction::Install, + removable: false, + removes_with_command: false, + }; + let seen = |name: &str, title: Option<&str>| SeenClient { + name: name.to_owned(), + title: title.map(str::to_owned), + version: "1".to_owned(), + seen_at: SystemTime::UNIX_EPOCH, + }; + + assert_eq!(connected_name(&seen("codex-mcp-client", None), &[found]), "Codex CLI"); + assert_eq!(connected_name(&seen("codex-mcp-client", None), &[]), "ChatGPT"); + assert_eq!(connected_name(&seen("x-agent", Some("X Agent")), &[]), "X Agent"); + } + + #[test] + fn the_copied_header_carries_the_scheme_and_paths_read_from_home() { + assert_eq!(authorization_header("tp_abc"), "Bearer tp_abc"); + assert_eq!( + display_path(Path::new("/home/ana/.cursor/mcp.json"), Path::new("/home/ana")), + "~/.cursor/mcp.json" + ); + assert_eq!( + display_path(Path::new("/etc/x.json"), Path::new("/home/ana")), + "/etc/x.json" + ); + } + + #[test] + fn each_client_status_has_its_own_words() { + let statuses = [ + ClientConfigStatus::NotConfigured, + ClientConfigStatus::Current, + ClientConfigStatus::Disabled, + ClientConfigStatus::Stale(StaleReason::Shadowed), + ClientConfigStatus::Stale(StaleReason::OtherUrl), + ClientConfigStatus::Stale(StaleReason::OtherToken), + ClientConfigStatus::Stale(StaleReason::OtherCommand), + ClientConfigStatus::OtherScope, + ClientConfigStatus::Unreadable, + ClientConfigStatus::Unknown, + ]; + let texts: std::collections::HashSet = statuses.into_iter().map(client_status_text).collect(); + + assert_eq!(texts.len(), statuses.len()); + } + #[test] fn each_failure_has_its_own_sentence() { let failures = [ diff --git a/linux/data/licenses/THIRD-PARTY-NOTICE.md b/linux/data/licenses/THIRD-PARTY-NOTICE.md index 2d36e4c195..f661e4f33d 100644 --- a/linux/data/licenses/THIRD-PARTY-NOTICE.md +++ b/linux/data/licenses/THIRD-PARTY-NOTICE.md @@ -4,6 +4,8 @@ TablePro is licensed under the GNU Affero General Public License, version 3 or l `build-aux/update-third-party-licenses.sh` writes this file from `Cargo.lock`. Do not edit it by hand. +The MCP client marks under `data/resources/icons/scalable/actions` name each client and stay their owners' trademarks. Claude, Claude Code, Cline, Cursor, Google Gemini, JetBrains, LM Studio, OpenCode, Warp, Windsurf and Zed are Simple Icons 16.37.0 files, under CC0-1.0. GitHub Copilot is the Simple Icons copy of Primer Octicons' copilot-24, under MIT, Copyright (c) 2026 GitHub Inc. goose is `documentation/static/img/goose.svg` from github.com/aaif-goose/goose, under Apache-2.0, Copyright 2024 Block, Inc. OpenAI is `client/assets/openai-logomark.svg` from github.com/openai/openai-realtime-console, under MIT, Copyright (c) 2024 OpenAI. Kiro is the icon kiro.dev publishes, and Visual Studio Code the icon in its brand kit at code.visualstudio.com/brand. Each file is used as published. The MIT and Apache 2.0 texts are under License texts. + ## Overview - MIT License (MIT) @@ -8221,6 +8223,7 @@ Used by: - toml_datetime 1.1.1+spec-1.1.0 - toml_edit 0.25.15+spec-1.1.0 - toml_parser 1.1.3+spec-1.1.0 +- toml_writer 1.1.2+spec-1.1.0 ~~~~text Copyright (c) Individual contributors diff --git a/linux/data/licenses/third-party.json b/linux/data/licenses/third-party.json index ea53aecf4a..d99887fce7 100644 --- a/linux/data/licenses/third-party.json +++ b/linux/data/licenses/third-party.json @@ -1284,7 +1284,8 @@ { "crate": { "name": "env_logger", "version": "0.11.11" } }, { "crate": { "name": "toml_datetime", "version": "1.1.1+spec-1.1.0" } }, { "crate": { "name": "toml_edit", "version": "0.25.15+spec-1.1.0" } }, - { "crate": { "name": "toml_parser", "version": "1.1.3+spec-1.1.0" } } + { "crate": { "name": "toml_parser", "version": "1.1.3+spec-1.1.0" } }, + { "crate": { "name": "toml_writer", "version": "1.1.2+spec-1.1.0" } } ] }, { @@ -3107,6 +3108,7 @@ { "name": "toml_datetime", "version": "1.1.1+spec-1.1.0", "license": "MIT OR Apache-2.0" }, { "name": "toml_edit", "version": "0.25.15+spec-1.1.0", "license": "MIT OR Apache-2.0" }, { "name": "toml_parser", "version": "1.1.3+spec-1.1.0", "license": "MIT OR Apache-2.0" }, + { "name": "toml_writer", "version": "1.1.2+spec-1.1.0", "license": "MIT OR Apache-2.0" }, { "name": "tower", "version": "0.5.3", "license": "MIT" }, { "name": "tower-http", "version": "0.6.11", "license": "MIT" }, { "name": "tower-layer", "version": "0.3.3", "license": "MIT" }, diff --git a/linux/data/resources/icons/scalable/actions/claude-symbolic.svg b/linux/data/resources/icons/scalable/actions/claude-symbolic.svg new file mode 100644 index 0000000000..1beee86121 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/claude-symbolic.svg @@ -0,0 +1 @@ +Claude \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/claudecode-symbolic.svg b/linux/data/resources/icons/scalable/actions/claudecode-symbolic.svg new file mode 100644 index 0000000000..9b0061b760 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/claudecode-symbolic.svg @@ -0,0 +1 @@ +Claude Code \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/cline-symbolic.svg b/linux/data/resources/icons/scalable/actions/cline-symbolic.svg new file mode 100644 index 0000000000..0fe6a51fd8 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/cline-symbolic.svg @@ -0,0 +1 @@ +Cline \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/cursor-symbolic.svg b/linux/data/resources/icons/scalable/actions/cursor-symbolic.svg new file mode 100644 index 0000000000..61303fbcc3 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/cursor-symbolic.svg @@ -0,0 +1 @@ +Cursor \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/githubcopilot-symbolic.svg b/linux/data/resources/icons/scalable/actions/githubcopilot-symbolic.svg new file mode 100644 index 0000000000..f064947d1d --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/githubcopilot-symbolic.svg @@ -0,0 +1 @@ +GitHub Copilot \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/googlegemini-symbolic.svg b/linux/data/resources/icons/scalable/actions/googlegemini-symbolic.svg new file mode 100644 index 0000000000..765adb0887 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/googlegemini-symbolic.svg @@ -0,0 +1 @@ +Google Gemini \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/goose.svg b/linux/data/resources/icons/scalable/actions/goose.svg new file mode 100644 index 0000000000..94152e79d3 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/goose.svg @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/linux/data/resources/icons/scalable/actions/jetbrains-symbolic.svg b/linux/data/resources/icons/scalable/actions/jetbrains-symbolic.svg new file mode 100644 index 0000000000..2f669ff6a4 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/jetbrains-symbolic.svg @@ -0,0 +1 @@ +JetBrains \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/kiro.svg b/linux/data/resources/icons/scalable/actions/kiro.svg new file mode 100644 index 0000000000..5fe3cf6847 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/kiro.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/linux/data/resources/icons/scalable/actions/lmstudio-symbolic.svg b/linux/data/resources/icons/scalable/actions/lmstudio-symbolic.svg new file mode 100644 index 0000000000..e324916aaf --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/lmstudio-symbolic.svg @@ -0,0 +1 @@ +LM Studio \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/openai-symbolic.svg b/linux/data/resources/icons/scalable/actions/openai-symbolic.svg new file mode 100644 index 0000000000..e04db75a5b --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/openai-symbolic.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/opencode-symbolic.svg b/linux/data/resources/icons/scalable/actions/opencode-symbolic.svg new file mode 100644 index 0000000000..1e0da06f97 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/opencode-symbolic.svg @@ -0,0 +1 @@ +OpenCode \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/vscode.svg b/linux/data/resources/icons/scalable/actions/vscode.svg new file mode 100644 index 0000000000..c453e633f3 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/vscode.svg @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/linux/data/resources/icons/scalable/actions/warp-symbolic.svg b/linux/data/resources/icons/scalable/actions/warp-symbolic.svg new file mode 100644 index 0000000000..b825120839 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/warp-symbolic.svg @@ -0,0 +1 @@ +Warp \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/windsurf-symbolic.svg b/linux/data/resources/icons/scalable/actions/windsurf-symbolic.svg new file mode 100644 index 0000000000..bb77fc9348 --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/windsurf-symbolic.svg @@ -0,0 +1 @@ +Windsurf \ No newline at end of file diff --git a/linux/data/resources/icons/scalable/actions/zed-symbolic.svg b/linux/data/resources/icons/scalable/actions/zed-symbolic.svg new file mode 100644 index 0000000000..02327fd13b --- /dev/null +++ b/linux/data/resources/icons/scalable/actions/zed-symbolic.svg @@ -0,0 +1 @@ +Zed Industries \ No newline at end of file diff --git a/linux/data/resources/resources.gresource.xml b/linux/data/resources/resources.gresource.xml index bf12eb901c..e49cb383e0 100644 --- a/linux/data/resources/resources.gresource.xml +++ b/linux/data/resources/resources.gresource.xml @@ -54,5 +54,22 @@ icons/scalable/actions/statement-pending-symbolic.svg icons/scalable/actions/document-modified-symbolic.svg icons/scalable/actions/assistant-symbolic.svg + + icons/scalable/actions/claude-symbolic.svg + icons/scalable/actions/claudecode-symbolic.svg + icons/scalable/actions/cline-symbolic.svg + icons/scalable/actions/cursor-symbolic.svg + icons/scalable/actions/githubcopilot-symbolic.svg + icons/scalable/actions/googlegemini-symbolic.svg + icons/scalable/actions/goose.svg + icons/scalable/actions/jetbrains-symbolic.svg + icons/scalable/actions/kiro.svg + icons/scalable/actions/lmstudio-symbolic.svg + icons/scalable/actions/openai-symbolic.svg + icons/scalable/actions/opencode-symbolic.svg + icons/scalable/actions/vscode.svg + icons/scalable/actions/warp-symbolic.svg + icons/scalable/actions/windsurf-symbolic.svg + icons/scalable/actions/zed-symbolic.svg diff --git a/linux/data/resources/ui/preferences-mcp-page.ui b/linux/data/resources/ui/preferences-mcp-page.ui index 3f38172b89..f1d0d1f34d 100644 --- a/linux/data/resources/ui/preferences-mcp-page.ui +++ b/linux/data/resources/ui/preferences-mcp-page.ui @@ -49,7 +49,7 @@ Client Setup - Give a client the address, and the access token to send as a Bearer token in the Authorization header. The token is kept in the keyring. + Give a client the address, and the Authorization header that carries the access token. The token is kept in the keyring. Address @@ -74,14 +74,18 @@ - Access Token + Authorization Header + false + edit-copy-symbolic - Copy Access Token + Copy Authorization Header center - Copy Access Token + Copy Authorization Header