Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

feat(mcp): add MCP server with hardened SQL write tools

Tobi54af1d96474b
diff --git a/macos/App/DependencyInjection/DependencyContainer.swift b/macos/App/DependencyInjection/DependencyContainer.swift
index ab75b67..638545f 100644
--- a/macos/App/DependencyInjection/DependencyContainer.swift
+++ b/macos/App/DependencyInjection/DependencyContainer.swift
@@ -52,6 +52,36 @@ final class DependencyContainer {
lazy var sshTunnelService = SSHTunnelService()
lazy var exportService = ExportService()
+ // MARK: - MCP Server
+
+ lazy var mcpServer: MCPServer = {
+ MCPServer(
+ connectionManager: connectionManager,
+ connectionRepository: connectionRepository,
+ serverVersion: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0"
+ )
+ }()
+
+ /// Start MCP server if enabled. Call once at app startup.
+ func bootstrapMCPServer() async {
+ let enabled = UserDefaults.standard.bool(forKey: "mcp.enabled")
+ guard enabled else { return }
+
+ // Set start time for uptime tracking
+ let currentStartTime = UserDefaults.standard.double(forKey: "mcp.startTime")
+ if currentStartTime == 0 {
+ UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: "mcp.startTime")
+ }
+
+ // Load MCP modes for all connections
+ let configs = (try? await connectionRepository.fetchAll()) ?? []
+ for config in configs {
+ await mcpServer.setConnectionMode(config.mcpMode, for: config.id)
+ }
+
+ await mcpServer.start()
+ }
+
// MARK: - AI
lazy var providerRegistry = ProviderRegistry()
diff --git a/macos/App/Lifecycle/AppDelegate.swift b/macos/App/Lifecycle/AppDelegate.swift
index c12c46e..48b421b 100644
--- a/macos/App/Lifecycle/AppDelegate.swift
+++ b/macos/App/Lifecycle/AppDelegate.swift
@@ -24,6 +24,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// AIChatView / other callers can resolve them by name without waiting.
Task { await DependencyContainer.shared.bootstrapProviderRegistry() }
+ // Initialize MCP status bar icon
+ _ = MCPStatusBarController.shared
+
+ // Bootstrap MCP server if enabled
+ Task { await DependencyContainer.shared.bootstrapMCPServer() }
+
// Thin scrollbars app-wide; horizontal always visible
UserDefaults.standard.set("Always", forKey: "AppleShowScrollBars")
diff --git a/macos/App/Lifecycle/GridexApp.swift b/macos/App/Lifecycle/GridexApp.swift
index 4466433..250e889 100644
--- a/macos/App/Lifecycle/GridexApp.swift
+++ b/macos/App/Lifecycle/GridexApp.swift
@@ -6,7 +6,6 @@
import SwiftUI
import SwiftData
-@main
struct GridexApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@FocusedObject private var focusedAppState: AppState?
@@ -74,6 +73,13 @@ struct GridexApp: App {
currentAppState?.aiPanelVisible.toggle()
}
.keyboardShortcut("a", modifiers: [.command, .shift])
+
+ Divider()
+
+ Button("MCP Server...") {
+ MCPWindowController.show()
+ }
+ .keyboardShortcut("m", modifiers: [.command, .shift])
}
CommandMenu("Database") {
diff --git a/macos/App/Lifecycle/main.swift b/macos/App/Lifecycle/main.swift
new file mode 100644
index 0000000..34a0c08
--- /dev/null
+++ b/macos/App/Lifecycle/main.swift
@@ -0,0 +1,81 @@
+// main.swift
+// Gridex
+//
+// Application entry point. Supports both GUI and MCP CLI modes.
+
+import SwiftUI
+import SwiftData
+import Dispatch
+
+// Check for MCP CLI mode
+if CommandLine.arguments.contains("--mcp-stdio") {
+ runMCPServer()
+} else {
+ // Run normal GUI app
+ GridexApp.main()
+}
+
+// MARK: - MCP Server Mode
+
+func runMCPServer() -> Never {
+ // Disable buffering for stdio
+ setbuf(stdout, nil)
+ setbuf(stderr, nil)
+
+ // Initialize SwiftData with same schema as main app
+ let schema = Schema([
+ SavedConnectionEntity.self,
+ QueryHistoryEntity.self,
+ LLMProviderEntity.self,
+ ])
+
+ let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
+
+ guard let modelContainer = try? ModelContainer(for: schema, configurations: [config]) else {
+ fputs("Error: Failed to initialize database\n", stderr)
+ exit(1)
+ }
+
+ // Run async server on a detached task (not MainActor-bound).
+ // Main thread must remain free for dispatchMain() to service it.
+ Task.detached {
+ await runMCPServerAsync(modelContainer: modelContainer)
+ }
+
+ // Keep main thread alive; lets Swift concurrency executors run.
+ dispatchMain()
+}
+
+func runMCPServerAsync(modelContainer: ModelContainer) async {
+ // Create services
+ let connectionManager = ConnectionManager()
+ let connectionRepository = SwiftDataConnectionRepository(modelContainer: modelContainer)
+
+ // Create MCP server with stdio transport for CLI mode
+ let mcpServer = MCPServer(
+ connectionManager: connectionManager,
+ connectionRepository: connectionRepository,
+ serverVersion: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0",
+ transportMode: .stdio
+ )
+
+ // Load connections and their MCP modes
+ do {
+ let configs = try await connectionRepository.fetchAll()
+ for config in configs where config.mcpMode != .locked {
+ await mcpServer.setConnectionMode(config.mcpMode, for: config.id)
+ }
+ } catch {
+ fputs("Warning: Failed to load connections: \(error)\n", stderr)
+ }
+
+ // Start server
+ await mcpServer.start()
+
+ // Keep MCPServer alive — if this function returns, the transport's
+ // weak delegate on the server becomes nil and requests stop working.
+ while !Task.isCancelled {
+ try? await Task.sleep(nanoseconds: 1_000_000_000)
+ }
+ _ = mcpServer
+}
diff --git a/macos/Core/Enums/MCPConnectionMode.swift b/macos/Core/Enums/MCPConnectionMode.swift
new file mode 100644
index 0000000..9a908b7
--- /dev/null
+++ b/macos/Core/Enums/MCPConnectionMode.swift
@@ -0,0 +1,39 @@
+// MCPConnectionMode.swift
+// Gridex
+//
+// MCP access mode for database connections.
+
+import Foundation
+
+enum MCPConnectionMode: String, Codable, Sendable, CaseIterable, Identifiable {
+ case locked = "locked"
+ case readOnly = "read_only"
+ case readWrite = "read_write"
+
+ var id: String { rawValue }
+
+ var displayName: String {
+ switch self {
+ case .locked: return "Locked"
+ case .readOnly: return "Read-only"
+ case .readWrite: return "Read-write"
+ }
+ }
+
+ var description: String {
+ switch self {
+ case .locked:
+ return "AI cannot access this connection"
+ case .readOnly:
+ return "AI can query but not modify (recommended for production)"
+ case .readWrite:
+ return "AI can modify with your approval (use for dev only)"
+ }
+ }
+
+ var allowsTier1: Bool { self != .locked }
+ var allowsTier2: Bool { self != .locked }
+ var allowsTier3: Bool { self == .readWrite }
+ var allowsTier4: Bool { self == .readWrite }
+ var allowsTier5: Bool { self != .locked }
+}
diff --git a/macos/Core/Enums/MCPPermissionTier.swift b/macos/Core/Enums/MCPPermissionTier.swift
new file mode 100644
index 0000000..2430d89
--- /dev/null
+++ b/macos/Core/Enums/MCPPermissionTier.swift
@@ -0,0 +1,39 @@
+// MCPPermissionTier.swift
+// Gridex
+//
+// Permission tiers for MCP tools.
+
+import Foundation
+
+enum MCPPermissionTier: Int, Codable, Sendable, Comparable {
+ case schema = 1 // Tier 1: Schema introspection (read-only, no approval)
+ case read = 2 // Tier 2: Query execution (read, no approval by default)
+ case write = 3 // Tier 3: Data modification (write, REQUIRES approval)
+ case ddl = 4 // Tier 4: DDL (schema change, CRITICAL approval)
+ case advanced = 5 // Tier 5: Advanced features
+
+ static func < (lhs: MCPPermissionTier, rhs: MCPPermissionTier) -> Bool {
+ lhs.rawValue < rhs.rawValue
+ }
+
+ var displayName: String {
+ switch self {
+ case .schema: return "Schema"
+ case .read: return "Read"
+ case .write: return "Write"
+ case .ddl: return "DDL"
+ case .advanced: return "Advanced"
+ }
+ }
+
+ var requiresApproval: Bool {
+ switch self {
+ case .schema, .read: return false
+ case .write, .ddl, .advanced: return true
+ }
+ }
+
+ var isReadOnly: Bool {
+ self == .schema || self == .read
+ }
+}
diff --git a/macos/Core/Enums/SQLDialect.swift b/macos/Core/Enums/SQLDialect.swift
index 54dd2e3..0a2224e 100644
--- a/macos/Core/Enums/SQLDialect.swift
+++ b/macos/Core/Enums/SQLDialect.swift
@@ -24,6 +24,11 @@ enum SQLDialect: Sendable {
}
}
+ func qualifiedIdentifier(_ name: String, schema: String? = nil) -> String {
+ guard let schema else { return quoteIdentifier(name) }
+ return "\(quoteIdentifier(schema)).\(quoteIdentifier(name))"
+ }
+
var limitClause: String {
"LIMIT"
}
diff --git a/macos/Core/Models/Database/ConnectionConfig.swift b/macos/Core/Models/Database/ConnectionConfig.swift
index 578e4a3..9907905 100644
--- a/macos/Core/Models/Database/ConnectionConfig.swift
+++ b/macos/Core/Models/Database/ConnectionConfig.swift
@@ -28,6 +28,9 @@ struct ConnectionConfig: Codable, Sendable, Hashable, Identifiable {
// SSH Tunnel
var sshConfig: SSHTunnelConfig?
+ // MCP Access
+ var mcpMode: MCPConnectionMode
+
init(
id: UUID = UUID(),
name: String,
@@ -43,7 +46,8 @@ struct ConnectionConfig: Codable, Sendable, Hashable, Identifiable {
sslCertPath: String? = nil,
sslCACertPath: String? = nil,
filePath: String? = nil,
- sshConfig: SSHTunnelConfig? = nil
+ sshConfig: SSHTunnelConfig? = nil,
+ mcpMode: MCPConnectionMode = .locked
) {
self.id = id
self.name = name
@@ -60,6 +64,7 @@ struct ConnectionConfig: Codable, Sendable, Hashable, Identifiable {
self.sslCACertPath = sslCACertPath
self.filePath = filePath
self.sshConfig = sshConfig
+ self.mcpMode = mcpMode
}
var displayHost: String {
diff --git a/macos/Core/Models/MCP/MCPAuditEntry.swift b/macos/Core/Models/MCP/MCPAuditEntry.swift
new file mode 100644
index 0000000..0270788
--- /dev/null
+++ b/macos/Core/Models/MCP/MCPAuditEntry.swift
@@ -0,0 +1,110 @@
+// MCPAuditEntry.swift
+// Gridex
+//
+// Audit log entry for MCP tool invocations.
+
+import Foundation
+
+struct MCPAuditEntry: Codable, Sendable, Identifiable {
+ var id: UUID { eventId }
+ let timestamp: Date
+ let eventId: UUID
+ let client: MCPAuditClient
+ let tool: String
+ let tier: Int
+ let connectionId: UUID?
+ let connectionType: String?
+ let input: MCPAuditInput
+ let result: MCPAuditResult
+ let security: MCPAuditSecurity
+ let error: String?
+
+ init(
+ tool: String,
+ tier: MCPPermissionTier,
+ connectionId: UUID?,
+ connectionType: DatabaseType?,
+ client: MCPAuditClient,
+ input: MCPAuditInput,
+ result: MCPAuditResult,
+ security: MCPAuditSecurity,
+ error: String? = nil
+ ) {
+ self.timestamp = Date()
+ self.eventId = UUID()
+ self.client = client
+ self.tool = tool
+ self.tier = tier.rawValue
+ self.connectionId = connectionId
+ self.connectionType = connectionType?.rawValue
+ self.input = input
+ self.result = result
+ self.security = security
+ self.error = error
+ }
+}
+
+struct MCPAuditClient: Codable, Sendable {
+ let name: String
+ let version: String
+ let transport: String
+
+ static let unknown = MCPAuditClient(name: "unknown", version: "0.0.0", transport: "stdio")
+}
+
+struct MCPAuditInput: Codable, Sendable {
+ let sqlPreview: String?
+ let paramsCount: Int?
+ let inputHash: String?
+
+ init(sql: String? = nil, paramsCount: Int? = nil) {
+ if let sql {
+ let truncated = sql.count > 200 ? String(sql.prefix(200)) + "..." : sql
+ self.sqlPreview = truncated
+ self.inputHash = "sha256:\(sql.hashValue)"
+ } else {
+ self.sqlPreview = nil
+ self.inputHash = nil
+ }
+ self.paramsCount = paramsCount
+ }
+
+ static let empty = MCPAuditInput()
+}
+
+struct MCPAuditResult: Codable, Sendable {
+ let status: String
+ let rowsAffected: Int?
+ let rowsReturned: Int?
+ let durationMs: Int
+ let bytesReturned: Int?
+
+ init(status: MCPAuditStatus, rowsAffected: Int? = nil, rowsReturned: Int? = nil, durationMs: Int, bytesReturned: Int? = nil) {
+ self.status = status.rawValue
+ self.rowsAffected = rowsAffected
+ self.rowsReturned = rowsReturned
+ self.durationMs = durationMs
+ self.bytesReturned = bytesReturned
+ }
+}
+
+enum MCPAuditStatus: String, Codable, Sendable {
+ case success
+ case error
+ case denied
+ case timeout
+}
+
+struct MCPAuditSecurity: Codable, Sendable {
+ let permissionMode: String
+ let userApproved: Bool?
+ let approvalSessionId: UUID?
+ let scopesApplied: [String]?
+
+ init(mode: MCPConnectionMode, userApproved: Bool? = nil, approvalSessionId: UUID? = nil, scopesApplied: [String]? = nil) {
+ self.permissionMode = mode.rawValue
+ self.userApproved = userApproved
+ self.approvalSessionId = approvalSessionId
+ self.scopesApplied = scopesApplied
+ }
+}
diff --git a/macos/Core/Models/MCP/MCPProtocol.swift b/macos/Core/Models/MCP/MCPProtocol.swift
new file mode 100644
index 0000000..ff39c2c
--- /dev/null
+++ b/macos/Core/Models/MCP/MCPProtocol.swift
@@ -0,0 +1,299 @@
+// MCPProtocol.swift
+// Gridex
+//
+// MCP (Model Context Protocol) JSON-RPC 2.0 types.
+
+import Foundation
+
+// MARK: - JSON-RPC 2.0 Base Types
+
+struct JSONRPCRequest: Codable, Sendable {
+ let jsonrpc: String
+ let id: JSONRPCId?
+ let method: String
+ let params: JSONValue?
+
+ init(id: JSONRPCId? = nil, method: String, params: JSONValue? = nil) {
+ self.jsonrpc = "2.0"
+ self.id = id
+ self.method = method
+ self.params = params
+ }
+}
+
+struct JSONRPCResponse: Codable, Sendable {
+ let jsonrpc: String
+ let id: JSONRPCId?
+ let result: JSONValue?
+ let error: JSONRPCError?
+
+ init(id: JSONRPCId?, result: JSONValue) {
+ self.jsonrpc = "2.0"
+ self.id = id
+ self.result = result
+ self.error = nil
+ }
+
+ init(id: JSONRPCId?, error: JSONRPCError) {
+ self.jsonrpc = "2.0"
+ self.id = id
+ self.result = nil
+ self.error = error
+ }
+}
+
+struct JSONRPCError: Codable, Sendable {
+ let code: Int
+ let message: String
+ let data: JSONValue?
+
+ init(code: Int, message: String, data: JSONValue? = nil) {
+ self.code = code
+ self.message = message
+ self.data = data
+ }
+
+ static let parseError = JSONRPCError(code: -32700, message: "Parse error")
+ static let invalidRequest = JSONRPCError(code: -32600, message: "Invalid Request")
+ static let methodNotFound = JSONRPCError(code: -32601, message: "Method not found")
+ static let invalidParams = JSONRPCError(code: -32602, message: "Invalid params")
+ static let internalError = JSONRPCError(code: -32603, message: "Internal error")
+}
+
+enum JSONRPCId: Codable, Sendable, Hashable {
+ case string(String)
+ case int(Int)
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if let intVal = try? container.decode(Int.self) {
+ self = .int(intVal)
+ } else if let strVal = try? container.decode(String.self) {
+ self = .string(strVal)
+ } else {
+ throw DecodingError.typeMismatch(
+ JSONRPCId.self,
+ DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Expected string or int")
+ )
+ }
+ }
+
+ func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .string(let s): try container.encode(s)
+ case .int(let i): try container.encode(i)
+ }
+ }
+}
+
+// MARK: - JSON Value (Dynamic)
+
+indirect enum JSONValue: Codable, Sendable, Hashable {
+ case null
+ case bool(Bool)
+ case int(Int)
+ case double(Double)
+ case string(String)
+ case array([JSONValue])
+ case object([String: JSONValue])
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if container.decodeNil() {
+ self = .null
+ } else if let b = try? container.decode(Bool.self) {
+ self = .bool(b)
+ } else if let i = try? container.decode(Int.self) {
+ self = .int(i)
+ } else if let d = try? container.decode(Double.self) {
+ self = .double(d)
+ } else if let s = try? container.decode(String.self) {
+ self = .string(s)
+ } else if let arr = try? container.decode([JSONValue].self) {
+ self = .array(arr)
+ } else if let obj = try? container.decode([String: JSONValue].self) {
+ self = .object(obj)
+ } else {
+ throw DecodingError.typeMismatch(
+ JSONValue.self,
+ DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Unknown JSON type")
+ )
+ }
+ }
+
+ func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .null: try container.encodeNil()
+ case .bool(let b): try container.encode(b)
+ case .int(let i): try container.encode(i)
+ case .double(let d): try container.encode(d)
+ case .string(let s): try container.encode(s)
+ case .array(let arr): try container.encode(arr)
+ case .object(let obj): try container.encode(obj)
+ }
+ }
+
+ subscript(key: String) -> JSONValue? {
+ if case .object(let obj) = self { return obj[key] }
+ return nil
+ }
+
+ subscript(index: Int) -> JSONValue? {
+ if case .array(let arr) = self, index < arr.count { return arr[index] }
+ return nil
+ }
+
+ var stringValue: String? {
+ if case .string(let s) = self { return s }
+ return nil
+ }
+
+ var intValue: Int? {
+ if case .int(let i) = self { return i }
+ return nil
+ }
+
+ var boolValue: Bool? {
+ if case .bool(let b) = self { return b }
+ return nil
+ }
+
+ var arrayValue: [JSONValue]? {
+ if case .array(let a) = self { return a }
+ return nil
+ }
+
+ var objectValue: [String: JSONValue]? {
+ if case .object(let o) = self { return o }
+ return nil
+ }
+}
+
+// MARK: - MCP Server Info
+
+struct MCPServerInfo: Codable, Sendable {
+ let name: String
+ let version: String
+ let protocolVersion: String
+ let capabilities: MCPCapabilities
+
+ static func gridex(version: String) -> MCPServerInfo {
+ MCPServerInfo(
+ name: "gridex",
+ version: version,
+ protocolVersion: "2024-11-05",
+ capabilities: MCPCapabilities(
+ tools: MCPToolsCapability(listChanged: true),
+ resources: MCPResourcesCapability(subscribe: true, listChanged: true),
+ prompts: MCPPromptsCapability(listChanged: true),
+ logging: MCPLoggingCapability()
+ )
+ )
+ }
+}
+
+struct MCPCapabilities: Codable, Sendable {
+ let tools: MCPToolsCapability?
+ let resources: MCPResourcesCapability?
+ let prompts: MCPPromptsCapability?
+ let logging: MCPLoggingCapability?
+}
+
+struct MCPToolsCapability: Codable, Sendable {
+ let listChanged: Bool?
+}
+
+struct MCPResourcesCapability: Codable, Sendable {
+ let subscribe: Bool?
+ let listChanged: Bool?
+}
+
+struct MCPPromptsCapability: Codable, Sendable {
+ let listChanged: Bool?
+}
+
+struct MCPLoggingCapability: Codable, Sendable {}
+
+// MARK: - MCP Tool Definition
+
+struct MCPToolDefinition: Codable, Sendable {
+ let name: String
+ let description: String
+ let inputSchema: JSONValue
+
+ init(name: String, description: String, inputSchema: [String: Any]) {
+ self.name = name
+ self.description = description
+ self.inputSchema = Self.convertToJSONValue(inputSchema)
+ }
+
+ private static func convertToJSONValue(_ value: Any) -> JSONValue {
+ switch value {
+ case let b as Bool: return .bool(b)
+ case let i as Int: return .int(i)
+ case let d as Double: return .double(d)
+ case let s as String: return .string(s)
+ case let arr as [Any]: return .array(arr.map { convertToJSONValue($0) })
+ case let dict as [String: Any]: return .object(dict.mapValues { convertToJSONValue($0) })
+ default: return .null
+ }
+ }
+}
+
+// MARK: - MCP Tool Result
+
+struct MCPToolResult: Codable, Sendable {
+ let content: [MCPContent]
+ let isError: Bool?
+
+ init(text: String, isError: Bool = false) {
+ self.content = [MCPContent(type: "text", text: text)]
+ self.isError = isError ? true : nil
+ }
+
+ init(content: [MCPContent], isError: Bool = false) {
+ self.content = content
+ self.isError = isError ? true : nil
+ }
+
+ static func error(_ message: String) -> MCPToolResult {
+ MCPToolResult(text: message, isError: true)
+ }
+}
+
+struct MCPContent: Codable, Sendable {
+ let type: String
+ let text: String?
+ let data: String?
+ let mimeType: String?
+
+ init(type: String, text: String? = nil, data: String? = nil, mimeType: String? = nil) {
+ self.type = type
+ self.text = text
+ self.data = data
+ self.mimeType = mimeType
+ }
+}
+
+// MARK: - MCP Client Info
+
+struct MCPClientInfo: Codable, Sendable {
+ let name: String
+ let version: String
+}
+
+// MARK: - MCP Error Codes
+
+enum MCPErrorCode: Int, Sendable {
+ case permissionDenied = -32001
+ case approvalTimeout = -32002
+ case approvalDenied = -32003
+ case connectionError = -32004
+ case syntaxError = -32005
+ case notFound = -32006
+ case rateLimitExceeded = -32007
+ case scopeDenied = -32008
+ case queryTimeout = -32009
+}
diff --git a/macos/Data/Persistence/Models/SavedConnectionEntity.swift b/macos/Data/Persistence/Models/SavedConnectionEntity.swift
index f7c1c68..be57936 100644
--- a/macos/Data/Persistence/Models/SavedConnectionEntity.swift
+++ b/macos/Data/Persistence/Models/SavedConnectionEntity.swift
@@ -28,6 +28,7 @@ final class SavedConnectionEntity {
var lastConnectedAt: Date?
var createdAt: Date
var filePath: String?
+ var mcpMode: String?
init(
id: UUID = UUID(),
@@ -49,7 +50,8 @@ final class SavedConnectionEntity {
sortOrder: Int = 0,
lastConnectedAt: Date? = nil,
createdAt: Date = Date(),
- filePath: String? = nil
+ filePath: String? = nil,
+ mcpMode: String? = nil
) {
self.id = id
self.name = name
@@ -71,6 +73,7 @@ final class SavedConnectionEntity {
self.lastConnectedAt = lastConnectedAt
self.createdAt = createdAt
self.filePath = filePath
+ self.mcpMode = mcpMode
}
func toConfig() -> ConnectionConfig {
@@ -97,7 +100,8 @@ final class SavedConnectionEntity {
colorTag: colorTag.flatMap { ColorTag(rawValue: $0) },
group: group,
filePath: filePath,
- sshConfig: sshConfig
+ sshConfig: sshConfig,
+ mcpMode: mcpMode.flatMap { MCPConnectionMode(rawValue: $0) } ?? .locked
)
}
}
diff --git a/macos/Data/Persistence/Repositories/SwiftDataConnectionRepository.swift b/macos/Data/Persistence/Repositories/SwiftDataConnectionRepository.swift
index cfd7e65..7a91be5 100644
--- a/macos/Data/Persistence/Repositories/SwiftDataConnectionRepository.swift
+++ b/macos/Data/Persistence/Repositories/SwiftDataConnectionRepository.swift
@@ -63,7 +63,8 @@ final class SwiftDataConnectionRepository: ConnectionRepository, @unchecked Send
sshKeyPath: config.sshConfig?.keyPath,
colorTag: config.colorTag?.rawValue,
group: config.group,
- filePath: config.filePath
+ filePath: config.filePath,
+ mcpMode: config.mcpMode.rawValue
)
context.insert(entity)
try context.save()
@@ -95,6 +96,7 @@ final class SwiftDataConnectionRepository: ConnectionRepository, @unchecked Send
entity.sshUsername = config.sshConfig?.username
entity.sshAuthMethod = config.sshConfig?.authMethod.rawValue
entity.sshKeyPath = config.sshConfig?.keyPath
+ entity.mcpMode = config.mcpMode.rawValue
try context.save()
}
diff --git a/macos/Presentation/Windows/MCP/MCPActivityView.swift b/macos/Presentation/Windows/MCP/MCPActivityView.swift
new file mode 100644
index 0000000..f66f735
--- /dev/null
+++ b/macos/Presentation/Windows/MCP/MCPActivityView.swift
@@ -0,0 +1,311 @@
+// MCPActivityView.swift
+// Gridex
+//
+// MCP audit log and activity viewer.
+
+import SwiftUI
+
+struct MCPActivityView: View {
+ @ObservedObject var state: MCPWindowState
+
+ @State private var selectedEntryId: UUID?
+ @State private var filterTool: String? = nil
+ @State private var filterStatus: MCPAuditStatus? = nil
+ @State private var searchText = ""
+ @State private var sortOrder: [KeyPathComparator<MCPAuditEntry>] = [
+ KeyPathComparator(\.timestamp, order: .reverse)
+ ]
+
+ private var selectedEntry: MCPAuditEntry? {
+ guard let id = selectedEntryId else { return nil }
+ return state.fullActivity.first { $0.id == id }
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ filterBar
+ Divider()
+ HSplitView {
+ tableSection
+ .frame(minWidth: 440)
+
+ if let entry = selectedEntry {
+ detailPanel(entry)
+ .frame(minWidth: 280, idealWidth: 340, maxWidth: 420)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .task {
+ await state.loadFullActivity()
+ }
+ }
+
+ // MARK: - Filter Bar
+
+ private var filterBar: some View {
+ HStack(spacing: 10) {
+ HStack(spacing: 6) {
+ Image(systemName: "magnifyingglass")
+ .foregroundStyle(.secondary)
+ .font(.callout)
+ TextField("Search tool, SQL, or client", text: $searchText)
+ .textFieldStyle(.plain)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 5)
+ .background(Color(nsColor: .controlBackgroundColor))
+ .overlay(
+ RoundedRectangle(cornerRadius: 6)
+ .stroke(Color.gray.opacity(0.2), lineWidth: 1)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ .frame(maxWidth: 260)
+
+ Picker("Tool", selection: $filterTool) {
+ Text("All Tools").tag(nil as String?)
+ Divider()
+ ForEach(uniqueTools, id: \.self) { tool in
+ Text(tool).tag(tool as String?)
+ }
+ }
+ .labelsHidden()
+ .frame(width: 140)
+
+ Picker("Status", selection: $filterStatus) {
+ Text("All Status").tag(nil as MCPAuditStatus?)
+ Divider()
+ Text("Success").tag(MCPAuditStatus.success as MCPAuditStatus?)
+ Text("Error").tag(MCPAuditStatus.error as MCPAuditStatus?)
+ Text("Denied").tag(MCPAuditStatus.denied as MCPAuditStatus?)
+ }
+ .labelsHidden()
+ .frame(width: 120)
+
+ Spacer()
+
+ Button {
+ Task { await state.loadFullActivity(force: true) }
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ }
+ .help("Refresh")
+
+ Menu {
+ Button("Export as JSON…") { exportLog() }
+ Divider()
+ Button("Clear Log…", role: .destructive) { clearLog() }
+ } label: {
+ Image(systemName: "ellipsis.circle")
+ }
+ .menuStyle(.borderlessButton)
+ .fixedSize()
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ }
+
+ // MARK: - Table
+
+ @ViewBuilder
+ private var tableSection: some View {
+ if state.isLoadingActivity && state.fullActivity.isEmpty {
+ ProgressView()
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else if filteredEntries.isEmpty {
+ ContentUnavailableView(
+ "No Activity",
+ systemImage: "waveform.path.ecg",
+ description: Text("MCP tool invocations will appear here.")
+ )
+ } else {
+ Table(filteredEntries, selection: $selectedEntryId, sortOrder: $sortOrder) {
+ TableColumn("Time", value: \.timestamp) { entry in
+ Text(formatTime(entry.timestamp))
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.secondary)
+ }
+ .width(min: 70, ideal: 80)
+
+ TableColumn("Tool", value: \.tool) { entry in
+ HStack(spacing: 6) {
+ Circle()
+ .fill(colorForTier(entry.tier))
+ .frame(width: 6, height: 6)
+ Text(entry.tool)
+ .font(.system(.caption, design: .monospaced))
+ }
+ }
+ .width(min: 120, ideal: 160)
+
+ TableColumn("Client") { entry in
+ Text(entry.client.name)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .width(min: 80, ideal: 100)
+
+ TableColumn("Status") { entry in
+ let status = MCPAuditStatus(rawValue: entry.result.status) ?? .success
+ Text(status.rawValue)
+ .font(.caption)
+ .foregroundStyle(colorForStatus(status))
+ }
+ .width(60)
+
+ TableColumn("Duration") { entry in
+ Text("\(entry.result.durationMs)ms")
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .monospacedDigit()
+ }
+ .width(70)
+ }
+ .tableStyle(.inset(alternatesRowBackgrounds: true))
+ }
+ }
+
+ // MARK: - Detail
+
+ private func detailPanel(_ entry: MCPAuditEntry) -> some View {
+ Form {
+ Section("Event") {
+ LabeledContent("Tool", value: entry.tool)
+ LabeledContent("Tier", value: "Tier \(entry.tier)")
+ LabeledContent("Time", value: formatFullTime(entry.timestamp))
+ LabeledContent("Event ID") {
+ Text(entry.eventId.uuidString.prefix(8) + "…")
+ .font(.system(.caption, design: .monospaced))
+ .textSelection(.enabled)
+ }
+ }
+
+ Section("Client") {
+ LabeledContent("Name", value: entry.client.name)
+ LabeledContent("Version", value: entry.client.version)
+ LabeledContent("Transport", value: entry.client.transport)
+ }
+
+ if entry.connectionId != nil || entry.connectionType != nil {
+ Section("Connection") {
+ if let connType = entry.connectionType {
+ LabeledContent("Database", value: connType)
+ }
+ if let connId = entry.connectionId {
+ LabeledContent("ID") {
+ Text(connId.uuidString.prefix(8) + "…")
+ .font(.system(.caption, design: .monospaced))
+ .textSelection(.enabled)
+ }
+ }
+ }
+ }
+
+ Section("Result") {
+ LabeledContent("Status") {
+ let status = MCPAuditStatus(rawValue: entry.result.status) ?? .success
+ Text(status.rawValue.capitalized)
+ .foregroundStyle(colorForStatus(status))
+ }
+ LabeledContent("Duration", value: "\(entry.result.durationMs)ms")
+ if let rows = entry.result.rowsReturned {
+ LabeledContent("Rows returned", value: "\(rows)")
+ }
+ if let affected = entry.result.rowsAffected {
+ LabeledContent("Rows affected", value: "\(affected)")
+ }
+ }
+
+ if let sql = entry.input.sqlPreview {
+ Section("SQL") {
+ Text(sql)
+ .font(.system(.caption, design: .monospaced))
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(8)
+ .background(Color(nsColor: .textBackgroundColor))
+ .clipShape(RoundedRectangle(cornerRadius: 4))
+ }
+ }
+
+ if let error = entry.error {
+ Section("Error") {
+ Text(error)
+ .font(.caption)
+ .foregroundStyle(.red)
+ .textSelection(.enabled)
+ }
+ }
+ }
+ .formStyle(.grouped)
+ }
+
+ // MARK: - Helpers
+
+ private var filteredEntries: [MCPAuditEntry] {
+ var result = state.fullActivity
+
+ if let tool = filterTool {
+ result = result.filter { $0.tool == tool }
+ }
+
+ if let status = filterStatus {
+ result = result.filter { $0.result.status == status.rawValue }
+ }
+
+ if !searchText.isEmpty {
+ result = result.filter {
+ $0.tool.localizedCaseInsensitiveContains(searchText) ||
+ $0.client.name.localizedCaseInsensitiveContains(searchText) ||
+ ($0.input.sqlPreview?.localizedCaseInsensitiveContains(searchText) ?? false)
+ }
+ }
+
+ return result.sorted(using: sortOrder)
+ }
+
+ private var uniqueTools: [String] {
+ Array(Set(state.fullActivity.map(\.tool))).sorted()
+ }
+
+ private func exportLog() {
+ // TODO: Implement export
+ }
+
+ private func clearLog() {
+ // TODO: Implement clear with confirmation
+ }
+
+ private func formatTime(_ date: Date) -> String {
+ let formatter = DateFormatter()
+ formatter.dateFormat = "HH:mm:ss"
+ return formatter.string(from: date)
+ }
+
+ private func formatFullTime(_ date: Date) -> String {
+ let formatter = DateFormatter()
+ formatter.dateStyle = .medium
+ formatter.timeStyle = .medium
+ return formatter.string(from: date)
+ }
+
+ private func colorForTier(_ tier: Int) -> Color {
+ switch tier {
+ case 1: return .blue
+ case 2: return .green
+ case 3: return .orange
+ case 4: return .red
+ case 5: return .purple
+ default: return .gray
+ }
+ }
+
+ private func colorForStatus(_ status: MCPAuditStatus) -> Color {
+ switch status {
+ case .success: return .green
+ case .error: return .red
+ case .denied: return .orange
+ case .timeout: return .yellow
+ }
+ }
+}
diff --git a/macos/Presentation/Windows/MCP/MCPAdvancedView.swift b/macos/Presentation/Windows/MCP/MCPAdvancedView.swift
new file mode 100644
index 0000000..e50243a
--- /dev/null
+++ b/macos/Presentation/Windows/MCP/MCPAdvancedView.swift
@@ -0,0 +1,149 @@
+// MCPAdvancedView.swift
+// Gridex
+//
+// Advanced MCP server settings.
+
+import SwiftUI
+
+struct MCPAdvancedView: View {
+ // Rate limiting
+ @AppStorage("mcp.rateLimit.queriesPerMinute") private var queriesPerMinute = 60
+ @AppStorage("mcp.rateLimit.queriesPerHour") private var queriesPerHour = 1000
+ @AppStorage("mcp.rateLimit.writesPerMinute") private var writesPerMinute = 10
+ @AppStorage("mcp.rateLimit.ddlPerMinute") private var ddlPerMinute = 1
+
+ // Timeouts
+ @AppStorage("mcp.timeout.query") private var queryTimeout = 30
+ @AppStorage("mcp.timeout.approval") private var approvalTimeout = 60
+ @AppStorage("mcp.timeout.connection") private var connectionTimeout = 10
+
+ // Audit log
+ @AppStorage("mcp.audit.retentionDays") private var retentionDays = 90
+ @AppStorage("mcp.audit.maxSizeMB") private var maxSizeMB = 100
+
+ // Security
+ @AppStorage("mcp.security.requireApprovalForWrites") private var requireApprovalForWrites = true
+ @AppStorage("mcp.security.allowRemoteHTTP") private var allowRemoteHTTP = false
+
+ @State private var showResetConfirmation = false
+
+ var body: some View {
+ Form {
+ Section("Rate Limits") {
+ stepper("Queries per minute", value: $queriesPerMinute, in: 10...200, step: 10)
+ stepper("Queries per hour", value: $queriesPerHour, in: 100...5000, step: 100)
+ stepper("Writes per minute", value: $writesPerMinute, in: 1...50, step: 1)
+ stepper("DDL per minute", value: $ddlPerMinute, in: 1...10, step: 1)
+ }
+
+ Section("Timeouts") {
+ stepper("Query timeout", value: $queryTimeout, in: 5...300, step: 5, suffix: "s")
+ stepper("Approval timeout", value: $approvalTimeout, in: 10...300, step: 10, suffix: "s")
+ stepper("Connection timeout", value: $connectionTimeout, in: 5...60, step: 5, suffix: "s")
+ }
+
+ Section("Audit Log") {
+ LabeledContent("Retention") {
+ Picker("", selection: $retentionDays) {
+ Text("7 days").tag(7)
+ Text("30 days").tag(30)
+ Text("90 days").tag(90)
+ Text("1 year").tag(365)
+ Text("Forever").tag(0)
+ }
+ .labelsHidden()
+ .frame(width: 130)
+ }
+
+ stepper("Max log size", value: $maxSizeMB, in: 10...500, step: 10, suffix: "MB")
+
+ LabeledContent("Location") {
+ HStack(spacing: 6) {
+ Text("~/Library/Application Support/Gridex/")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ .lineLimit(1)
+ .truncationMode(.middle)
+
+ Button {
+ openLogFolder()
+ } label: {
+ Image(systemName: "folder")
+ }
+ .buttonStyle(.borderless)
+ .help("Open in Finder")
+ }
+ }
+ }
+
+ Section("Security") {
+ Toggle("Require approval for write operations", isOn: $requireApprovalForWrites)
+
+ Toggle("Allow remote HTTP connections", isOn: $allowRemoteHTTP)
+
+ if allowRemoteHTTP {
+ HStack(alignment: .top, spacing: 8) {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundStyle(.orange)
+ .font(.caption)
+ Text("Remote HTTP allows connections from other machines. Use only on trusted networks.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ Section {
+ HStack {
+ Spacer()
+ Button("Reset to Defaults…") {
+ showResetConfirmation = true
+ }
+ }
+ }
+ }
+ .formStyle(.grouped)
+ .alert("Reset All Settings?", isPresented: $showResetConfirmation) {
+ Button("Cancel", role: .cancel) {}
+ Button("Reset", role: .destructive) { resetToDefaults() }
+ } message: {
+ Text("This will restore all MCP settings to their default values.")
+ }
+ }
+
+ private func stepper(_ title: String, value: Binding<Int>, in range: ClosedRange<Int>, step: Int, suffix: String = "") -> some View {
+ LabeledContent(title) {
+ HStack(spacing: 4) {
+ Text("\(value.wrappedValue)\(suffix)")
+ .font(.system(.body, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .monospacedDigit()
+ .frame(minWidth: 60, alignment: .trailing)
+
+ Stepper("", value: value, in: range, step: step)
+ .labelsHidden()
+ }
+ }
+ }
+
+ private func openLogFolder() {
+ let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
+ let gridexDir = appSupport.appendingPathComponent("Gridex")
+ NSWorkspace.shared.open(gridexDir)
+ }
+
+ private func resetToDefaults() {
+ queriesPerMinute = 60
+ queriesPerHour = 1000
+ writesPerMinute = 10
+ ddlPerMinute = 1
+ queryTimeout = 30
+ approvalTimeout = 60
+ connectionTimeout = 10
+ retentionDays = 90
+ maxSizeMB = 100
+ requireApprovalForWrites = true
+ allowRemoteHTTP = false
+ }
+}
diff --git a/macos/Presentation/Windows/MCP/MCPConnectionsView.swift b/macos/Presentation/Windows/MCP/MCPConnectionsView.swift
new file mode 100644
index 0000000..652e7bc
--- /dev/null
+++ b/macos/Presentation/Windows/MCP/MCPConnectionsView.swift
@@ -0,0 +1,171 @@
+// MCPConnectionsView.swift
+// Gridex
+//
+// MCP connection access management.
+
+import SwiftUI
+
+struct MCPConnectionsView: View {
+ @ObservedObject var state: MCPWindowState
+
+ @State private var searchText = ""
+ @State private var filterMode: MCPConnectionMode? = nil
+ @State private var selection: UUID?
+ @State private var sortOrder: [KeyPathComparator<ConnectionConfig>] = [
+ KeyPathComparator(\.name)
+ ]
+
+ var body: some View {
+ VStack(spacing: 0) {
+ filterBar
+ Divider()
+ contentBody
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ // MARK: - Filter bar
+
+ private var filterBar: some View {
+ HStack(spacing: 10) {
+ HStack(spacing: 6) {
+ Image(systemName: "magnifyingglass")
+ .foregroundStyle(.secondary)
+ .font(.callout)
+ TextField("Search connections", text: $searchText)
+ .textFieldStyle(.plain)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 5)
+ .background(Color(nsColor: .controlBackgroundColor))
+ .overlay(
+ RoundedRectangle(cornerRadius: 6)
+ .stroke(Color.gray.opacity(0.2), lineWidth: 1)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ .frame(maxWidth: 280)
+
+ Picker("Filter", selection: $filterMode) {
+ Text("All Access").tag(nil as MCPConnectionMode?)
+ Divider()
+ ForEach(MCPConnectionMode.allCases) { mode in
+ Text(mode.displayName).tag(mode as MCPConnectionMode?)
+ }
+ }
+ .labelsHidden()
+ .frame(width: 140)
+
+ Spacer()
+
+ Text("\(filteredConnections.count) of \(state.connections.count)")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ }
+
+ // MARK: - Content
+
+ @ViewBuilder
+ private var contentBody: some View {
+ if filteredConnections.isEmpty {
+ ContentUnavailableView(
+ searchText.isEmpty && filterMode == nil ? "No Connections" : "No Results",
+ systemImage: searchText.isEmpty && filterMode == nil
+ ? "externaldrive.badge.questionmark"
+ : "magnifyingglass",
+ description: Text(
+ searchText.isEmpty && filterMode == nil
+ ? "Add a database connection in Gridex to enable MCP access."
+ : "Try a different search or filter."
+ )
+ )
+ } else {
+ connectionsTable
+ }
+ }
+
+ private var connectionsTable: some View {
+ Table(filteredConnections, selection: $selection, sortOrder: $sortOrder) {
+ TableColumn("") { config in
+ Circle()
+ .fill(modeColor(config.mcpMode))
+ .frame(width: 8, height: 8)
+ }
+ .width(16)
+
+ TableColumn("Name", value: \.name) { config in
+ HStack(spacing: 6) {
+ Image(systemName: config.databaseType.iconName)
+ .foregroundStyle(.secondary)
+ Text(config.name)
+ }
+ }
+ .width(min: 120, ideal: 180)
+
+ TableColumn("Type") { config in
+ Text(config.databaseType.displayName)
+ .foregroundStyle(.secondary)
+ }
+ .width(min: 70, ideal: 90)
+
+ TableColumn("Host") { config in
+ Text(config.displayHost)
+ .foregroundStyle(.secondary)
+ }
+ .width(min: 120, ideal: 200)
+
+ TableColumn("Access") { config in
+ Picker("", selection: Binding(
+ get: { config.mcpMode },
+ set: { newMode in
+ Task { await state.updateConnectionMode(config, newMode) }
+ }
+ )) {
+ ForEach(MCPConnectionMode.allCases) { mode in
+ Text(mode.displayName).tag(mode)
+ }
+ }
+ .labelsHidden()
+ .pickerStyle(.menu)
+ }
+ .width(min: 110, ideal: 130)
+
+ TableColumn("Description") { config in
+ Text(config.mcpMode.description)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .width(min: 140, ideal: 220)
+ }
+ .tableStyle(.inset(alternatesRowBackgrounds: true))
+ }
+
+ // MARK: - Helpers
+
+ private var filteredConnections: [ConnectionConfig] {
+ var result = state.connections
+
+ if !searchText.isEmpty {
+ result = result.filter {
+ $0.name.localizedCaseInsensitiveContains(searchText) ||
+ $0.displayHost.localizedCaseInsensitiveContains(searchText)
+ }
+ }
+
+ if let mode = filterMode {
+ result = result.filter { $0.mcpMode == mode }
+ }
+
+ return result.sorted(using: sortOrder)
+ }
+
+ private func modeColor(_ mode: MCPConnectionMode) -> Color {
+ switch mode {
+ case .locked: return .red
+ case .readOnly: return .blue
+ case .readWrite: return .green
+ }
+ }
+}
diff --git a/macos/Presentation/Windows/MCP/MCPOverviewView.swift b/macos/Presentation/Windows/MCP/MCPOverviewView.swift
new file mode 100644
index 0000000..02285ed
--- /dev/null
+++ b/macos/Presentation/Windows/MCP/MCPOverviewView.swift
@@ -0,0 +1,262 @@
+// MCPOverviewView.swift
+// Gridex
+//
+// MCP Server dashboard overview.
+
+import SwiftUI
+
+struct MCPOverviewView: View {
+ @AppStorage("mcp.enabled") private var mcpEnabled = false
+ @AppStorage("mcp.httpEnabled") private var httpEnabled = false
+ @AppStorage("mcp.httpPort") private var httpPort = 3333
+
+ @ObservedObject var state: MCPWindowState
+ let switchTab: (MCPTab) -> Void
+
+ var body: some View {
+ Form {
+ Section {
+ serverStatusRow
+ }
+
+ Section("Access") {
+ LabeledContent("Locked") {
+ accessValue(count: countFor(.locked), color: .red)
+ }
+ LabeledContent("Read-only") {
+ accessValue(count: countFor(.readOnly), color: .blue)
+ }
+ LabeledContent("Read-write") {
+ accessValue(count: countFor(.readWrite), color: .green)
+ }
+
+ Button("Manage Connections…") {
+ switchTab(.connections)
+ }
+ .controlSize(.small)
+ }
+
+ Section("Transport") {
+ LabeledContent("stdio") {
+ HStack(spacing: 6) {
+ Text("Local clients")
+ .foregroundStyle(.secondary)
+ Image(systemName: "checkmark.circle.fill")
+ .foregroundStyle(.green)
+ .font(.caption)
+ }
+ }
+
+ Toggle("HTTP", isOn: $httpEnabled)
+
+ if httpEnabled {
+ LabeledContent("Port") {
+ HStack(spacing: 4) {
+ TextField("", value: $httpPort, format: .number.grouping(.never))
+ .textFieldStyle(.roundedBorder)
+ .frame(width: 80)
+ .multilineTextAlignment(.trailing)
+ Text("localhost only")
+ .foregroundStyle(.secondary)
+ .font(.caption)
+ }
+ }
+ }
+ }
+
+ Section {
+ if state.recentActivity.isEmpty {
+ HStack {
+ Text("No activity yet")
+ .foregroundStyle(.secondary)
+ .font(.callout)
+ Spacer()
+ }
+ .padding(.vertical, 4)
+ } else {
+ ForEach(state.recentActivity.prefix(5)) { entry in
+ activityRow(entry)
+ }
+
+ Button("View All Activity…") {
+ switchTab(.activity)
+ }
+ .controlSize(.small)
+ }
+ } header: {
+ HStack {
+ Text("Recent Activity")
+ Spacer()
+ if !state.recentActivity.isEmpty {
+ Text("\(state.recentActivity.count) events")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .textCase(nil)
+ }
+ }
+ }
+
+ if !state.connections.isEmpty {
+ Section("Connections") {
+ ForEach(state.connections.prefix(5)) { config in
+ connectionRow(config)
+ }
+
+ if state.connections.count > 5 {
+ Button("Show all \(state.connections.count) connections…") {
+ switchTab(.connections)
+ }
+ .controlSize(.small)
+ }
+ }
+ }
+ }
+ .formStyle(.grouped)
+ }
+
+ // MARK: - Server Status Row
+
+ private var serverStatusRow: some View {
+ HStack(spacing: 14) {
+ ZStack {
+ Circle()
+ .fill((mcpEnabled ? Color.green : Color.secondary).opacity(0.15))
+ .frame(width: 38, height: 38)
+
+ Image(systemName: mcpEnabled ? "checkmark.circle.fill" : "pause.circle.fill")
+ .font(.system(size: 22))
+ .foregroundStyle(mcpEnabled ? Color.green : Color.secondary)
+ }
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(mcpEnabled ? "MCP Server is running" : "MCP Server is stopped")
+ .font(.headline)
+ Text(overviewStatusDetail)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+ }
+ .padding(.vertical, 6)
+ }
+
+ private var overviewStatusDetail: String {
+ if !mcpEnabled {
+ return "Start the server from the header to allow AI clients to access your databases."
+ }
+ var parts: [String] = []
+ if state.uptime > 0 {
+ parts.append("Running for \(formatUptime(state.uptime))")
+ }
+ let activeCount = state.connections.filter { $0.mcpMode != .locked }.count
+ parts.append("\(activeCount) of \(state.connections.count) connection\(state.connections.count == 1 ? "" : "s") exposed")
+ return parts.joined(separator: " · ")
+ }
+
+ // MARK: - Rows
+
+ private func accessValue(count: Int, color: Color) -> some View {
+ HStack(spacing: 8) {
+ Circle()
+ .fill(color)
+ .frame(width: 6, height: 6)
+ Text("\(count)")
+ .font(.system(.callout, design: .rounded).weight(.medium))
+ .monospacedDigit()
+ .foregroundStyle(count > 0 ? .primary : .secondary)
+ }
+ }
+
+ private func activityRow(_ entry: MCPAuditEntry) -> some View {
+ LabeledContent {
+ HStack(spacing: 8) {
+ Text("\(entry.result.durationMs)ms")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .monospacedDigit()
+
+ Circle()
+ .fill(colorForStatus(MCPAuditStatus(rawValue: entry.result.status) ?? .success))
+ .frame(width: 6, height: 6)
+ }
+ } label: {
+ VStack(alignment: .leading, spacing: 1) {
+ HStack(spacing: 6) {
+ Text(entry.tool)
+ .font(.system(.callout, design: .monospaced))
+ Text("·")
+ .foregroundStyle(.tertiary)
+ Text(entry.client.name)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Text(formatRelativeTime(entry.timestamp))
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ }
+ }
+ }
+
+ private func connectionRow(_ config: ConnectionConfig) -> some View {
+ LabeledContent {
+ Text(config.mcpMode.displayName)
+ .font(.caption)
+ .foregroundStyle(modeColor(config.mcpMode))
+ } label: {
+ HStack(spacing: 8) {
+ Image(systemName: config.databaseType.iconName)
+ .foregroundStyle(.secondary)
+ .frame(width: 16)
+
+ Text(config.name)
+
+ Text(config.displayHost)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ }
+ }
+
+ // MARK: - Helpers
+
+ private func countFor(_ mode: MCPConnectionMode) -> Int {
+ state.connections.filter { $0.mcpMode == mode }.count
+ }
+
+ private func modeColor(_ mode: MCPConnectionMode) -> Color {
+ switch mode {
+ case .locked: return .red
+ case .readOnly: return .blue
+ case .readWrite: return .green
+ }
+ }
+
+ private func colorForStatus(_ status: MCPAuditStatus) -> Color {
+ switch status {
+ case .success: return .green
+ case .error: return .red
+ case .denied: return .orange
+ case .timeout: return .yellow
+ }
+ }
+
+ private func formatRelativeTime(_ date: Date) -> String {
+ let interval = Date().timeIntervalSince(date)
+ if interval < 60 { return "just now" }
+ if interval < 3600 { return "\(Int(interval / 60))m ago" }
+ if interval < 86400 { return "\(Int(interval / 3600))h ago" }
+ return "\(Int(interval / 86400))d ago"
+ }
+
+ private func formatUptime(_ interval: TimeInterval) -> String {
+ let total = Int(interval)
+ let h = total / 3600
+ let m = (total % 3600) / 60
+ let s = total % 60
+ if h > 0 { return "\(h)h \(m)m" }
+ if m > 0 { return "\(m)m \(s)s" }
+ return "\(s)s"
+ }
+}
diff --git a/macos/Presentation/Windows/MCP/MCPSetupView.swift b/macos/Presentation/Windows/MCP/MCPSetupView.swift
new file mode 100644
index 0000000..e5abd27
--- /dev/null
+++ b/macos/Presentation/Windows/MCP/MCPSetupView.swift
@@ -0,0 +1,347 @@
+// MCPSetupView.swift
+// Gridex
+//
+// Quick setup guide for configuring AI clients.
+
+import SwiftUI
+
+struct MCPSetupView: View {
+ @AppStorage("mcp.httpEnabled") private var httpEnabled = false
+ @AppStorage("mcp.httpPort") private var httpPort = 3333
+
+ @State private var copiedClient: String?
+ @State private var selectedClient: MCPClientType = .claudeDesktop
+ @State private var installResult: InstallResult?
+ @State private var showInstallAlert = false
+
+ enum InstallResult {
+ case success(String)
+ case error(String)
+
+ var title: String {
+ switch self {
+ case .success: return "Installed"
+ case .error: return "Install Failed"
+ }
+ }
+
+ var message: String {
+ switch self {
+ case .success(let msg), .error(let msg): return msg
+ }
+ }
+ }
+
+ var body: some View {
+ Form {
+ Section {
+ HStack(spacing: 10) {
+ Image(systemName: "info.circle.fill")
+ .foregroundStyle(.blue)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("This is a config file, not a terminal command")
+ .font(.callout.weight(.medium))
+ Text("Use \"Install\" below to add Gridex to your client automatically, or copy and paste into the config file manually.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ }
+ .padding(.vertical, 2)
+ }
+
+ Section("Client") {
+ Picker("AI Client", selection: $selectedClient) {
+ ForEach(MCPClientType.allCases) { client in
+ Label(client.displayName, systemImage: client.iconName).tag(client)
+ }
+ }
+ .pickerStyle(.menu)
+
+ LabeledContent("Config file") {
+ HStack(spacing: 6) {
+ Text(selectedClient.configPath)
+ .font(.system(.caption, design: .monospaced))
+ .textSelection(.enabled)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+
+ Button {
+ openConfigPath()
+ } label: {
+ Image(systemName: "arrow.up.right.square")
+ }
+ .buttonStyle(.borderless)
+ .help("Show in Finder")
+ }
+ }
+ }
+
+ Section {
+ HStack {
+ Button {
+ installConfig()
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: "wand.and.stars")
+ Text("Install for \(selectedClient.displayName)")
+ }
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.large)
+
+ Button {
+ copyConfig()
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: copiedClient == selectedClient.rawValue ? "checkmark" : "doc.on.clipboard")
+ Text(copiedClient == selectedClient.rawValue ? "Copied" : "Copy")
+ }
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.large)
+ }
+ } header: {
+ Text("Quick Install")
+ } footer: {
+ Text("Install merges Gridex into your existing config automatically. Backup of the original file is kept next to it.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+
+ Section {
+ ScrollView(.horizontal, showsIndicators: false) {
+ Text(selectedClient.configJSON(httpPort: httpPort, httpEnabled: httpEnabled))
+ .font(.system(.body, design: .monospaced))
+ .textSelection(.enabled)
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .background(Color(nsColor: .textBackgroundColor))
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ } header: {
+ Text("Configuration Preview")
+ } footer: {
+ Text("This is the JSON that will be merged into the mcpServers section of your config file.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+
+ Section("Manual Steps") {
+ stepRow(1, "Click \"Install\" above, or copy the JSON manually")
+ stepRow(2, "If manual: open the config file (Finder button)")
+ stepRow(3, "Paste the JSON inside \"mcpServers\": { ... }")
+ stepRow(4, "Save the file and restart \(selectedClient.displayName)")
+ stepRow(5, "Ask: \"List my database connections\"")
+ }
+ }
+ .formStyle(.grouped)
+ .alert(installResult?.title ?? "", isPresented: $showInstallAlert, presenting: installResult) { _ in
+ Button("OK") {}
+ } message: { result in
+ Text(result.message)
+ }
+ }
+
+ private func stepRow(_ number: Int, _ text: String) -> some View {
+ HStack(alignment: .top, spacing: 10) {
+ Text("\(number)")
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(.white)
+ .frame(width: 18, height: 18)
+ .background(Color.accentColor)
+ .clipShape(Circle())
+
+ Text(text)
+ .font(.callout)
+
+ Spacer()
+ }
+ }
+
+ private func copyConfig() {
+ let config = selectedClient.configJSON(httpPort: httpPort, httpEnabled: httpEnabled)
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(config, forType: .string)
+
+ withAnimation { copiedClient = selectedClient.rawValue }
+
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
+ withAnimation {
+ if copiedClient == selectedClient.rawValue {
+ copiedClient = nil
+ }
+ }
+ }
+ }
+
+ private func openConfigPath() {
+ let path = expandedConfigPath()
+ let url = URL(fileURLWithPath: path)
+ if FileManager.default.fileExists(atPath: path) {
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ } else {
+ NSWorkspace.shared.open(url.deletingLastPathComponent())
+ }
+ }
+
+ private func expandedConfigPath() -> String {
+ selectedClient.configPath
+ .replacingOccurrences(of: "~", with: FileManager.default.homeDirectoryForCurrentUser.path)
+ }
+
+ // MARK: - Install
+
+ private func installConfig() {
+ let fileManager = FileManager.default
+ let path = expandedConfigPath()
+ let url = URL(fileURLWithPath: path)
+
+ // Ensure parent directory exists
+ let dir = url.deletingLastPathComponent()
+ if !fileManager.fileExists(atPath: dir.path) {
+ do {
+ try fileManager.createDirectory(at: dir, withIntermediateDirectories: true)
+ } catch {
+ installResult = .error("Could not create config directory: \(error.localizedDescription)")
+ showInstallAlert = true
+ return
+ }
+ }
+
+ // Read existing JSON or start fresh
+ var existing: [String: Any] = [:]
+ if fileManager.fileExists(atPath: path) {
+ if let data = try? Data(contentsOf: url),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
+ existing = json
+
+ // Backup original
+ let backupURL = url.appendingPathExtension("bak")
+ try? data.write(to: backupURL)
+ } else if let data = try? Data(contentsOf: url), !data.isEmpty {
+ installResult = .error("Existing config file is not valid JSON. Please fix or delete it, then try again.")
+ showInstallAlert = true
+ return
+ }
+ }
+
+ // Build gridex entry
+ let gridexEntry: [String: Any]
+ if selectedClient == .claudeCode && httpEnabled {
+ gridexEntry = [
+ "url": "http://127.0.0.1:\(httpPort)/mcp"
+ ]
+ } else {
+ let gridexPath = Bundle.main.bundlePath.isEmpty
+ ? "/Applications/Gridex.app/Contents/MacOS/Gridex"
+ : "\(Bundle.main.bundlePath)/Contents/MacOS/Gridex"
+ gridexEntry = [
+ "command": gridexPath,
+ "args": ["--mcp-stdio"]
+ ]
+ }
+
+ // Merge into mcpServers
+ var mcpServers = existing["mcpServers"] as? [String: Any] ?? [:]
+ mcpServers["gridex"] = gridexEntry
+ existing["mcpServers"] = mcpServers
+
+ // Write back with pretty formatting
+ do {
+ let data = try JSONSerialization.data(
+ withJSONObject: existing,
+ options: [.prettyPrinted, .sortedKeys]
+ )
+ try data.write(to: url)
+ installResult = .success("Gridex has been added to \(selectedClient.displayName)'s config. Restart \(selectedClient.displayName) to apply.")
+ showInstallAlert = true
+ } catch {
+ installResult = .error("Could not write config file: \(error.localizedDescription)")
+ showInstallAlert = true
+ }
+ }
+}
+
+enum MCPClientType: String, CaseIterable, Identifiable {
+ case claudeDesktop = "claude_desktop"
+ case cursor = "cursor"
+ case windsurf = "windsurf"
+ case claudeCode = "claude_code"
+
+ var id: String { rawValue }
+
+ var displayName: String {
+ switch self {
+ case .claudeDesktop: return "Claude Desktop"
+ case .cursor: return "Cursor"
+ case .windsurf: return "Windsurf"
+ case .claudeCode: return "Claude Code"
+ }
+ }
+
+ var iconName: String {
+ switch self {
+ case .claudeDesktop: return "message.fill"
+ case .cursor: return "cursorarrow"
+ case .windsurf: return "wind"
+ case .claudeCode: return "terminal.fill"
+ }
+ }
+
+ var configPath: String {
+ switch self {
+ case .claudeDesktop:
+ return "~/Library/Application Support/Claude/claude_desktop_config.json"
+ case .cursor:
+ return "~/.cursor/mcp.json"
+ case .windsurf:
+ return "~/.windsurf/mcp.json"
+ case .claudeCode:
+ return "~/.claude/settings.json"
+ }
+ }
+
+ func configJSON(httpPort: Int, httpEnabled: Bool) -> String {
+ let gridexPath = Bundle.main.executablePath ?? "/Applications/Gridex.app/Contents/MacOS/Gridex"
+
+ switch self {
+ case .claudeDesktop, .cursor, .windsurf:
+ return """
+ {
+ "mcpServers": {
+ "gridex": {
+ "command": "\(gridexPath)",
+ "args": ["--mcp-stdio"]
+ }
+ }
+ }
+ """
+ case .claudeCode:
+ if httpEnabled {
+ return """
+ {
+ "mcpServers": {
+ "gridex": {
+ "url": "http://127.0.0.1:\(httpPort)/mcp"
+ }
+ }
+ }
+ """
+ } else {
+ return """
+ {
+ "mcpServers": {
+ "gridex": {
+ "command": "\(gridexPath)",
+ "args": ["--mcp-stdio"]
+ }
+ }
+ }
+ """
+ }
+ }
+ }
+}
diff --git a/macos/Presentation/Windows/MCP/MCPWindow.swift b/macos/Presentation/Windows/MCP/MCPWindow.swift
new file mode 100644
index 0000000..d905337
--- /dev/null
+++ b/macos/Presentation/Windows/MCP/MCPWindow.swift
@@ -0,0 +1,273 @@
+// MCPWindow.swift
+// Gridex
+//
+// Dedicated MCP Server management window.
+
+import SwiftUI
+
+@MainActor
+final class MCPWindowState: ObservableObject {
+ @Published var connections: [ConnectionConfig] = []
+ @Published var recentActivity: [MCPAuditEntry] = []
+ @Published var fullActivity: [MCPAuditEntry] = []
+ @Published var uptime: TimeInterval = 0
+ @Published var isLoadingActivity = false
+
+ private var timer: Timer?
+ private var hasLoadedConnections = false
+ private var hasLoadedActivity = false
+
+ private let connectionRepository: any ConnectionRepository = DependencyContainer.shared.connectionRepository
+
+ func start() {
+ startTimer()
+ Task { await loadConnections() }
+ Task { await loadRecentActivity() }
+ }
+
+ func stop() {
+ timer?.invalidate()
+ timer = nil
+ }
+
+ func loadConnections(force: Bool = false) async {
+ if hasLoadedConnections && !force { return }
+ let configs = (try? await connectionRepository.fetchAll()) ?? []
+ connections = configs
+ hasLoadedConnections = true
+ }
+
+ func loadRecentActivity() async {
+ let auditLogger = await DependencyContainer.shared.mcpServer.auditLog
+ let recent = (try? await auditLogger.recentEntries(limit: 10)) ?? []
+ recentActivity = recent
+ }
+
+ func loadFullActivity(force: Bool = false) async {
+ if hasLoadedActivity && !force { return }
+ isLoadingActivity = true
+ let auditLogger = await DependencyContainer.shared.mcpServer.auditLog
+ let all = (try? await auditLogger.recentEntries(limit: 500)) ?? []
+ fullActivity = all
+ isLoadingActivity = false
+ hasLoadedActivity = true
+ }
+
+ func updateConnectionMode(_ config: ConnectionConfig, _ mode: MCPConnectionMode) async {
+ var updated = config
+ updated.mcpMode = mode
+ try? await connectionRepository.update(updated)
+ await DependencyContainer.shared.mcpServer.setConnectionMode(mode, for: config.id)
+ if let idx = connections.firstIndex(where: { $0.id == config.id }) {
+ connections[idx] = updated
+ }
+ }
+
+ private func startTimer() {
+ refreshUptime()
+ timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
+ Task { @MainActor in self?.refreshUptime() }
+ }
+ }
+
+ private func refreshUptime() {
+ let enabled = UserDefaults.standard.bool(forKey: "mcp.enabled")
+ let startTime = UserDefaults.standard.double(forKey: "mcp.startTime")
+ if enabled && startTime > 0 {
+ uptime = Date().timeIntervalSince1970 - startTime
+ } else {
+ uptime = 0
+ }
+ }
+}
+
+struct MCPWindow: View {
+ @AppStorage("mcp.enabled") private var mcpEnabled = false
+ @AppStorage("mcp.startTime") private var serverStartTime: Double = 0
+
+ @State private var selectedTab: MCPTab = .overview
+ @StateObject private var state = MCPWindowState()
+
+ var body: some View {
+ VStack(spacing: 0) {
+ headerBar
+ Divider()
+ tabBar
+ Divider()
+ content
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .frame(minWidth: 860, minHeight: 580)
+ .background(Color(nsColor: .windowBackgroundColor))
+ .onAppear { state.start() }
+ .onDisappear { state.stop() }
+ .onChange(of: mcpEnabled) { _, newValue in
+ if newValue {
+ serverStartTime = Date().timeIntervalSince1970
+ } else {
+ serverStartTime = 0
+ }
+ }
+ }
+
+ // MARK: - Header
+
+ private var headerBar: some View {
+ HStack(spacing: 12) {
+ HStack(spacing: 8) {
+ ZStack {
+ Circle()
+ .fill((mcpEnabled ? Color.green : Color.secondary).opacity(0.18))
+ .frame(width: 24, height: 24)
+ Circle()
+ .fill(mcpEnabled ? Color.green : Color.secondary)
+ .frame(width: 8, height: 8)
+ }
+
+ VStack(alignment: .leading, spacing: 1) {
+ Text("MCP Server")
+ .font(.system(size: 13, weight: .semibold))
+ Text(statusDetail)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .monospacedDigit()
+ }
+ }
+
+ Spacer()
+
+ Button {
+ toggleServer()
+ } label: {
+ Text(mcpEnabled ? "Stop Server" : "Start Server")
+ .frame(minWidth: 84)
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.regular)
+ .tint(mcpEnabled ? .red : .accentColor)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 10)
+ }
+
+ private var statusDetail: String {
+ if !mcpEnabled { return "Server is stopped" }
+ if state.uptime > 0 {
+ return "Running · \(formatUptime(state.uptime))"
+ }
+ return "Running"
+ }
+
+ private func toggleServer() {
+ let newValue = !mcpEnabled
+ mcpEnabled = newValue
+ Task {
+ if newValue {
+ await DependencyContainer.shared.bootstrapMCPServer()
+ } else {
+ await DependencyContainer.shared.mcpServer.stop()
+ }
+ MCPStatusBarController.shared.refresh()
+ }
+ }
+
+ // MARK: - Tab Bar
+
+ private var tabBar: some View {
+ HStack {
+ Picker("", selection: $selectedTab) {
+ ForEach(MCPTab.allCases) { tab in
+ Text(tab.title).tag(tab)
+ }
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .frame(maxWidth: 520)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 8)
+ }
+
+ // MARK: - Content
+
+ @ViewBuilder
+ private var content: some View {
+ switch selectedTab {
+ case .overview:
+ MCPOverviewView(state: state, switchTab: { selectedTab = $0 })
+ case .connections:
+ MCPConnectionsView(state: state)
+ case .activity:
+ MCPActivityView(state: state)
+ case .setup:
+ MCPSetupView()
+ case .config:
+ MCPAdvancedView()
+ }
+ }
+
+ private func formatUptime(_ interval: TimeInterval) -> String {
+ let total = Int(interval)
+ let h = total / 3600
+ let m = (total % 3600) / 60
+ let s = total % 60
+ if h > 0 { return "\(h)h \(m)m" }
+ if m > 0 { return "\(m)m \(s)s" }
+ return "\(s)s"
+ }
+}
+
+// MARK: - Tab Model
+
+enum MCPTab: String, Hashable, CaseIterable, Identifiable {
+ case overview
+ case connections
+ case activity
+ case setup
+ case config
+
+ var id: String { rawValue }
+
+ var title: String {
+ switch self {
+ case .overview: return "Overview"
+ case .connections: return "Connections"
+ case .activity: return "Activity"
+ case .setup: return "Setup"
+ case .config: return "Config"
+ }
+ }
+}
+
+// MARK: - Window Controller
+
+class MCPWindowController: NSWindowController {
+ static var shared: MCPWindowController?
+
+ convenience init() {
+ let window = NSWindow(
+ contentRect: NSRect(x: 0, y: 0, width: 1000, height: 700),
+ styleMask: [.titled, .closable, .miniaturizable, .resizable],
+ backing: .buffered,
+ defer: false
+ )
+ window.title = "MCP Server"
+ window.isOpaque = true
+ window.backgroundColor = NSColor.windowBackgroundColor
+ window.center()
+ window.contentView = NSHostingView(rootView: MCPWindow())
+ window.isReleasedWhenClosed = false
+
+ self.init(window: window)
+ }
+
+ static func show() {
+ if shared == nil {
+ shared = MCPWindowController()
+ }
+ shared?.showWindow(nil)
+ shared?.window?.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
+}
diff --git a/macos/Resources/Info.plist b/macos/Resources/Info.plist
index af1c770..12820b3 100644
--- a/macos/Resources/Info.plist
+++ b/macos/Resources/Info.plist
@@ -32,9 +32,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
- <string>0.0.3</string>
+ <string>0.0.4</string>
<key>CFBundleVersion</key>
- <string>3</string>
+ <string>4</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>NSAppTransportSecurity</key>
@@ -50,15 +50,15 @@
<string></string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
+ <key>SUAutomaticallyUpdate</key>
+ <false/>
+ <key>SUEnableAutomaticChecks</key>
+ <true/>
<key>SUFeedURL</key>
<string>https://cdn.gridex.app/macos/appcast.xml</string>
<key>SUPublicEDKey</key>
<string>4/cJL5efe7LF8thRAWjaLJui1cdzIxRPf0bgt3Waxas=</string>
- <key>SUEnableAutomaticChecks</key>
- <true/>
<key>SUScheduledCheckInterval</key>
<integer>86400</integer>
- <key>SUAutomaticallyUpdate</key>
- <false/>
</dict>
</plist>
diff --git a/macos/Services/MCP/Audit/MCPAuditLogger.swift b/macos/Services/MCP/Audit/MCPAuditLogger.swift
new file mode 100644
index 0000000..4e71191
--- /dev/null
+++ b/macos/Services/MCP/Audit/MCPAuditLogger.swift
@@ -0,0 +1,108 @@
+// MCPAuditLogger.swift
+// Gridex
+//
+// Async audit logger for MCP tool invocations.
+// Writes JSONL to ~/Library/Application Support/Gridex/mcp-audit.jsonl
+
+import Foundation
+
+actor MCPAuditLogger {
+ private let fileURL: URL
+ private let encoder: JSONEncoder
+ private let maxFileSize: Int64 = 100 * 1024 * 1024 // 100MB
+ private var fileHandle: FileHandle?
+
+ init() {
+ let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
+ let gridexDir = appSupport.appendingPathComponent("Gridex", isDirectory: true)
+ try? FileManager.default.createDirectory(at: gridexDir, withIntermediateDirectories: true)
+ self.fileURL = gridexDir.appendingPathComponent("mcp-audit.jsonl")
+
+ self.encoder = JSONEncoder()
+ self.encoder.dateEncodingStrategy = .iso8601
+ self.encoder.outputFormatting = .sortedKeys
+ }
+
+ func log(_ entry: MCPAuditEntry) async {
+ do {
+ try await rotateIfNeeded()
+ let data = try encoder.encode(entry)
+ guard var line = String(data: data, encoding: .utf8) else { return }
+ line.append("\n")
+ try await appendToFile(line)
+ } catch {
+ // Audit logging should never crash the app
+ print("[MCP Audit] Failed to log entry: \(error)")
+ }
+ }
+
+ private func appendToFile(_ line: String) async throws {
+ let handle = try getOrCreateHandle()
+ if let data = line.data(using: .utf8) {
+ try handle.write(contentsOf: data)
+ }
+ }
+
+ private func getOrCreateHandle() throws -> FileHandle {
+ if let handle = fileHandle { return handle }
+
+ if !FileManager.default.fileExists(atPath: fileURL.path) {
+ FileManager.default.createFile(atPath: fileURL.path, contents: nil)
+ }
+
+ let handle = try FileHandle(forWritingTo: fileURL)
+ try handle.seekToEnd()
+ fileHandle = handle
+ return handle
+ }
+
+ private func rotateIfNeeded() async throws {
+ guard FileManager.default.fileExists(atPath: fileURL.path) else { return }
+ let attrs = try FileManager.default.attributesOfItem(atPath: fileURL.path)
+ guard let size = attrs[.size] as? Int64, size >= maxFileSize else { return }
+
+ // Close current handle
+ try fileHandle?.close()
+ fileHandle = nil
+
+ // Rotate: rename current to timestamped backup
+ let timestamp = ISO8601DateFormatter().string(from: Date())
+ .replacingOccurrences(of: ":", with: "-")
+ let backupURL = fileURL.deletingLastPathComponent()
+ .appendingPathComponent("mcp-audit-\(timestamp).jsonl")
+ try FileManager.default.moveItem(at: fileURL, to: backupURL)
+ }
+
+ func close() async {
+ try? fileHandle?.close()
+ fileHandle = nil
+ }
+
+ // MARK: - Query Methods
+
+ func recentEntries(limit: Int = 100) async throws -> [MCPAuditEntry] {
+ guard FileManager.default.fileExists(atPath: fileURL.path) else { return [] }
+
+ let data = try Data(contentsOf: fileURL)
+ let lines = String(data: data, encoding: .utf8)?.components(separatedBy: .newlines) ?? []
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+
+ var entries: [MCPAuditEntry] = []
+ for line in lines.suffix(limit).reversed() {
+ guard !line.isEmpty, let lineData = line.data(using: .utf8) else { continue }
+ if let entry = try? decoder.decode(MCPAuditEntry.self, from: lineData) {
+ entries.append(entry)
+ }
+ }
+ return entries
+ }
+
+ func clearAll() async throws {
+ try fileHandle?.close()
+ fileHandle = nil
+ try FileManager.default.removeItem(at: fileURL)
+ }
+
+ var logFileURL: URL { fileURL }
+}
diff --git a/macos/Services/MCP/MCPServer.swift b/macos/Services/MCP/MCPServer.swift
new file mode 100644
index 0000000..ca6c694
--- /dev/null
+++ b/macos/Services/MCP/MCPServer.swift
@@ -0,0 +1,328 @@
+// MCPServer.swift
+// Gridex
+//
+// Main MCP Server actor that handles all MCP protocol communication.
+
+import Foundation
+
+enum MCPTransportMode {
+ case stdio // CLI mode - uses stdin/stdout
+ case httpOnly // GUI mode - HTTP transport only (no blocking stdin)
+}
+
+actor MCPServer: StdioTransportDelegate {
+ private let transport: StdioTransport?
+ private let toolRegistry: MCPToolRegistry
+ private let permissionEngine: MCPPermissionEngine
+ private let auditLogger: MCPAuditLogger
+ private let rateLimiter: MCPRateLimiter
+ private let approvalGate: MCPApprovalGate
+
+ private let connectionManager: ConnectionManager
+ private let connectionRepository: any ConnectionRepository
+
+ private var isRunning = false
+ private var clientInfo: MCPClientInfo?
+
+ private let serverVersion: String
+ private let transportMode: MCPTransportMode
+
+ init(
+ connectionManager: ConnectionManager,
+ connectionRepository: any ConnectionRepository,
+ serverVersion: String = "1.0.0",
+ transportMode: MCPTransportMode = .httpOnly
+ ) {
+ self.connectionManager = connectionManager
+ self.connectionRepository = connectionRepository
+ self.serverVersion = serverVersion
+ self.transportMode = transportMode
+
+ // Only create stdio transport in CLI mode
+ self.transport = transportMode == .stdio ? StdioTransport() : nil
+ self.toolRegistry = MCPToolRegistry()
+ self.permissionEngine = MCPPermissionEngine()
+ self.auditLogger = MCPAuditLogger()
+ self.rateLimiter = MCPRateLimiter()
+ self.approvalGate = MCPApprovalGate()
+ }
+
+ // MARK: - Lifecycle
+
+ func start() async {
+ guard !isRunning else { return }
+ isRunning = true
+
+ if let transport = transport {
+ await transport.setDelegate(self)
+ await transport.start()
+ }
+ // TODO: Start HTTP transport if httpEnabled
+ }
+
+ func stop() async {
+ isRunning = false
+ if let transport = transport {
+ await transport.stop()
+ }
+ await auditLogger.close()
+ }
+
+ // MARK: - Permission Management
+
+ func setConnectionMode(_ mode: MCPConnectionMode, for connectionId: UUID) async {
+ await permissionEngine.setMode(mode, for: connectionId)
+ }
+
+ func getConnectionMode(for connectionId: UUID) async -> MCPConnectionMode {
+ await permissionEngine.getMode(for: connectionId)
+ }
+
+ // MARK: - StdioTransportDelegate
+
+ nonisolated func transport(_ transport: StdioTransport, didReceiveRequest request: JSONRPCRequest) async {
+ await handleRequest(request)
+ }
+
+ // MARK: - Request Handling
+
+ private func handleRequest(_ request: JSONRPCRequest) async {
+ let response: JSONRPCResponse
+
+ switch request.method {
+ case "initialize":
+ response = await handleInitialize(request)
+
+ case "initialized":
+ // Client acknowledges initialization, no response needed
+ return
+
+ case "tools/list":
+ response = await handleToolsList(request)
+
+ case "tools/call":
+ response = await handleToolCall(request)
+
+ case "ping":
+ response = JSONRPCResponse(id: request.id, result: .object(["pong": .bool(true)]))
+
+ case "shutdown":
+ response = JSONRPCResponse(id: request.id, result: .null)
+ await transport?.send(response)
+ await stop()
+ return
+
+ default:
+ response = JSONRPCResponse(id: request.id, error: .methodNotFound)
+ }
+
+ await transport?.send(response)
+ }
+
+ private func handleInitialize(_ request: JSONRPCRequest) async -> JSONRPCResponse {
+ // Extract client info
+ if let params = request.params,
+ let clientInfoObj = params["clientInfo"]?.objectValue {
+ let name = clientInfoObj["name"]?.stringValue ?? "unknown"
+ let version = clientInfoObj["version"]?.stringValue ?? "0.0.0"
+ clientInfo = MCPClientInfo(name: name, version: version)
+ }
+
+ let serverInfo = MCPServerInfo.gridex(version: serverVersion)
+
+ let result: JSONValue = .object([
+ "serverInfo": .object([
+ "name": .string(serverInfo.name),
+ "version": .string(serverInfo.version)
+ ]),
+ "protocolVersion": .string(serverInfo.protocolVersion),
+ "capabilities": .object([
+ "tools": .object(["listChanged": .bool(true)]),
+ "resources": .object(["subscribe": .bool(true), "listChanged": .bool(true)]),
+ "prompts": .object(["listChanged": .bool(true)]),
+ "logging": .object([:])
+ ])
+ ])
+
+ return JSONRPCResponse(id: request.id, result: result)
+ }
+
+ private func handleToolsList(_ request: JSONRPCRequest) async -> JSONRPCResponse {
+ let definitions = await toolRegistry.definitions()
+
+ var toolsArray: [JSONValue] = []
+ for def in definitions {
+ toolsArray.append(.object([
+ "name": .string(def.name),
+ "description": .string(def.description),
+ "inputSchema": def.inputSchema
+ ]))
+ }
+
+ let result: JSONValue = .object([
+ "tools": .array(toolsArray)
+ ])
+
+ return JSONRPCResponse(id: request.id, result: result)
+ }
+
+ private func handleToolCall(_ request: JSONRPCRequest) async -> JSONRPCResponse {
+ guard let params = request.params,
+ let toolName = params["name"]?.stringValue else {
+ return JSONRPCResponse(id: request.id, error: .invalidParams)
+ }
+
+ let toolParams = params["arguments"] ?? .object([:])
+
+ guard let tool = await toolRegistry.get(toolName) else {
+ let error = JSONRPCError(
+ code: MCPErrorCode.notFound.rawValue,
+ message: "Tool '\(toolName)' not found"
+ )
+ return JSONRPCResponse(id: request.id, error: error)
+ }
+
+ let startTime = Date()
+ let client = MCPAuditClient(
+ name: clientInfo?.name ?? "unknown",
+ version: clientInfo?.version ?? "0.0.0",
+ transport: "stdio"
+ )
+
+ // Extract connection ID for audit
+ var connectionId: UUID?
+ var connectionType: DatabaseType?
+ if let connIdStr = toolParams["connection_id"]?.stringValue,
+ let connId = UUID(uuidString: connIdStr) {
+ connectionId = connId
+ if let conn = await connectionManager.activeConnection(for: connId) {
+ connectionType = conn.config.databaseType
+ }
+ }
+
+ let context = MCPToolContext(
+ connectionManager: connectionManager,
+ permissionEngine: permissionEngine,
+ auditLogger: auditLogger,
+ rateLimiter: rateLimiter,
+ approvalGate: approvalGate,
+ client: client,
+ connectionRepository: connectionRepository
+ )
+
+ do {
+ let toolResult = try await tool.execute(params: toolParams, context: context)
+ let durationMs = Int(Date().timeIntervalSince(startTime) * 1000)
+
+ // Get connection mode for audit
+ var connMode: MCPConnectionMode = .locked
+ if let connId = connectionId {
+ connMode = await permissionEngine.getMode(for: connId)
+ }
+
+ // Log to audit
+ let auditEntry = MCPAuditEntry(
+ tool: toolName,
+ tier: tool.tier,
+ connectionId: connectionId,
+ connectionType: connectionType,
+ client: client,
+ input: MCPAuditInput(
+ sql: toolParams["sql"]?.stringValue,
+ paramsCount: toolParams["params"]?.arrayValue?.count
+ ),
+ result: MCPAuditResult(
+ status: toolResult.isError == true ? .error : .success,
+ durationMs: durationMs
+ ),
+ security: MCPAuditSecurity(mode: connMode)
+ )
+ await auditLogger.log(auditEntry)
+
+ // Build response
+ var contentArray: [JSONValue] = []
+ for content in toolResult.content {
+ var contentObj: [String: JSONValue] = ["type": .string(content.type)]
+ if let text = content.text { contentObj["text"] = .string(text) }
+ if let data = content.data { contentObj["data"] = .string(data) }
+ if let mimeType = content.mimeType { contentObj["mimeType"] = .string(mimeType) }
+ contentArray.append(.object(contentObj))
+ }
+
+ var resultObj: [String: JSONValue] = ["content": .array(contentArray)]
+ if toolResult.isError == true {
+ resultObj["isError"] = .bool(true)
+ }
+
+ return JSONRPCResponse(id: request.id, result: .object(resultObj))
+
+ } catch {
+ let durationMs = Int(Date().timeIntervalSince(startTime) * 1000)
+ let errorMessage = sanitizeError(error)
+
+ // Get connection mode for audit
+ var errorConnMode: MCPConnectionMode = .locked
+ if let connId = connectionId {
+ errorConnMode = await permissionEngine.getMode(for: connId)
+ }
+
+ // Log error to audit
+ let auditEntry = MCPAuditEntry(
+ tool: toolName,
+ tier: tool.tier,
+ connectionId: connectionId,
+ connectionType: connectionType,
+ client: client,
+ input: MCPAuditInput(
+ sql: toolParams["sql"]?.stringValue,
+ paramsCount: toolParams["params"]?.arrayValue?.count
+ ),
+ result: MCPAuditResult(status: .error, durationMs: durationMs),
+ security: MCPAuditSecurity(mode: errorConnMode),
+ error: errorMessage
+ )
+ await auditLogger.log(auditEntry)
+
+ // Return error as tool result (not JSON-RPC error)
+ let toolResult = MCPToolResult.error(errorMessage)
+ var contentArray: [JSONValue] = []
+ for content in toolResult.content {
+ contentArray.append(.object([
+ "type": .string(content.type),
+ "text": .string(content.text ?? "")
+ ]))
+ }
+
+ return JSONRPCResponse(
+ id: request.id,
+ result: .object([
+ "content": .array(contentArray),
+ "isError": .bool(true)
+ ])
+ )
+ }
+ }
+
+ private func sanitizeError(_ error: Error) -> String {
+ // Never expose sensitive information
+ let message = error.localizedDescription
+
+ // Remove potential file paths
+ let sanitized = message
+ .replacingOccurrences(of: #"/Users/[^/\s]+"#, with: "[path]", options: .regularExpression)
+ .replacingOccurrences(of: #"/home/[^/\s]+"#, with: "[path]", options: .regularExpression)
+
+ // Remove potential connection strings
+ let noConnStrings = sanitized
+ .replacingOccurrences(of: #"postgres://[^\s]+"#, with: "[connection]", options: .regularExpression)
+ .replacingOccurrences(of: #"mysql://[^\s]+"#, with: "[connection]", options: .regularExpression)
+ .replacingOccurrences(of: #"mongodb://[^\s]+"#, with: "[connection]", options: .regularExpression)
+
+ return noConnStrings
+ }
+
+ // MARK: - Accessors for testing
+
+ var auditLog: MCPAuditLogger { auditLogger }
+ var tools: MCPToolRegistry { toolRegistry }
+}
diff --git a/macos/Services/MCP/MCPStatusBarController.swift b/macos/Services/MCP/MCPStatusBarController.swift
new file mode 100644
index 0000000..0303c66
--- /dev/null
+++ b/macos/Services/MCP/MCPStatusBarController.swift
@@ -0,0 +1,182 @@
+// MCPStatusBarController.swift
+// Gridex
+//
+// Menu bar status indicator for MCP server.
+
+import AppKit
+import SwiftUI
+
+@MainActor
+class MCPStatusBarController: NSObject, NSMenuDelegate {
+ static let shared = MCPStatusBarController()
+
+ private var statusItem: NSStatusItem?
+ private var connectedClients = 0
+ private var pendingApproval = false
+
+ private var isEnabled: Bool {
+ UserDefaults.standard.bool(forKey: "mcp.enabled")
+ }
+
+ private override init() {
+ super.init()
+ setupStatusItem()
+ }
+
+ private func setupStatusItem() {
+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
+ statusItem?.isVisible = true
+ updateIcon()
+ setupMenu()
+ }
+
+ func refresh() {
+ updateIcon()
+ }
+
+ private func updateIcon() {
+ guard let button = statusItem?.button else { return }
+
+ let iconName: String
+ let color: NSColor
+
+ if !isEnabled {
+ iconName = "server.rack"
+ color = .systemGray
+ } else if pendingApproval {
+ iconName = "server.rack"
+ color = .systemOrange
+ } else if connectedClients > 0 {
+ iconName = "server.rack"
+ color = .systemBlue
+ } else {
+ iconName = "server.rack"
+ color = .systemGreen
+ }
+
+ let config = NSImage.SymbolConfiguration(pointSize: 14, weight: .medium)
+ if let image = NSImage(systemSymbolName: iconName, accessibilityDescription: "MCP Server") {
+ let coloredImage = image.withSymbolConfiguration(config)
+ button.image = coloredImage
+ button.contentTintColor = color
+ }
+
+ button.toolTip = statusTooltip()
+ }
+
+ private func statusTooltip() -> String {
+ if !isEnabled {
+ return "MCP Server: Disabled"
+ }
+ if pendingApproval {
+ return "MCP Server: Approval Required"
+ }
+ if connectedClients > 0 {
+ return "MCP Server: \(connectedClients) client(s) connected"
+ }
+ return "MCP Server: Running"
+ }
+
+ private func setupMenu() {
+ let menu = NSMenu()
+ menu.delegate = self
+
+ // Status header
+ let headerItem = NSMenuItem(title: "MCP Server", action: nil, keyEquivalent: "")
+ headerItem.isEnabled = false
+ headerItem.tag = 0
+ menu.addItem(headerItem)
+
+ menu.addItem(NSMenuItem.separator())
+
+ // Toggle
+ let toggleItem = NSMenuItem(
+ title: "Enable MCP Server",
+ action: #selector(toggleServer),
+ keyEquivalent: ""
+ )
+ toggleItem.target = self
+ toggleItem.tag = 1
+ menu.addItem(toggleItem)
+
+ menu.addItem(NSMenuItem.separator())
+
+ // Open MCP Window
+ let openItem = NSMenuItem(
+ title: "Open MCP Server...",
+ action: #selector(openMCPWindow),
+ keyEquivalent: ""
+ )
+ openItem.target = self
+ menu.addItem(openItem)
+
+ // Activity Log
+ let activityItem = NSMenuItem(
+ title: "View Activity Log",
+ action: #selector(openActivityLog),
+ keyEquivalent: ""
+ )
+ activityItem.target = self
+ menu.addItem(activityItem)
+
+ self.statusItem?.menu = menu
+ }
+
+ // NSMenuDelegate - update toggle state when menu opens
+ nonisolated func menuWillOpen(_ menu: NSMenu) {
+ Task { @MainActor in
+ if let toggleItem = menu.item(withTag: 1) {
+ toggleItem.state = self.isEnabled ? .on : .off
+ }
+ }
+ }
+
+ @objc private func toggleServer() {
+ let newValue = !isEnabled
+ UserDefaults.standard.set(newValue, forKey: "mcp.enabled")
+ updateIcon()
+
+ // Start or stop MCP server
+ Task {
+ if newValue {
+ await DependencyContainer.shared.bootstrapMCPServer()
+ } else {
+ await DependencyContainer.shared.mcpServer.stop()
+ }
+ }
+ }
+
+ @objc private func openMCPWindow() {
+ MCPWindowController.show()
+ }
+
+ @objc private func openActivityLog() {
+ MCPWindowController.show()
+ // TODO: Navigate to activity section
+ }
+
+ // MARK: - Public API
+
+ func updateClientCount(_ count: Int) {
+ connectedClients = count
+ updateIcon()
+ }
+
+ func showPendingApproval(_ pending: Bool) {
+ pendingApproval = pending
+ updateIcon()
+
+ if pending {
+ // Pulse the icon
+ NSApp.requestUserAttention(.criticalRequest)
+ }
+ }
+
+ func show() {
+ statusItem?.isVisible = true
+ }
+
+ func hide() {
+ statusItem?.isVisible = false
+ }
+}
diff --git a/macos/Services/MCP/Security/MCPApprovalGate.swift b/macos/Services/MCP/Security/MCPApprovalGate.swift
new file mode 100644
index 0000000..3d981ea
--- /dev/null
+++ b/macos/Services/MCP/Security/MCPApprovalGate.swift
@@ -0,0 +1,144 @@
+// MCPApprovalGate.swift
+// Gridex
+//
+// Approval gate for MCP write operations.
+// Shows a dialog and waits for user confirmation.
+
+import Foundation
+import AppKit
+import SwiftUI
+
+actor MCPApprovalGate {
+ private var pendingApprovals: [UUID: CheckedContinuation<Bool, Never>] = [:]
+ private var sessionApprovals: [SessionApprovalKey: Date] = [:]
+ private let sessionTimeout: TimeInterval = 30 * 60 // 30 minutes
+
+ struct SessionApprovalKey: Hashable {
+ let connectionId: UUID
+ let tool: String
+ }
+
+ func requestApproval(
+ tool: String,
+ description: String,
+ details: String,
+ connectionId: UUID,
+ client: MCPAuditClient,
+ timeout: TimeInterval = 60
+ ) async -> Bool {
+ // Check for session approval
+ let key = SessionApprovalKey(connectionId: connectionId, tool: tool)
+ if let approvalTime = sessionApprovals[key],
+ Date().timeIntervalSince(approvalTime) < sessionTimeout {
+ return true
+ }
+
+ let requestId = UUID()
+
+ return await withCheckedContinuation { continuation in
+ pendingApprovals[requestId] = continuation
+
+ // Show dialog on main thread
+ Task { @MainActor in
+ let result = await showApprovalDialog(
+ requestId: requestId,
+ tool: tool,
+ description: description,
+ details: details,
+ connectionId: connectionId,
+ client: client
+ )
+
+ Task {
+ await self.handleApprovalResult(
+ requestId: requestId,
+ result: result,
+ key: key
+ )
+ }
+ }
+
+ // Set timeout
+ Task {
+ try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
+ await self.timeoutApproval(requestId: requestId)
+ }
+ }
+ }
+
+ private func handleApprovalResult(requestId: UUID, result: ApprovalResult, key: SessionApprovalKey) {
+ guard let continuation = pendingApprovals.removeValue(forKey: requestId) else { return }
+
+ switch result {
+ case .approved:
+ continuation.resume(returning: true)
+ case .approvedForSession:
+ sessionApprovals[key] = Date()
+ continuation.resume(returning: true)
+ case .denied:
+ continuation.resume(returning: false)
+ }
+ }
+
+ private func timeoutApproval(requestId: UUID) {
+ guard let continuation = pendingApprovals.removeValue(forKey: requestId) else { return }
+ continuation.resume(returning: false)
+ }
+
+ func revokeSessionApproval(for connectionId: UUID) {
+ sessionApprovals = sessionApprovals.filter { $0.key.connectionId != connectionId }
+ }
+
+ func revokeAllSessionApprovals() {
+ sessionApprovals.removeAll()
+ }
+
+ @MainActor
+ private func showApprovalDialog(
+ requestId: UUID,
+ tool: String,
+ description: String,
+ details: String,
+ connectionId: UUID,
+ client: MCPAuditClient
+ ) async -> ApprovalResult {
+ await withCheckedContinuation { continuation in
+ let alert = NSAlert()
+ alert.messageText = "\(client.name) wants to:"
+ alert.informativeText = """
+ \(description)
+
+ \(details)
+
+ Connection: \(connectionId.uuidString.prefix(8))...
+ """
+ alert.alertStyle = .warning
+
+ alert.addButton(withTitle: "Deny")
+ alert.addButton(withTitle: "Approve Once")
+ alert.addButton(withTitle: "Approve for Session")
+
+ // Bring app to front
+ NSApp.activate(ignoringOtherApps: true)
+
+ let response = alert.runModal()
+
+ switch response {
+ case .alertFirstButtonReturn:
+ continuation.resume(returning: .denied)
+ case .alertSecondButtonReturn:
+ continuation.resume(returning: .approved)
+ case .alertThirdButtonReturn:
+ continuation.resume(returning: .approvedForSession)
+ default:
+ continuation.resume(returning: .denied)
+ }
+ }
+ }
+}
+
+enum ApprovalResult {
+ case approved
+ case approvedForSession
+ case denied
+}
diff --git a/macos/Services/MCP/Security/MCPIdentifierValidator.swift b/macos/Services/MCP/Security/MCPIdentifierValidator.swift
new file mode 100644
index 0000000..af9f534
--- /dev/null
+++ b/macos/Services/MCP/Security/MCPIdentifierValidator.swift
@@ -0,0 +1,52 @@
+// MCPIdentifierValidator.swift
+// Gridex
+//
+// Allowlist check for SQL identifiers received from MCP clients. Defense-
+// in-depth: even when the identifier is later quoted via
+// `SQLDialect.quoteIdentifier`, this validator rejects anything outside a
+// strict ASCII shape so unusual names never reach a driver.
+
+import Foundation
+
+enum MCPIdentifierValidator {
+ static let maxLength = 128
+
+ static func isValid(_ identifier: String) -> Bool {
+ var count = 0
+ for scalar in identifier.unicodeScalars {
+ count += 1
+ if count > maxLength { return false }
+ let v = scalar.value
+ let isLetter = (v >= 0x41 && v <= 0x5A) || (v >= 0x61 && v <= 0x7A) || v == 0x5F
+ let isDigit = v >= 0x30 && v <= 0x39
+ if count == 1 {
+ if !isLetter { return false }
+ } else {
+ if !isLetter && !isDigit { return false }
+ }
+ }
+ return count > 0
+ }
+
+ static func validate(_ identifier: String, as name: String = "identifier") throws {
+ guard isValid(identifier) else {
+ throw MCPToolError.invalidParameters(
+ "\(name) '\(identifier)' contains invalid characters. Allowed: letters, digits, underscore; must start with a letter or underscore; max \(maxLength) chars."
+ )
+ }
+ }
+
+ /// Shared extraction for MCP write tools: reads `table_name` and optional
+ /// `schema` from params and validates both. The returned schema is `nil`
+ /// when the caller omitted it.
+ static func extractTableAndSchema(from params: JSONValue) throws -> (table: String, schema: String?) {
+ guard let table = params["table_name"]?.stringValue else {
+ throw MCPToolError.invalidParameters("table_name is required")
+ }
+ try validate(table, as: "table_name")
+
+ let schema = params["schema"]?.stringValue
+ if let schema { try validate(schema, as: "schema") }
+ return (table, schema)
+ }
+}
diff --git a/macos/Services/MCP/Security/MCPPermissionEngine.swift b/macos/Services/MCP/Security/MCPPermissionEngine.swift
new file mode 100644
index 0000000..a0ee93a
--- /dev/null
+++ b/macos/Services/MCP/Security/MCPPermissionEngine.swift
@@ -0,0 +1,166 @@
+// MCPPermissionEngine.swift
+// Gridex
+//
+// Validates MCP tool permissions against connection modes.
+
+import Foundation
+
+actor MCPPermissionEngine {
+ private var connectionModes: [UUID: MCPConnectionMode] = [:]
+
+ func setMode(_ mode: MCPConnectionMode, for connectionId: UUID) {
+ connectionModes[connectionId] = mode
+ }
+
+ func getMode(for connectionId: UUID) -> MCPConnectionMode {
+ connectionModes[connectionId] ?? .locked
+ }
+
+ func removeMode(for connectionId: UUID) {
+ connectionModes[connectionId] = nil
+ }
+
+ func checkPermission(tier: MCPPermissionTier, connectionId: UUID) -> MCPPermissionResult {
+ let mode = getMode(for: connectionId)
+ return checkPermission(tier: tier, mode: mode)
+ }
+
+ func checkPermission(tier: MCPPermissionTier, mode: MCPConnectionMode) -> MCPPermissionResult {
+ switch tier {
+ case .schema:
+ return mode.allowsTier1 ? .allowed : .denied("Connection is locked. MCP access is disabled.")
+
+ case .read:
+ return mode.allowsTier2 ? .allowed : .denied("Connection is locked. MCP access is disabled.")
+
+ case .write:
+ if !mode.allowsTier3 {
+ return .denied("This operation requires read-write mode. Ask the user to enable it in Connection Settings > MCP Access.")
+ }
+ return .requiresApproval
+
+ case .ddl:
+ if !mode.allowsTier4 {
+ return .denied("DDL operations require read-write mode. Ask the user to enable it in Connection Settings > MCP Access.")
+ }
+ return .requiresApproval
+
+ case .advanced:
+ return mode.allowsTier5 ? .allowed : .denied("Connection is locked. MCP access is disabled.")
+ }
+ }
+
+ func validateReadOnlyQuery(_ sql: String) -> MCPPermissionResult {
+ let code = MCPSQLSanitizer.stripCommentsAndStrings(sql)
+ let trimmedUpper = code.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
+
+ // One optional trailing ';' is fine; anything else is multi-statement.
+ let withoutTrailingSemi = trimmedUpper.hasSuffix(";")
+ ? String(trimmedUpper.dropLast()).trimmingCharacters(in: .whitespacesAndNewlines)
+ : trimmedUpper
+ if withoutTrailingSemi.contains(";") {
+ return .denied("Multiple statements are not allowed in read-only mode.")
+ }
+
+ let isReadOnly = Self.readOnlyPrefixes.contains { trimmedUpper.hasPrefix($0) }
+ if !isReadOnly {
+ return .denied("Only SELECT queries are allowed in read-only mode. This query appears to modify data.")
+ }
+
+ let range = NSRange(code.startIndex..., in: code)
+ if let match = Self.dangerousKeywordRegex.firstMatch(in: code, options: [], range: range),
+ let matchRange = Range(match.range, in: code) {
+ let hit = String(code[matchRange]).uppercased()
+ return .denied("Query contains '\(hit)' which is not allowed in read-only mode.")
+ }
+
+ return .allowed
+ }
+
+ private static let readOnlyPrefixes = ["SELECT", "SHOW", "EXPLAIN", "DESCRIBE", "DESC", "WITH"]
+
+ private static let dangerousKeywords = [
+ // DML / DDL
+ "INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT",
+ "DROP", "CREATE", "ALTER", "TRUNCATE", "RENAME",
+ "GRANT", "REVOKE",
+ // Procedural execution
+ "CALL", "EXEC", "EXECUTE", "DO",
+ // Sequence / state mutations
+ "NEXTVAL", "SETVAL",
+ // PostgreSQL filesystem / server access
+ "LO_IMPORT", "LO_EXPORT",
+ "PG_READ_SERVER_FILES", "PG_WRITE_SERVER_FILES",
+ "PG_READ_BINARY_FILE", "PG_LS_DIR",
+ "DBLINK", "DBLINK_EXEC",
+ // Bulk / admin
+ "COPY", "VACUUM", "ANALYZE", "REINDEX", "CLUSTER", "REFRESH",
+ "LOCK", "UNLOCK",
+ // Session state
+ "SET", "RESET", "BEGIN", "COMMIT", "ROLLBACK", "SAVEPOINT"
+ ]
+
+ private static let dangerousKeywordRegex: NSRegularExpression = {
+ let alternation = dangerousKeywords
+ .map { NSRegularExpression.escapedPattern(for: $0) }
+ .joined(separator: "|")
+ return try! NSRegularExpression(pattern: "\\b(\(alternation))\\b", options: .caseInsensitive)
+ }()
+
+ /// Validate a WHERE clause supplied by an MCP client.
+ /// Blocks statement terminators, SQL comments, and trivial tautologies.
+ func validateWhereClause(_ whereClause: String?) -> MCPPermissionResult {
+ guard let whereClause else {
+ return .denied("WHERE clause is required for UPDATE/DELETE operations. Bare UPDATE/DELETE without WHERE is not allowed.")
+ }
+ let trimmed = whereClause.trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmed.isEmpty {
+ return .denied("WHERE clause is required for UPDATE/DELETE operations.")
+ }
+
+ // Reject injection vectors outright
+ if trimmed.contains(";") {
+ return .denied("WHERE clause must not contain ';' — statement terminators are forbidden.")
+ }
+ if trimmed.contains("--") {
+ return .denied("WHERE clause must not contain '--' — SQL line comments are forbidden.")
+ }
+ if trimmed.contains("/*") || trimmed.contains("*/") {
+ return .denied("WHERE clause must not contain '/*' or '*/' — SQL block comments are forbidden.")
+ }
+
+ // Reject trivial predicates (exact match after whitespace removal)
+ let compact = trimmed.uppercased()
+ .components(separatedBy: .whitespacesAndNewlines).joined()
+ let trivials: Set<String> = [
+ "1=1", "TRUE", "1", "'1'='1'",
+ "1<>0", "0=0", "2>1", "TRUE=TRUE", "NULLISNULL"
+ ]
+ if trivials.contains(compact) {
+ return .denied("Trivial WHERE clause '\(trimmed)' is not allowed. Provide a meaningful predicate.")
+ }
+
+ return .allowed
+ }
+}
+
+enum MCPPermissionResult: Sendable {
+ case allowed
+ case requiresApproval
+ case denied(String)
+
+ var isAllowed: Bool {
+ if case .allowed = self { return true }
+ return false
+ }
+
+ var requiresUserApproval: Bool {
+ if case .requiresApproval = self { return true }
+ return false
+ }
+
+ var errorMessage: String? {
+ if case .denied(let msg) = self { return msg }
+ return nil
+ }
+}
diff --git a/macos/Services/MCP/Security/MCPRateLimiter.swift b/macos/Services/MCP/Security/MCPRateLimiter.swift
new file mode 100644
index 0000000..ee06c59
--- /dev/null
+++ b/macos/Services/MCP/Security/MCPRateLimiter.swift
@@ -0,0 +1,175 @@
+// MCPRateLimiter.swift
+// Gridex
+//
+// Rate limiter for MCP operations.
+
+import Foundation
+
+actor MCPRateLimiter {
+ private var queryCount: [UUID: RateBucket] = [:]
+ private var writeCount: [UUID: RateBucket] = [:]
+ private var ddlCount: [UUID: RateBucket] = [:]
+
+ // Configurable limits (can be overridden via UserDefaults)
+ var queriesPerMinute: Int { UserDefaults.standard.integer(forKey: "mcp.rateLimit.queriesPerMinute").nonZero ?? 60 }
+ var queriesPerHour: Int { UserDefaults.standard.integer(forKey: "mcp.rateLimit.queriesPerHour").nonZero ?? 1000 }
+ var writesPerMinute: Int { UserDefaults.standard.integer(forKey: "mcp.rateLimit.writesPerMinute").nonZero ?? 10 }
+ var ddlPerMinute: Int { UserDefaults.standard.integer(forKey: "mcp.rateLimit.ddlPerMinute").nonZero ?? 1 }
+
+ func checkLimit(tier: MCPPermissionTier, connectionId: UUID) -> RateLimitResult {
+ let now = Date()
+
+ switch tier {
+ case .schema, .read, .advanced:
+ return checkQueryLimit(connectionId: connectionId, now: now)
+ case .write:
+ return checkWriteLimit(connectionId: connectionId, now: now)
+ case .ddl:
+ return checkDDLLimit(connectionId: connectionId, now: now)
+ }
+ }
+
+ func recordUsage(tier: MCPPermissionTier, connectionId: UUID) {
+ let now = Date()
+
+ switch tier {
+ case .schema, .read, .advanced:
+ recordQuery(connectionId: connectionId, now: now)
+ case .write:
+ recordWrite(connectionId: connectionId, now: now)
+ case .ddl:
+ recordDDL(connectionId: connectionId, now: now)
+ }
+ }
+
+ // MARK: - Query Rate Limiting
+
+ private func checkQueryLimit(connectionId: UUID, now: Date) -> RateLimitResult {
+ let bucket = queryCount[connectionId] ?? RateBucket()
+
+ // Check per-minute limit
+ let minuteCount = bucket.countInWindow(now: now, windowSeconds: 60)
+ if minuteCount >= queriesPerMinute {
+ let retryAfter = bucket.oldestInWindow(now: now, windowSeconds: 60)
+ .map { 60 - Int(now.timeIntervalSince($0)) } ?? 60
+ return .exceeded(retryAfter: max(1, retryAfter))
+ }
+
+ // Check per-hour limit
+ let hourCount = bucket.countInWindow(now: now, windowSeconds: 3600)
+ if hourCount >= queriesPerHour {
+ let retryAfter = bucket.oldestInWindow(now: now, windowSeconds: 3600)
+ .map { 3600 - Int(now.timeIntervalSince($0)) } ?? 3600
+ return .exceeded(retryAfter: max(1, retryAfter))
+ }
+
+ return .allowed
+ }
+
+ private func recordQuery(connectionId: UUID, now: Date) {
+ var bucket = queryCount[connectionId] ?? RateBucket()
+ bucket.record(now: now)
+ bucket.cleanup(now: now, maxAge: 3600) // Keep 1 hour of history
+ queryCount[connectionId] = bucket
+ }
+
+ // MARK: - Write Rate Limiting
+
+ private func checkWriteLimit(connectionId: UUID, now: Date) -> RateLimitResult {
+ let bucket = writeCount[connectionId] ?? RateBucket()
+
+ let minuteCount = bucket.countInWindow(now: now, windowSeconds: 60)
+ if minuteCount >= writesPerMinute {
+ let retryAfter = bucket.oldestInWindow(now: now, windowSeconds: 60)
+ .map { 60 - Int(now.timeIntervalSince($0)) } ?? 60
+ return .exceeded(retryAfter: max(1, retryAfter))
+ }
+
+ return .allowed
+ }
+
+ private func recordWrite(connectionId: UUID, now: Date) {
+ var bucket = writeCount[connectionId] ?? RateBucket()
+ bucket.record(now: now)
+ bucket.cleanup(now: now, maxAge: 60)
+ writeCount[connectionId] = bucket
+ }
+
+ // MARK: - DDL Rate Limiting
+
+ private func checkDDLLimit(connectionId: UUID, now: Date) -> RateLimitResult {
+ let bucket = ddlCount[connectionId] ?? RateBucket()
+
+ let minuteCount = bucket.countInWindow(now: now, windowSeconds: 60)
+ if minuteCount >= ddlPerMinute {
+ let retryAfter = bucket.oldestInWindow(now: now, windowSeconds: 60)
+ .map { 60 - Int(now.timeIntervalSince($0)) } ?? 60
+ return .exceeded(retryAfter: max(1, retryAfter))
+ }
+
+ return .allowed
+ }
+
+ private func recordDDL(connectionId: UUID, now: Date) {
+ var bucket = ddlCount[connectionId] ?? RateBucket()
+ bucket.record(now: now)
+ bucket.cleanup(now: now, maxAge: 60)
+ ddlCount[connectionId] = bucket
+ }
+
+ func resetLimits(for connectionId: UUID) {
+ queryCount[connectionId] = nil
+ writeCount[connectionId] = nil
+ ddlCount[connectionId] = nil
+ }
+
+ func resetAllLimits() {
+ queryCount.removeAll()
+ writeCount.removeAll()
+ ddlCount.removeAll()
+ }
+}
+
+struct RateBucket {
+ private var timestamps: [Date] = []
+
+ mutating func record(now: Date) {
+ timestamps.append(now)
+ }
+
+ func countInWindow(now: Date, windowSeconds: TimeInterval) -> Int {
+ let cutoff = now.addingTimeInterval(-windowSeconds)
+ return timestamps.filter { $0 > cutoff }.count
+ }
+
+ func oldestInWindow(now: Date, windowSeconds: TimeInterval) -> Date? {
+ let cutoff = now.addingTimeInterval(-windowSeconds)
+ return timestamps.filter { $0 > cutoff }.min()
+ }
+
+ mutating func cleanup(now: Date, maxAge: TimeInterval) {
+ let cutoff = now.addingTimeInterval(-maxAge)
+ timestamps = timestamps.filter { $0 > cutoff }
+ }
+}
+
+enum RateLimitResult {
+ case allowed
+ case exceeded(retryAfter: Int)
+
+ var isAllowed: Bool {
+ if case .allowed = self { return true }
+ return false
+ }
+
+ var retryAfterSeconds: Int? {
+ if case .exceeded(let seconds) = self { return seconds }
+ return nil
+ }
+}
+
+private extension Int {
+ var nonZero: Int? {
+ self > 0 ? self : nil
+ }
+}
diff --git a/macos/Services/MCP/Security/MCPRowCountEstimator.swift b/macos/Services/MCP/Security/MCPRowCountEstimator.swift
new file mode 100644
index 0000000..08bf7a0
--- /dev/null
+++ b/macos/Services/MCP/Security/MCPRowCountEstimator.swift
@@ -0,0 +1,28 @@
+// MCPRowCountEstimator.swift
+// Gridex
+//
+// Pre-approval row count estimation for write tools.
+//
+// The estimate runs against the same (already validated & quoted) SQL shape
+// that the write tool will execute, so it never reconstructs SQL from
+// user-supplied substrings — avoiding the "parse to rebuild COUNT(*)"
+// injection pattern.
+
+import Foundation
+
+enum MCPRowCountEstimator {
+ static func estimate(
+ adapter: any DatabaseAdapter,
+ qualifiedTable: String,
+ whereClause: String,
+ config: ConnectionConfig
+ ) async -> Int {
+ guard config.databaseType.isSQL else { return 0 }
+ let sql = "SELECT COUNT(*) FROM \(qualifiedTable) WHERE \(whereClause)"
+ guard let result = try? await adapter.executeRaw(sql: sql),
+ let count = result.rows.first?.first?.intValue else {
+ return 0
+ }
+ return count
+ }
+}
diff --git a/macos/Services/MCP/Security/MCPSQLSanitizer.swift b/macos/Services/MCP/Security/MCPSQLSanitizer.swift
new file mode 100644
index 0000000..bcbbc23
--- /dev/null
+++ b/macos/Services/MCP/Security/MCPSQLSanitizer.swift
@@ -0,0 +1,70 @@
+// MCPSQLSanitizer.swift
+// Gridex
+//
+// Normalizes SQL strings for security checks — NOT for execution.
+// Strips line comments, block comments, and single-quoted string literals so
+// syntactic checks (e.g. "does this contain WHERE?") operate on code-only
+// content rather than being fooled by payloads hidden inside comments or
+// literals.
+
+import Foundation
+
+enum MCPSQLSanitizer {
+ static func stripCommentsAndStrings(_ sql: String) -> String {
+ var result = ""
+ result.reserveCapacity(sql.count)
+ var i = sql.startIndex
+ let end = sql.endIndex
+
+ while i < end {
+ let c = sql[i]
+ let next = sql.index(after: i)
+
+ // -- line comment
+ if c == "-", next < end, sql[next] == "-" {
+ while i < end, sql[i] != "\n" {
+ i = sql.index(after: i)
+ }
+ continue
+ }
+
+ // /* block comment */
+ if c == "/", next < end, sql[next] == "*" {
+ i = sql.index(after: next)
+ while i < end {
+ let j = sql.index(after: i)
+ if sql[i] == "*", j < end, sql[j] == "/" {
+ i = sql.index(after: j)
+ break
+ }
+ i = sql.index(after: i)
+ }
+ continue
+ }
+
+ // 'single-quoted literal'
+ if c == "'" {
+ i = sql.index(after: i)
+ while i < end {
+ if sql[i] == "'" {
+ let j = sql.index(after: i)
+ if j < end, sql[j] == "'" {
+ // Escaped '' inside literal
+ i = sql.index(after: j)
+ continue
+ }
+ i = sql.index(after: i)
+ break
+ }
+ i = sql.index(after: i)
+ }
+ result.append(" ")
+ continue
+ }
+
+ result.append(c)
+ i = sql.index(after: i)
+ }
+ return result
+ }
+}
diff --git a/macos/Services/MCP/Tools/MCPTool.swift b/macos/Services/MCP/Tools/MCPTool.swift
new file mode 100644
index 0000000..c4f6582
--- /dev/null
+++ b/macos/Services/MCP/Tools/MCPTool.swift
@@ -0,0 +1,107 @@
+// MCPTool.swift
+// Gridex
+//
+// Protocol for MCP tools.
+
+import Foundation
+
+protocol MCPTool: Sendable {
+ var name: String { get }
+ var description: String { get }
+ var tier: MCPPermissionTier { get }
+ var inputSchema: [String: Any] { get }
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult
+}
+
+struct MCPToolContext: Sendable {
+ let connectionManager: ConnectionManager
+ let permissionEngine: MCPPermissionEngine
+ let auditLogger: MCPAuditLogger
+ let rateLimiter: MCPRateLimiter
+ let approvalGate: MCPApprovalGate
+ let client: MCPAuditClient
+ let connectionRepository: any ConnectionRepository
+
+ func getAdapter(for connectionId: UUID) async throws -> (any DatabaseAdapter, ConnectionConfig) {
+ guard let connection = await connectionManager.activeConnection(for: connectionId) else {
+ throw MCPToolError.connectionNotFound(connectionId)
+ }
+ return (connection.adapter, connection.config)
+ }
+
+ func checkPermission(tier: MCPPermissionTier, connectionId: UUID) async -> MCPPermissionResult {
+ await permissionEngine.checkPermission(tier: tier, connectionId: connectionId)
+ }
+
+ func checkRateLimit(tier: MCPPermissionTier, connectionId: UUID) async throws {
+ let result = await rateLimiter.checkLimit(tier: tier, connectionId: connectionId)
+ if let retryAfter = result.retryAfterSeconds {
+ throw MCPToolError.rateLimitExceeded(retryAfter: retryAfter)
+ }
+ }
+
+ func recordUsage(tier: MCPPermissionTier, connectionId: UUID) async {
+ await rateLimiter.recordUsage(tier: tier, connectionId: connectionId)
+ }
+
+ func requestApproval(
+ tool: String,
+ description: String,
+ details: String,
+ connectionId: UUID
+ ) async -> Bool {
+ await approvalGate.requestApproval(
+ tool: tool,
+ description: description,
+ details: details,
+ connectionId: connectionId,
+ client: client
+ )
+ }
+}
+
+enum MCPToolError: Error, LocalizedError, Sendable {
+ case connectionNotFound(UUID)
+ case connectionNotConnected(UUID)
+ case tableNotFound(String)
+ case invalidParameters(String)
+ case permissionDenied(String)
+ case queryFailed(String)
+ case rateLimitExceeded(retryAfter: Int)
+
+ var errorDescription: String? {
+ switch self {
+ case .connectionNotFound(let id):
+ return "Connection '\(id)' not found. Use list_connections to see available connections."
+ case .connectionNotConnected(let id):
+ return "Connection '\(id)' is not active. The user needs to connect first."
+ case .tableNotFound(let name):
+ return "Table '\(name)' not found."
+ case .invalidParameters(let msg):
+ return "Invalid parameters: \(msg)"
+ case .permissionDenied(let msg):
+ return msg
+ case .queryFailed(let msg):
+ return "Query failed: \(msg)"
+ case .rateLimitExceeded(let retryAfter):
+ return "Rate limit exceeded. Retry after \(retryAfter) seconds."
+ }
+ }
+}
+
+extension MCPTool {
+ func definition() -> MCPToolDefinition {
+ MCPToolDefinition(name: name, description: description, inputSchema: inputSchema)
+ }
+
+ func extractConnectionId(from params: JSONValue) throws -> UUID {
+ guard let idString = params["connection_id"]?.stringValue else {
+ throw MCPToolError.invalidParameters("connection_id is required")
+ }
+ guard let uuid = UUID(uuidString: idString) else {
+ throw MCPToolError.invalidParameters("connection_id must be a valid UUID")
+ }
+ return uuid
+ }
+}
diff --git a/macos/Services/MCP/Tools/MCPToolRegistry.swift b/macos/Services/MCP/Tools/MCPToolRegistry.swift
new file mode 100644
index 0000000..ce55440
--- /dev/null
+++ b/macos/Services/MCP/Tools/MCPToolRegistry.swift
@@ -0,0 +1,67 @@
+// MCPToolRegistry.swift
+// Gridex
+//
+// Registry for all available MCP tools.
+
+import Foundation
+
+actor MCPToolRegistry {
+ private var tools: [String: any MCPTool] = [:]
+
+ init() {
+ // Register default tools synchronously during init
+ // Tier 1: Schema Introspection
+ tools[ListConnectionsTool().name] = ListConnectionsTool()
+ tools[ListTablesTool().name] = ListTablesTool()
+ tools[DescribeTableTool().name] = DescribeTableTool()
+ tools[ListSchemasTool().name] = ListSchemasTool()
+ tools[GetSampleRowsTool().name] = GetSampleRowsTool()
+ tools[ListRelationshipsTool().name] = ListRelationshipsTool()
+
+ // Tier 2: Query Execution
+ tools[QueryTool().name] = QueryTool()
+ tools[ExplainQueryTool().name] = ExplainQueryTool()
+ tools[SearchAcrossTablesTool().name] = SearchAcrossTablesTool()
+
+ // Tier 3: Data Modification (requires approval)
+ tools[InsertRowsTool().name] = InsertRowsTool()
+ tools[UpdateRowsTool().name] = UpdateRowsTool()
+ tools[DeleteRowsTool().name] = DeleteRowsTool()
+ tools[ExecuteWriteQueryTool().name] = ExecuteWriteQueryTool()
+ }
+
+ private func registerDefaultToolsAsync() {
+ // Tier 1: Schema Introspection
+ register(ListConnectionsTool())
+ register(ListTablesTool())
+ register(DescribeTableTool())
+ register(ListSchemasTool())
+ register(GetSampleRowsTool())
+ register(ListRelationshipsTool())
+
+ // Tier 2: Query Execution
+ register(QueryTool())
+ register(ExplainQueryTool())
+ register(SearchAcrossTablesTool())
+ }
+
+ func register(_ tool: any MCPTool) {
+ tools[tool.name] = tool
+ }
+
+ func unregister(_ name: String) {
+ tools[name] = nil
+ }
+
+ func get(_ name: String) -> (any MCPTool)? {
+ tools[name]
+ }
+
+ func allTools() -> [any MCPTool] {
+ Array(tools.values)
+ }
+
+ func definitions() -> [MCPToolDefinition] {
+ tools.values.map { $0.definition() }
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier1/DescribeTableTool.swift b/macos/Services/MCP/Tools/Tier1/DescribeTableTool.swift
new file mode 100644
index 0000000..c231a88
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier1/DescribeTableTool.swift
@@ -0,0 +1,141 @@
+// DescribeTableTool.swift
+// Gridex
+//
+// MCP Tool: Get detailed structure of a table.
+
+import Foundation
+
+struct DescribeTableTool: MCPTool {
+ let name = "describe_table"
+ let description = "Get detailed structure of a table including columns, data types, indexes, primary keys, foreign keys, and constraints."
+ let tier = MCPPermissionTier.schema
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "table_name": [
+ "type": "string",
+ "description": "Name of the table to describe"
+ ],
+ "schema": [
+ "type": "string",
+ "description": "Optional schema name"
+ ]
+ ],
+ "required": ["connection_id", "table_name"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let tableName = params["table_name"]?.stringValue else {
+ throw MCPToolError.invalidParameters("table_name is required")
+ }
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, config) = try await context.getAdapter(for: connectionId)
+ let schemaName = params["schema"]?.stringValue
+
+ let tableDesc = try await adapter.describeTable(name: tableName, schema: schemaName)
+ let indexes = try await adapter.listIndexes(table: tableName, schema: schemaName)
+ let foreignKeys = try await adapter.listForeignKeys(table: tableName, schema: schemaName)
+
+ var result: [String: Any] = [
+ "name": tableDesc.name,
+ "database_type": config.databaseType.displayName
+ ]
+
+ if let schema = tableDesc.schema {
+ result["schema"] = schema
+ }
+
+ if let comment = tableDesc.comment {
+ result["comment"] = comment
+ }
+
+ if let rowCount = tableDesc.estimatedRowCount {
+ result["estimated_rows"] = rowCount
+ }
+
+ // Columns
+ var columns: [[String: Any]] = []
+ for col in tableDesc.columns {
+ var colInfo: [String: Any] = [
+ "name": col.name,
+ "type": col.dataType,
+ "nullable": col.isNullable
+ ]
+ if col.isPrimaryKey { colInfo["primary_key"] = true }
+ if let defaultVal = col.defaultValue { colInfo["default"] = defaultVal }
+ if let comment = col.comment { colInfo["comment"] = comment }
+ columns.append(colInfo)
+ }
+ result["columns"] = columns
+
+ // Primary key
+ let pkColumns = tableDesc.columns.filter(\.isPrimaryKey).map(\.name)
+ if !pkColumns.isEmpty {
+ result["primary_key"] = pkColumns
+ }
+
+ // Indexes
+ if !indexes.isEmpty {
+ var indexList: [[String: Any]] = []
+ for idx in indexes {
+ indexList.append([
+ "name": idx.name,
+ "columns": idx.columns,
+ "unique": idx.isUnique,
+ "type": idx.type ?? "btree"
+ ])
+ }
+ result["indexes"] = indexList
+ }
+
+ // Foreign keys
+ if !foreignKeys.isEmpty {
+ var fkList: [[String: Any]] = []
+ for fk in foreignKeys {
+ fkList.append([
+ "name": fk.name ?? "",
+ "columns": fk.columns,
+ "references_table": fk.referencedTable,
+ "references_columns": fk.referencedColumns
+ ])
+ }
+ result["foreign_keys"] = fkList
+ }
+
+ // Constraints
+ if !tableDesc.constraints.isEmpty {
+ var constraintList: [[String: Any]] = []
+ for c in tableDesc.constraints {
+ constraintList.append([
+ "name": c.name,
+ "type": c.type,
+ "definition": c.definition ?? ""
+ ])
+ }
+ result["constraints"] = constraintList
+ }
+
+ // Generate DDL
+ let ddl = tableDesc.toDDL(dialect: config.databaseType.sqlDialect)
+ result["ddl"] = ddl
+
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try JSONSerialization.data(withJSONObject: result, options: [.prettyPrinted, .sortedKeys])
+ let json = String(data: data, encoding: .utf8) ?? "{}"
+
+ return MCPToolResult(text: json)
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier1/GetSampleRowsTool.swift b/macos/Services/MCP/Tools/Tier1/GetSampleRowsTool.swift
new file mode 100644
index 0000000..3041281
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier1/GetSampleRowsTool.swift
@@ -0,0 +1,87 @@
+// GetSampleRowsTool.swift
+// Gridex
+//
+// MCP Tool: Get sample rows from a table.
+
+import Foundation
+
+struct GetSampleRowsTool: MCPTool {
+ let name = "get_sample_rows"
+ let description = "Get sample rows from a table to help understand data shape. Default limit 10, max 100."
+ let tier = MCPPermissionTier.schema
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "table_name": [
+ "type": "string",
+ "description": "Name of the table"
+ ],
+ "limit": [
+ "type": "integer",
+ "description": "Number of rows to return (default 10, max 100)",
+ "default": 10,
+ "minimum": 1,
+ "maximum": 100
+ ]
+ ],
+ "required": ["connection_id", "table_name"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let tableName = params["table_name"]?.stringValue else {
+ throw MCPToolError.invalidParameters("table_name is required")
+ }
+
+ let limit = min(100, max(1, params["limit"]?.intValue ?? 10))
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, _) = try await context.getAdapter(for: connectionId)
+
+ let result = try await adapter.fetchRows(
+ table: tableName,
+ schema: nil,
+ columns: nil,
+ where: nil,
+ orderBy: nil,
+ limit: limit,
+ offset: 0
+ )
+
+ if result.rows.isEmpty {
+ return MCPToolResult(text: "Table '\(tableName)' is empty.")
+ }
+
+ // Format as JSON array of objects
+ var rows: [[String: String]] = []
+ for row in result.rows {
+ var rowDict: [String: String] = [:]
+ for (idx, col) in result.columns.enumerated() {
+ if idx < row.count {
+ rowDict[col.name] = row[idx].displayString
+ }
+ }
+ rows.append(rowDict)
+ }
+
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(rows)
+ let json = String(data: data, encoding: .utf8) ?? "[]"
+
+ let header = "Sample \(rows.count) row(s) from '\(tableName)':\n"
+ let columns = "Columns: " + result.columns.map { "\($0.name) (\($0.dataType))" }.joined(separator: ", ") + "\n\n"
+
+ return MCPToolResult(text: header + columns + json)
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier1/ListConnectionsTool.swift b/macos/Services/MCP/Tools/Tier1/ListConnectionsTool.swift
new file mode 100644
index 0000000..c0413f2
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier1/ListConnectionsTool.swift
@@ -0,0 +1,55 @@
+// ListConnectionsTool.swift
+// Gridex
+//
+// MCP Tool: List all configured database connections.
+
+import Foundation
+
+struct ListConnectionsTool: MCPTool {
+ let name = "list_connections"
+ let description = "List all configured database connections. Returns connection IDs, names, and types (postgres/mysql/sqlite/redis/mongodb/mssql)."
+ let tier = MCPPermissionTier.schema
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [:] as [String: Any]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let configs = try await context.connectionRepository.fetchAll()
+ let activeConnections = await context.connectionManager.allActiveConnections
+
+ var connections: [[String: Any]] = []
+ for config in configs {
+ let mode = await context.permissionEngine.getMode(for: config.id)
+
+ // Skip locked connections from MCP view
+ if mode == .locked { continue }
+
+ let isConnected = activeConnections.contains { $0.id == config.id }
+
+ connections.append([
+ "id": config.id.uuidString,
+ "name": config.name,
+ "type": config.databaseType.rawValue,
+ "host": config.displayHost,
+ "database": config.database ?? "",
+ "is_connected": isConnected,
+ "mcp_mode": mode.rawValue
+ ])
+ }
+
+ if connections.isEmpty {
+ return MCPToolResult(text: "No connections available for MCP access. All connections are either locked or none exist.")
+ }
+
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(connections.map { dict -> [String: String] in
+ dict.mapValues { "\($0)" }
+ })
+ let json = String(data: data, encoding: .utf8) ?? "[]"
+
+ return MCPToolResult(text: json)
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier1/ListRelationshipsTool.swift b/macos/Services/MCP/Tools/Tier1/ListRelationshipsTool.swift
new file mode 100644
index 0000000..63c9a89
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier1/ListRelationshipsTool.swift
@@ -0,0 +1,104 @@
+// ListRelationshipsTool.swift
+// Gridex
+//
+// MCP Tool: List foreign key relationships for a table.
+
+import Foundation
+
+struct ListRelationshipsTool: MCPTool {
+ let name = "list_relationships"
+ let description = "List foreign key relationships for a table. Returns both incoming and outgoing references."
+ let tier = MCPPermissionTier.schema
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "table_name": [
+ "type": "string",
+ "description": "Name of the table"
+ ]
+ ],
+ "required": ["connection_id", "table_name"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let tableName = params["table_name"]?.stringValue else {
+ throw MCPToolError.invalidParameters("table_name is required")
+ }
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, _) = try await context.getAdapter(for: connectionId)
+
+ // Get outgoing foreign keys (this table references other tables)
+ let outgoing = try await adapter.listForeignKeys(table: tableName, schema: nil)
+
+ // For incoming relationships, we need to scan all tables
+ // This is expensive, so we'll do it if possible
+ var incoming: [ForeignKeyInfo] = []
+ let allTables = try await adapter.listTables(schema: nil)
+
+ for table in allTables where table.name != tableName {
+ let fks = try await adapter.listForeignKeys(table: table.name, schema: nil)
+ for fk in fks where fk.referencedTable == tableName {
+ incoming.append(ForeignKeyInfo(
+ name: fk.name,
+ columns: fk.columns,
+ referencedTable: table.name, // The table that references us
+ referencedColumns: fk.referencedColumns,
+ onDelete: fk.onDelete,
+ onUpdate: fk.onUpdate
+ ))
+ }
+ }
+
+ var result: [String: Any] = [
+ "table": tableName
+ ]
+
+ // Outgoing relationships
+ if !outgoing.isEmpty {
+ var outList: [[String: Any]] = []
+ for fk in outgoing {
+ outList.append([
+ "name": fk.name ?? "",
+ "columns": fk.columns,
+ "references_table": fk.referencedTable,
+ "references_columns": fk.referencedColumns
+ ])
+ }
+ result["outgoing"] = outList
+ } else {
+ result["outgoing"] = "None"
+ }
+
+ // Incoming relationships
+ if !incoming.isEmpty {
+ var inList: [[String: Any]] = []
+ for fk in incoming {
+ inList.append([
+ "from_table": fk.referencedTable,
+ "from_columns": fk.columns,
+ "to_columns": fk.referencedColumns
+ ])
+ }
+ result["incoming"] = inList
+ } else {
+ result["incoming"] = "None"
+ }
+
+ let data = try JSONSerialization.data(withJSONObject: result, options: [.prettyPrinted, .sortedKeys])
+ let json = String(data: data, encoding: .utf8) ?? "{}"
+
+ return MCPToolResult(text: json)
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier1/ListSchemasTool.swift b/macos/Services/MCP/Tools/Tier1/ListSchemasTool.swift
new file mode 100644
index 0000000..d0d8b61
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier1/ListSchemasTool.swift
@@ -0,0 +1,52 @@
+// ListSchemasTool.swift
+// Gridex
+//
+// MCP Tool: List schemas/databases available in a connection.
+
+import Foundation
+
+struct ListSchemasTool: MCPTool {
+ let name = "list_schemas"
+ let description = "List schemas/databases available in a connection."
+ let tier = MCPPermissionTier.schema
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ]
+ ],
+ "required": ["connection_id"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, config) = try await context.getAdapter(for: connectionId)
+
+ // For databases that support schemas (PostgreSQL, MSSQL)
+ if config.databaseType.supportsSchemas {
+ let schemas = try await adapter.listSchemas(database: nil)
+ if schemas.isEmpty {
+ return MCPToolResult(text: "No schemas found.")
+ }
+ let json = try JSONEncoder().encode(schemas)
+ return MCPToolResult(text: "Schemas: " + (String(data: json, encoding: .utf8) ?? "[]"))
+ }
+
+ // For MySQL and others, list databases
+ let databases = try await adapter.listDatabases()
+ if databases.isEmpty {
+ return MCPToolResult(text: "No databases found.")
+ }
+ let json = try JSONEncoder().encode(databases)
+ return MCPToolResult(text: "Databases: " + (String(data: json, encoding: .utf8) ?? "[]"))
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier1/ListTablesTool.swift b/macos/Services/MCP/Tools/Tier1/ListTablesTool.swift
new file mode 100644
index 0000000..44ab813
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier1/ListTablesTool.swift
@@ -0,0 +1,69 @@
+// ListTablesTool.swift
+// Gridex
+//
+// MCP Tool: List all tables in a database connection.
+
+import Foundation
+
+struct ListTablesTool: MCPTool {
+ let name = "list_tables"
+ let description = "List all tables in a database connection. Returns table names, schemas, and approximate row counts."
+ let tier = MCPPermissionTier.schema
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "schema": [
+ "type": "string",
+ "description": "Optional schema/database filter"
+ ]
+ ],
+ "required": ["connection_id"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, _) = try await context.getAdapter(for: connectionId)
+ let schemaFilter = params["schema"]?.stringValue
+
+ let tables = try await adapter.listTables(schema: schemaFilter)
+
+ var result: [[String: Any]] = []
+ for table in tables {
+ var entry: [String: Any] = [
+ "name": table.name,
+ "type": table.type.rawValue
+ ]
+ if let schema = table.schema {
+ entry["schema"] = schema
+ }
+ if let rowCount = table.estimatedRowCount {
+ entry["estimated_rows"] = rowCount
+ }
+ result.append(entry)
+ }
+
+ if result.isEmpty {
+ return MCPToolResult(text: "No tables found" + (schemaFilter.map { " in schema '\($0)'" } ?? "") + ".")
+ }
+
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(result.map { dict -> [String: String] in
+ dict.mapValues { "\($0)" }
+ })
+ let json = String(data: data, encoding: .utf8) ?? "[]"
+
+ return MCPToolResult(text: "Found \(result.count) table(s):\n\(json)")
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift b/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
new file mode 100644
index 0000000..0499315
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
@@ -0,0 +1,74 @@
+// ExplainQueryTool.swift
+// Gridex
+//
+// MCP Tool: Get EXPLAIN plan for a query without executing it.
+
+import Foundation
+
+struct ExplainQueryTool: MCPTool {
+ let name = "explain_query"
+ let description = "Get EXPLAIN plan for a query without executing it. Helps AI understand query performance."
+ let tier = MCPPermissionTier.read
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "sql": [
+ "type": "string",
+ "description": "SQL query to explain"
+ ]
+ ],
+ "required": ["connection_id", "sql"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let sql = params["sql"]?.stringValue else {
+ throw MCPToolError.invalidParameters("sql is required")
+ }
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, config) = try await context.getAdapter(for: connectionId)
+
+ // Build EXPLAIN query based on database type
+ let explainSQL: String
+ switch config.databaseType {
+ case .postgresql:
+ explainSQL = "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) \(sql)"
+ case .mysql:
+ explainSQL = "EXPLAIN \(sql)"
+ case .sqlite:
+ explainSQL = "EXPLAIN QUERY PLAN \(sql)"
+ case .mssql:
+ // SQL Server uses SET SHOWPLAN_TEXT or estimated plan
+ explainSQL = "SET SHOWPLAN_TEXT ON; \(sql); SET SHOWPLAN_TEXT OFF"
+ case .mongodb, .redis:
+ return MCPToolResult(text: "EXPLAIN is not supported for \(config.databaseType.displayName) connections.", isError: true)
+ }
+
+ let result = try await adapter.executeRaw(sql: explainSQL)
+
+ // Format the explain output
+ var output = "Query Plan for: \(sql)\n\n"
+
+ if result.rows.isEmpty {
+ output += "No plan information available."
+ } else {
+ for row in result.rows {
+ let line = row.map(\.displayString).joined(separator: " | ")
+ output += line + "\n"
+ }
+ }
+
+ return MCPToolResult(text: output)
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier2/QueryTool.swift b/macos/Services/MCP/Tools/Tier2/QueryTool.swift
new file mode 100644
index 0000000..0507439
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier2/QueryTool.swift
@@ -0,0 +1,152 @@
+// QueryTool.swift
+// Gridex
+//
+// MCP Tool: Execute a SQL query with read-only enforcement.
+
+import Foundation
+
+struct QueryTool: MCPTool {
+ let name = "query"
+ let description = "Execute a SQL query. In read-only mode, only SELECT statements are allowed. Returns rows with metadata (column types, row count, execution time)."
+ let tier = MCPPermissionTier.read
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "sql": [
+ "type": "string",
+ "description": "SQL query. Use parameterized placeholders."
+ ],
+ "params": [
+ "type": "array",
+ "description": "Parameters for placeholders"
+ ],
+ "row_limit": [
+ "type": "integer",
+ "description": "Maximum rows to return (default 1000, max 10000)",
+ "default": 1000,
+ "maximum": 10000
+ ]
+ ],
+ "required": ["connection_id", "sql"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let sql = params["sql"]?.stringValue else {
+ throw MCPToolError.invalidParameters("sql is required")
+ }
+
+ let rowLimit = min(10000, max(1, params["row_limit"]?.intValue ?? 1000))
+
+ // Check basic permission
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ // Check connection mode for read-only enforcement
+ let mode = await context.permissionEngine.getMode(for: connectionId)
+ if mode == .readOnly {
+ let readOnlyCheck = await context.permissionEngine.validateReadOnlyQuery(sql)
+ if let error = readOnlyCheck.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+ }
+
+ let (adapter, config) = try await context.getAdapter(for: connectionId)
+
+ // Apply row limit if not already present
+ var limitedSQL = sql
+ let upperSQL = sql.uppercased()
+ if !upperSQL.contains("LIMIT") && config.databaseType.isSQL {
+ limitedSQL = "\(sql.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: CharacterSet(charactersIn: ";"))) LIMIT \(rowLimit)"
+ }
+
+ // Extract parameters
+ var queryParams: [RowValue] = []
+ if let paramsArray = params["params"]?.arrayValue {
+ for p in paramsArray {
+ queryParams.append(jsonValueToRowValue(p))
+ }
+ }
+
+ let startTime = Date()
+ let result: QueryResult
+
+ if queryParams.isEmpty {
+ result = try await adapter.executeRaw(sql: limitedSQL)
+ } else {
+ result = try await adapter.executeWithRowValues(sql: limitedSQL, parameters: queryParams)
+ }
+
+ let durationMs = Int(Date().timeIntervalSince(startTime) * 1000)
+
+ // Format response
+ var response: [String: Any] = [
+ "success": true,
+ "row_count": result.rowCount,
+ "execution_time_ms": durationMs,
+ "query_type": result.queryType.rawValue
+ ]
+
+ if result.rowsAffected > 0 {
+ response["rows_affected"] = result.rowsAffected
+ }
+
+ // Include columns metadata
+ response["columns"] = result.columns.map { col -> [String: Any] in
+ var c: [String: Any] = [
+ "name": col.name,
+ "type": col.dataType
+ ]
+ if col.isNullable { c["nullable"] = true }
+ return c
+ }
+
+ // Include rows (limited)
+ var rows: [[String: String]] = []
+ for row in result.rows.prefix(rowLimit) {
+ var rowDict: [String: String] = [:]
+ for (idx, col) in result.columns.enumerated() {
+ if idx < row.count {
+ rowDict[col.name] = row[idx].displayString
+ }
+ }
+ rows.append(rowDict)
+ }
+ response["rows"] = rows
+
+ if result.rowCount > rowLimit {
+ response["truncated"] = true
+ response["message"] = "Results truncated to \(rowLimit) rows"
+ }
+
+ let data = try JSONSerialization.data(withJSONObject: response, options: [.prettyPrinted, .sortedKeys])
+ let json = String(data: data, encoding: .utf8) ?? "{}"
+
+ return MCPToolResult(text: json)
+ }
+
+ private func jsonValueToRowValue(_ value: JSONValue) -> RowValue {
+ switch value {
+ case .null: return .null
+ case .bool(let b): return .boolean(b)
+ case .int(let i): return .integer(Int64(i))
+ case .double(let d): return .double(d)
+ case .string(let s): return .string(s)
+ case .array, .object:
+ let encoder = JSONEncoder()
+ if let data = try? encoder.encode(value),
+ let str = String(data: data, encoding: .utf8) {
+ return .json(str)
+ }
+ return .null
+ }
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.swift b/macos/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.swift
new file mode 100644
index 0000000..61d0db2
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.swift
@@ -0,0 +1,99 @@
+// SearchAcrossTablesTool.swift
+// Gridex
+//
+// MCP Tool: Search for a keyword across table names, column names, and column comments.
+
+import Foundation
+
+struct SearchAcrossTablesTool: MCPTool {
+ let name = "search_across_tables"
+ let description = "Search for a keyword across table names, column names, and column comments. Useful for discovering relevant data."
+ let tier = MCPPermissionTier.read
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "keyword": [
+ "type": "string",
+ "description": "Keyword to search for"
+ ]
+ ],
+ "required": ["connection_id", "keyword"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let keyword = params["keyword"]?.stringValue else {
+ throw MCPToolError.invalidParameters("keyword is required")
+ }
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, _) = try await context.getAdapter(for: connectionId)
+
+ let searchTerm = keyword.lowercased()
+ var matches: [[String: Any]] = []
+
+ let tables = try await adapter.listTables(schema: nil)
+
+ for table in tables {
+ // Check table name
+ if table.name.lowercased().contains(searchTerm) {
+ matches.append([
+ "type": "table",
+ "table": table.name,
+ "match": table.name
+ ])
+ }
+
+ // Check columns
+ let tableDesc = try await adapter.describeTable(name: table.name, schema: nil)
+ for column in tableDesc.columns {
+ if column.name.lowercased().contains(searchTerm) {
+ matches.append([
+ "type": "column",
+ "table": table.name,
+ "column": column.name,
+ "data_type": column.dataType
+ ])
+ }
+
+ // Check column comment if available
+ if let comment = column.comment, comment.lowercased().contains(searchTerm) {
+ matches.append([
+ "type": "column_comment",
+ "table": table.name,
+ "column": column.name,
+ "comment": comment
+ ])
+ }
+ }
+
+ // Check table comment if available
+ if let comment = tableDesc.comment, comment.lowercased().contains(searchTerm) {
+ matches.append([
+ "type": "table_comment",
+ "table": table.name,
+ "comment": comment
+ ])
+ }
+ }
+
+ if matches.isEmpty {
+ return MCPToolResult(text: "No matches found for '\(keyword)'.")
+ }
+
+ let data = try JSONSerialization.data(withJSONObject: matches, options: [.prettyPrinted, .sortedKeys])
+ let json = String(data: data, encoding: .utf8) ?? "[]"
+
+ return MCPToolResult(text: "Found \(matches.count) match(es) for '\(keyword)':\n\(json)")
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier3/DeleteRowsTool.swift b/macos/Services/MCP/Tools/Tier3/DeleteRowsTool.swift
new file mode 100644
index 0000000..97138d0
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier3/DeleteRowsTool.swift
@@ -0,0 +1,91 @@
+// DeleteRowsTool.swift
+// Gridex
+//
+// MCP Tool: Delete rows from a table. Requires user approval and WHERE clause.
+
+import Foundation
+
+struct DeleteRowsTool: MCPTool {
+ let name = "delete_rows"
+ let description = "Delete rows matching WHERE clause. Requires user approval. WHERE clause is MANDATORY."
+ let tier = MCPPermissionTier.write
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "table_name": [
+ "type": "string",
+ "description": "Name of the table to delete from (letters, digits, underscore only)"
+ ],
+ "schema": [
+ "type": "string",
+ "description": "Optional schema name (letters, digits, underscore only)"
+ ],
+ "where": [
+ "type": "string",
+ "description": "WHERE clause (required). Must not contain ';', '--', '/*', or '*/'."
+ ],
+ "where_params": [
+ "type": "array",
+ "description": "Parameters for WHERE clause placeholders"
+ ]
+ ],
+ "required": ["connection_id", "table_name", "where"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+ let (tableName, schemaName) = try MCPIdentifierValidator.extractTableAndSchema(from: params)
+
+ guard let whereClause = params["where"]?.stringValue else {
+ throw MCPToolError.invalidParameters("where clause is required. Bare DELETE without WHERE is not allowed.")
+ }
+
+ if let error = await context.permissionEngine.validateWhereClause(whereClause).errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, config) = try await context.getAdapter(for: connectionId)
+ let qualifiedTable = config.databaseType.sqlDialect.qualifiedIdentifier(tableName, schema: schemaName)
+ let deleteSQL = "DELETE FROM \(qualifiedTable) WHERE \(whereClause)"
+
+ let estimatedRows = await MCPRowCountEstimator.estimate(
+ adapter: adapter,
+ qualifiedTable: qualifiedTable,
+ whereClause: whereClause,
+ config: config
+ )
+
+ if permission.requiresUserApproval {
+ let details = """
+ SQL: \(deleteSQL)
+
+ Estimated rows to delete: \(estimatedRows)
+
+ ⚠️ This operation cannot be undone!
+ """
+
+ let approved = await context.requestApproval(
+ tool: name,
+ description: "Delete rows from '\(tableName)' where \(whereClause)",
+ details: details,
+ connectionId: connectionId
+ )
+ if !approved {
+ throw MCPToolError.permissionDenied("User denied the operation.")
+ }
+ }
+
+ let result = try await adapter.executeRaw(sql: deleteSQL)
+ return MCPToolResult(text: "Successfully deleted \(result.rowsAffected) row(s) from '\(tableName)'.")
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.swift b/macos/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.swift
new file mode 100644
index 0000000..2f46bdb
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.swift
@@ -0,0 +1,123 @@
+// ExecuteWriteQueryTool.swift
+// Gridex
+//
+// MCP Tool: Execute arbitrary write SQL. Requires user approval.
+
+import Foundation
+
+struct ExecuteWriteQueryTool: MCPTool {
+ let name = "execute_write_query"
+ let description = "Execute one write SQL statement (INSERT/UPDATE/DELETE). Requires user approval. Only available in read-write mode. Multi-statement input is rejected."
+ let tier = MCPPermissionTier.write
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "sql": [
+ "type": "string",
+ "description": "A single SQL statement to execute. Must not contain multiple statements."
+ ],
+ "params": [
+ "type": "array",
+ "description": "Parameters for placeholders"
+ ]
+ ],
+ "required": ["connection_id", "sql"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let sql = params["sql"]?.stringValue else {
+ throw MCPToolError.invalidParameters("sql is required")
+ }
+
+ // Syntactic checks run against a comment/literal-stripped copy so
+ // payloads hidden in comments or string literals can't fool them.
+ // The ORIGINAL sql is still what gets executed.
+ let codeOnly = MCPSQLSanitizer.stripCommentsAndStrings(sql)
+ let upperCode = codeOnly.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
+
+ let withoutTrailingSemi = upperCode.hasSuffix(";")
+ ? String(upperCode.dropLast()).trimmingCharacters(in: .whitespacesAndNewlines)
+ : upperCode
+ if withoutTrailingSemi.contains(";") {
+ throw MCPToolError.invalidParameters("Multiple statements are not allowed. Send one statement at a time.")
+ }
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ if upperCode.hasPrefix("SELECT") || upperCode.hasPrefix("WITH") {
+ throw MCPToolError.invalidParameters("Use the 'query' tool for SELECT / WITH statements. This tool is for write operations only.")
+ }
+
+ if upperCode.hasPrefix("UPDATE") || upperCode.hasPrefix("DELETE") {
+ let range = NSRange(upperCode.startIndex..., in: upperCode)
+ if Self.whereRegex.firstMatch(in: upperCode, options: [], range: range) == nil {
+ throw MCPToolError.permissionDenied("UPDATE/DELETE without WHERE clause is not allowed.")
+ }
+ if let whereRange = codeOnly.range(of: "WHERE", options: .caseInsensitive) {
+ let whereClause = String(codeOnly[whereRange.upperBound...])
+ .trimmingCharacters(in: .whitespaces)
+ if let error = await context.permissionEngine.validateWhereClause(whereClause).errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+ }
+ }
+
+ let (adapter, _) = try await context.getAdapter(for: connectionId)
+
+ if permission.requiresUserApproval {
+ let approved = await context.requestApproval(
+ tool: name,
+ description: "Execute write query",
+ details: "SQL:\n\(sql)",
+ connectionId: connectionId
+ )
+ if !approved {
+ throw MCPToolError.permissionDenied("User denied the operation.")
+ }
+ }
+
+ let queryParams = params["params"]?.arrayValue ?? []
+ let result: QueryResult
+ if queryParams.isEmpty {
+ result = try await adapter.executeRaw(sql: sql)
+ } else {
+ let rowParams = queryParams.map { jsonValueToRowValue($0) }
+ result = try await adapter.executeWithRowValues(sql: sql, parameters: rowParams)
+ }
+
+ var response = "Query executed successfully."
+ if result.rowsAffected > 0 {
+ response += " \(result.rowsAffected) row(s) affected."
+ }
+ return MCPToolResult(text: response)
+ }
+
+ private static let whereRegex = try! NSRegularExpression(pattern: "\\bWHERE\\b", options: .caseInsensitive)
+
+ private func jsonValueToRowValue(_ value: JSONValue) -> RowValue {
+ switch value {
+ case .null: return .null
+ case .bool(let b): return .boolean(b)
+ case .int(let i): return .integer(Int64(i))
+ case .double(let d): return .double(d)
+ case .string(let s): return .string(s)
+ case .array, .object:
+ let encoder = JSONEncoder()
+ if let data = try? encoder.encode(value),
+ let str = String(data: data, encoding: .utf8) {
+ return .json(str)
+ }
+ return .null
+ }
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier3/InsertRowsTool.swift b/macos/Services/MCP/Tools/Tier3/InsertRowsTool.swift
new file mode 100644
index 0000000..18de650
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier3/InsertRowsTool.swift
@@ -0,0 +1,117 @@
+// InsertRowsTool.swift
+// Gridex
+//
+// MCP Tool: Insert rows into a table. Requires user approval.
+
+import Foundation
+
+struct InsertRowsTool: MCPTool {
+ let name = "insert_rows"
+ let description = "Insert one or more rows into a table. Requires user approval. Returns affected count."
+ let tier = MCPPermissionTier.write
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "table_name": [
+ "type": "string",
+ "description": "Name of the table to insert into"
+ ],
+ "schema": [
+ "type": "string",
+ "description": "Optional schema name"
+ ],
+ "rows": [
+ "type": "array",
+ "description": "Array of row objects to insert",
+ "items": ["type": "object"]
+ ]
+ ],
+ "required": ["connection_id", "table_name", "rows"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+
+ guard let tableName = params["table_name"]?.stringValue else {
+ throw MCPToolError.invalidParameters("table_name is required")
+ }
+
+ guard let rowsArray = params["rows"]?.arrayValue, !rowsArray.isEmpty else {
+ throw MCPToolError.invalidParameters("rows must be a non-empty array")
+ }
+
+ // Check permission
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ // Requires approval
+ if permission.requiresUserApproval {
+ let approved = await context.requestApproval(
+ tool: name,
+ description: "Insert \(rowsArray.count) row(s) into '\(tableName)'",
+ details: formatRowsPreview(rowsArray),
+ connectionId: connectionId
+ )
+ if !approved {
+ throw MCPToolError.permissionDenied("User denied the operation.")
+ }
+ }
+
+ let (adapter, _) = try await context.getAdapter(for: connectionId)
+ let schemaName = params["schema"]?.stringValue
+
+ var insertedCount = 0
+
+ for rowValue in rowsArray {
+ guard let rowObj = rowValue.objectValue else { continue }
+
+ var values: [String: RowValue] = [:]
+ for (key, val) in rowObj {
+ values[key] = jsonValueToRowValue(val)
+ }
+
+ _ = try await adapter.insertRow(table: tableName, schema: schemaName, values: values)
+ insertedCount += 1
+ }
+
+ return MCPToolResult(text: "Successfully inserted \(insertedCount) row(s) into '\(tableName)'.")
+ }
+
+ private func formatRowsPreview(_ rows: [JSONValue]) -> String {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let previewRows = Array(rows.prefix(5))
+ if let data = try? encoder.encode(previewRows),
+ let str = String(data: data, encoding: .utf8) {
+ if rows.count > 5 {
+ return str + "\n... and \(rows.count - 5) more rows"
+ }
+ return str
+ }
+ return "\(rows.count) rows"
+ }
+
+ private func jsonValueToRowValue(_ value: JSONValue) -> RowValue {
+ switch value {
+ case .null: return .null
+ case .bool(let b): return .boolean(b)
+ case .int(let i): return .integer(Int64(i))
+ case .double(let d): return .double(d)
+ case .string(let s): return .string(s)
+ case .array, .object:
+ let encoder = JSONEncoder()
+ if let data = try? encoder.encode(value),
+ let str = String(data: data, encoding: .utf8) {
+ return .json(str)
+ }
+ return .null
+ }
+ }
+}
diff --git a/macos/Services/MCP/Tools/Tier3/UpdateRowsTool.swift b/macos/Services/MCP/Tools/Tier3/UpdateRowsTool.swift
new file mode 100644
index 0000000..3aa2c1a
--- /dev/null
+++ b/macos/Services/MCP/Tools/Tier3/UpdateRowsTool.swift
@@ -0,0 +1,129 @@
+// UpdateRowsTool.swift
+// Gridex
+//
+// MCP Tool: Update rows in a table. Requires user approval and WHERE clause.
+
+import Foundation
+
+struct UpdateRowsTool: MCPTool {
+ let name = "update_rows"
+ let description = "Update rows matching WHERE clause. Requires user approval. WHERE clause is MANDATORY (no bare UPDATE)."
+ let tier = MCPPermissionTier.write
+
+ let inputSchema: [String: Any] = [
+ "type": "object",
+ "properties": [
+ "connection_id": [
+ "type": "string",
+ "description": "Connection identifier"
+ ],
+ "table_name": [
+ "type": "string",
+ "description": "Name of the table to update (letters, digits, underscore only)"
+ ],
+ "schema": [
+ "type": "string",
+ "description": "Optional schema name (letters, digits, underscore only)"
+ ],
+ "set": [
+ "type": "object",
+ "description": "Column-value pairs to update. Column names must be letters, digits, underscore only."
+ ],
+ "where": [
+ "type": "string",
+ "description": "WHERE clause (required). Must not contain ';', '--', '/*', or '*/'."
+ ],
+ "where_params": [
+ "type": "array",
+ "description": "Parameters for WHERE clause placeholders"
+ ]
+ ],
+ "required": ["connection_id", "table_name", "set", "where"]
+ ]
+
+ func execute(params: JSONValue, context: MCPToolContext) async throws -> MCPToolResult {
+ let connectionId = try extractConnectionId(from: params)
+ let (tableName, schemaName) = try MCPIdentifierValidator.extractTableAndSchema(from: params)
+
+ guard let setObj = params["set"]?.objectValue, !setObj.isEmpty else {
+ throw MCPToolError.invalidParameters("set must be a non-empty object with column-value pairs")
+ }
+ for key in setObj.keys {
+ try MCPIdentifierValidator.validate(key, as: "column name")
+ }
+
+ guard let whereClause = params["where"]?.stringValue else {
+ throw MCPToolError.invalidParameters("where clause is required. Bare UPDATE without WHERE is not allowed.")
+ }
+
+ if let error = await context.permissionEngine.validateWhereClause(whereClause).errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let permission = await context.checkPermission(tier: tier, connectionId: connectionId)
+ if let error = permission.errorMessage {
+ throw MCPToolError.permissionDenied(error)
+ }
+
+ let (adapter, config) = try await context.getAdapter(for: connectionId)
+ let dialect = config.databaseType.sqlDialect
+ let qualifiedTable = dialect.qualifiedIdentifier(tableName, schema: schemaName)
+
+ // Values are still inlined here because executeRaw takes a single string.
+ // A future refactor should bind parameters via executeWithRowValues.
+ let setClause = setObj.map { key, val in
+ "\(dialect.quoteIdentifier(key)) = \(formatValueForSQL(val, dialect: dialect))"
+ }.joined(separator: ", ")
+
+ let updateSQL = "UPDATE \(qualifiedTable) SET \(setClause) WHERE \(whereClause)"
+
+ let estimatedRows = await MCPRowCountEstimator.estimate(
+ adapter: adapter,
+ qualifiedTable: qualifiedTable,
+ whereClause: whereClause,
+ config: config
+ )
+
+ if permission.requiresUserApproval {
+ let details = """
+ SQL: \(updateSQL)
+
+ Estimated rows affected: \(estimatedRows)
+ """
+
+ let approved = await context.requestApproval(
+ tool: name,
+ description: "Update rows in '\(tableName)' where \(whereClause)",
+ details: details,
+ connectionId: connectionId
+ )
+ if !approved {
+ throw MCPToolError.permissionDenied("User denied the operation.")
+ }
+ }
+
+ let result = try await adapter.executeRaw(sql: updateSQL)
+ return MCPToolResult(text: "Successfully updated \(result.rowsAffected) row(s) in '\(tableName)'.")
+ }
+
+ private func formatValueForSQL(_ value: JSONValue, dialect: SQLDialect) -> String {
+ switch value {
+ case .null: return "NULL"
+ case .bool(let b):
+ return dialect == .postgresql ? (b ? "true" : "false") : (b ? "1" : "0")
+ case .int(let i): return "\(i)"
+ case .double(let d): return "\(d)"
+ case .string(let s):
+ let escaped = s.replacingOccurrences(of: "'", with: "''")
+ return "'\(escaped)'"
+ case .array, .object:
+ let encoder = JSONEncoder()
+ if let data = try? encoder.encode(value),
+ let str = String(data: data, encoding: .utf8) {
+ let escaped = str.replacingOccurrences(of: "'", with: "''")
+ return "'\(escaped)'"
+ }
+ return "NULL"
+ }
+ }
+}
diff --git a/macos/Services/MCP/Transport/StdioTransport.swift b/macos/Services/MCP/Transport/StdioTransport.swift
new file mode 100644
index 0000000..9bad02a
--- /dev/null
+++ b/macos/Services/MCP/Transport/StdioTransport.swift
@@ -0,0 +1,103 @@
+// StdioTransport.swift
+// Gridex
+//
+// MCP stdio transport for communication with AI clients.
+
+import Foundation
+
+actor StdioTransport {
+ private var isRunning = false
+ private var inputTask: Task<Void, Never>?
+ private let encoder: JSONEncoder
+ private let decoder: JSONDecoder
+
+ private weak var _delegate: StdioTransportDelegate?
+
+ init() {
+ self.encoder = JSONEncoder()
+ self.encoder.outputFormatting = .sortedKeys
+
+ self.decoder = JSONDecoder()
+ }
+
+ func setDelegate(_ delegate: StdioTransportDelegate?) {
+ _delegate = delegate
+ }
+
+ func start() async {
+ guard !isRunning else { return }
+ isRunning = true
+
+ inputTask = Task { [weak self] in
+ await self?.readLoop()
+ }
+ }
+
+ func stop() async {
+ isRunning = false
+ inputTask?.cancel()
+ inputTask = nil
+ }
+
+ private func readLoop() async {
+ while isRunning && !Task.isCancelled {
+ guard let line = readLine() else {
+ // EOF
+ break
+ }
+
+ guard !line.isEmpty else { continue }
+
+ do {
+ guard let data = line.data(using: .utf8) else { continue }
+ let request = try decoder.decode(JSONRPCRequest.self, from: data)
+ await _delegate?.transport(self, didReceiveRequest: request)
+ } catch {
+ let errorResponse = JSONRPCResponse(id: nil, error: .parseError)
+ await send(errorResponse)
+ }
+ }
+ }
+
+ func send(_ response: JSONRPCResponse) async {
+ do {
+ let data = try encoder.encode(response)
+ guard var line = String(data: data, encoding: .utf8) else { return }
+ line.append("\n")
+
+ if let outputData = line.data(using: .utf8) {
+ FileHandle.standardOutput.write(outputData)
+ }
+ } catch {
+ print("[MCP Transport] Failed to send response: \(error)", to: &standardError)
+ }
+ }
+
+ func sendNotification(method: String, params: JSONValue?) async {
+ let notification = JSONRPCRequest(id: nil, method: method, params: params)
+ do {
+ let data = try encoder.encode(notification)
+ guard var line = String(data: data, encoding: .utf8) else { return }
+ line.append("\n")
+
+ if let outputData = line.data(using: .utf8) {
+ FileHandle.standardOutput.write(outputData)
+ }
+ } catch {
+ print("[MCP Transport] Failed to send notification: \(error)", to: &standardError)
+ }
+ }
+}
+
+protocol StdioTransportDelegate: AnyObject, Sendable {
+ func transport(_ transport: StdioTransport, didReceiveRequest request: JSONRPCRequest) async
+}
+
+// Helper for writing to stderr
+private var standardError = StandardErrorOutputStream()
+
+private struct StandardErrorOutputStream: TextOutputStream {
+ mutating func write(_ string: String) {
+ FileHandle.standardError.write(Data(string.utf8))
+ }
+}
diff --git a/scripts/test-mcp.sh b/scripts/test-mcp.sh
new file mode 100755
index 0000000..f3ab1df
--- /dev/null
+++ b/scripts/test-mcp.sh
@@ -0,0 +1,73 @@
+#!/bin/bash
+# Test MCP server functionality
+# Usage: ./scripts/test-mcp.sh
+
+set -e
+
+GRIDEX_BIN="${1:-.build/debug/Gridex}"
+
+echo "Testing Gridex MCP Server..."
+echo "Binary: $GRIDEX_BIN"
+echo ""
+
+# Create a named pipe for communication
+PIPE_IN=$(mktemp -u)
+PIPE_OUT=$(mktemp -u)
+mkfifo "$PIPE_IN"
+mkfifo "$PIPE_OUT"
+
+# Cleanup on exit
+cleanup() {
+ rm -f "$PIPE_IN" "$PIPE_OUT"
+ [ -n "$MCP_PID" ] && kill "$MCP_PID" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+# Start MCP server in background
+"$GRIDEX_BIN" --mcp-stdio < "$PIPE_IN" > "$PIPE_OUT" 2>/dev/null &
+MCP_PID=$!
+
+# Give it a moment to start
+sleep 1
+
+# Check if process is running
+if ! kill -0 "$MCP_PID" 2>/dev/null; then
+ echo "ERROR: MCP server failed to start"
+ exit 1
+fi
+
+echo "MCP server started (PID: $MCP_PID)"
+
+# Send initialize request
+echo "Sending initialize request..."
+echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"test-client","version":"1.0.0"}}}' > "$PIPE_IN" &
+
+# Read response with timeout
+RESPONSE=$(timeout 5 head -n 1 "$PIPE_OUT" 2>/dev/null || echo "TIMEOUT")
+
+if [ "$RESPONSE" = "TIMEOUT" ]; then
+ echo "ERROR: No response from MCP server (timeout)"
+ exit 1
+fi
+
+echo "Response: $RESPONSE"
+
+# Check for success
+if echo "$RESPONSE" | grep -q '"result"'; then
+ echo ""
+ echo "SUCCESS: MCP server is responding correctly!"
+ echo ""
+ echo "You can now configure your AI client with:"
+ echo ""
+ echo '{
+ "mcpServers": {
+ "gridex": {
+ "command": "'$(realpath "$GRIDEX_BIN")'",
+ "args": ["--mcp-stdio"]
+ }
+ }
+}'
+else
+ echo "ERROR: Unexpected response"
+ exit 1
+fi