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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
2 changes: 2 additions & 0 deletions apple/.swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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$'
Expand Down
92 changes: 91 additions & 1 deletion apple/Packages/TableProMacCore/Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions apple/Packages/TableProMacCore/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"]),
Expand Down Expand Up @@ -66,6 +67,11 @@ let package = Package(
path: "Sources/TableProMCP",
swiftSettings: appModuleSettings
),
.target(
name: "TableProMCPClients",
path: "Sources/TableProMCPClients",
swiftSettings: appModuleSettings
),
.target(
name: "TableProCommandLine",
dependencies: [
Expand Down Expand Up @@ -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: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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")
Expand Down Expand Up @@ -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.")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ public actor BridgeProxy {
private let hostLines: AsyncStream<Data>
private let logger: any MCPBridgeLogger
private let discovery: BridgeDiscovery
private let instanceId = UUID().uuidString

private var clientInfo: JsonValue?

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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."
}
}
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
}
}
}
Loading
Loading