diff --git a/CLI/MCPBackend.swift b/CLI/MCPBackend.swift new file mode 100644 index 000000000000..ad73e27135e1 --- /dev/null +++ b/CLI/MCPBackend.swift @@ -0,0 +1,302 @@ +// MCPBackend.swift +// Backend for communicating with cmux daemon via direct Unix socket + +import Foundation + +/// Backend for communicating with cmux daemon via Unix socket v2 RPC. +/// +/// Sends JSON requests directly to the cmux socket instead of spawning CLI +/// subprocesses. This eliminates CLI flag incompatibilities and subprocess overhead. +/// +/// ## Why POSIX syscalls instead of FileHandle +/// +/// On macOS, `FileHandle` (`NSConcreteFileHandle`) is Apple's closed-source +/// Foundation implementation. When wrapping a Unix domain socket fd, +/// `FileHandle.write(_:)` does **not** reliably flush data to the socket — +/// the bytes can remain in an internal buffer, causing the subsequent +/// `readData(ofLength:)` to block forever (the daemon never receives the +/// request so it never sends a response). +/// +/// This was confirmed empirically: +/// - `FileHandle.write` + `FileHandle.readData` → **hangs indefinitely** +/// - `Darwin.write` + `Darwin.read` on the same fd → **works correctly** +/// +/// Apple's own networking guidance (TN3151) recommends against using +/// `NSFileHandle` for socket I/O. The `eonil/TCPIPSocket.Swift` project +/// also documents this caveat. We therefore use direct POSIX `read`/`write` +/// syscalls with proper EINTR retry and short-write handling, following the +/// pattern recommended by Apple DTS (Quinn "The Eskimo!"). +public class MCPBackend { + + // MARK: - Properties + + private let socketPath: String + private let password: String? + private let lock = NSLock() + private var requestId: Int = 0 + + /// Raw file descriptor for the connected Unix domain socket. + /// -1 means not connected. Managed directly via POSIX syscalls + /// (not wrapped in FileHandle — see class-level doc for rationale). + private var socketFd: Int32 = -1 + + // MARK: - Initialization + + public init(socketPath: String = "/tmp/cmux.sock", password: String? = nil) { + self.socketPath = socketPath + self.password = password + } + + deinit { + disconnect() + } + + // MARK: - Connection Management + + /// Connect to the cmux Unix socket. + private func connect() throws { + disconnect() + + // Validate socket file ownership before connecting (security check). + // Refuse to connect if the socket is not owned by the current user, + // matching the same check in CLI/cmux.swift. + var st = stat() + guard stat(socketPath, &st) == 0 else { + throw MCPError.executionFailed("Socket not found at \(socketPath)") + } + guard st.st_uid == getuid() else { + throw MCPError.executionFailed("Socket at \(socketPath) is not owned by the current user — refusing to connect") + } + + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { + throw MCPError.transportError("Failed to create socket: \(String(cString: strerror(errno)))") + } + + var addr = sockaddr_un() + addr.sun_family = sa_family_t(AF_UNIX) + + let pathBytes = socketPath.utf8CString + guard pathBytes.count <= MemoryLayout.size(ofValue: addr.sun_path) else { + Darwin.close(fd) + throw MCPError.transportError("Socket path too long: \(socketPath)") + } + + withUnsafeMutablePointer(to: &addr.sun_path) { ptr in + ptr.withMemoryRebound(to: CChar.self, capacity: pathBytes.count) { dest in + for (i, byte) in pathBytes.enumerated() { + dest[i] = byte + } + } + } + + let addrLen = socklen_t(MemoryLayout.size) + let result = withUnsafePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPtr in + Darwin.connect(fd, sockPtr, addrLen) + } + } + + guard result == 0 else { + Darwin.close(fd) + throw MCPError.transportError("Failed to connect to \(socketPath): \(String(cString: strerror(errno)))") + } + + socketFd = fd + } + + /// Disconnect from the socket. + private func disconnect() { + if socketFd >= 0 { + Darwin.close(socketFd) + socketFd = -1 + } + } + + /// Ensure we have a live connection, reconnecting if needed. + private func ensureConnected() throws { + if socketFd < 0 { + try connect() + // Authenticate if password is set + if let password = password, !password.isEmpty { + let _ = try sendRPC(method: "auth.login", params: ["password": password]) + } + } + } + + // MARK: - POSIX I/O Helpers + + /// Write all bytes to the socket fd, retrying on EINTR and handling short writes. + /// + /// Follows the write-loop pattern recommended by Apple DTS for synchronous + /// socket I/O — see Apple Developer Forums thread 53192. + private func writeAll(_ data: Data) throws { + try data.withUnsafeBytes { rawBuffer in + guard let base = rawBuffer.baseAddress else { return } + var offset = 0 + var remaining = rawBuffer.count + while remaining > 0 { + let written = Darwin.write(socketFd, base + offset, remaining) + if written < 0 { + if errno == EINTR { continue } // interrupted by signal, retry + disconnect() + throw MCPError.transportError("Socket write failed: \(String(cString: strerror(errno)))") + } + if written == 0 { + disconnect() + throw MCPError.transportError("Socket write returned 0 (connection closed)") + } + offset += written + remaining -= written + } + } + } + + /// Read from the socket fd until a newline (`\n`) delimiter is found. + /// + /// Returns the data before the newline (newline itself is consumed but not included). + /// Uses a small stack buffer to minimize allocations for typical JSON responses. + /// - Parameter timeoutMs: Poll timeout in milliseconds. Pass -1 for no timeout. + private func readLine(timeoutMs: Int32) throws -> Data { + var buffer = Data() + let newline = UInt8(ascii: "\n") + var chunk = [UInt8](repeating: 0, count: 4096) + + while true { + var pollFd = pollfd(fd: socketFd, events: Int16(POLLIN), revents: 0) + let pollResult = poll(&pollFd, 1, timeoutMs) + if pollResult == 0 { + disconnect() + let secs = timeoutMs / 1000 + throw MCPError.transportError("Socket read timed out after \(secs)s") + } + if pollResult < 0 { + if errno == EINTR { continue } + disconnect() + throw MCPError.transportError("Socket poll failed: \(String(cString: strerror(errno)))") + } + + let bytesRead = Darwin.read(socketFd, &chunk, chunk.count) + if bytesRead < 0 { + if errno == EINTR { continue } // interrupted by signal, retry + disconnect() + throw MCPError.transportError("Socket read failed: \(String(cString: strerror(errno)))") + } + if bytesRead == 0 { + // EOF — connection closed by daemon + disconnect() + if buffer.isEmpty { + throw MCPError.transportError("Socket connection closed") + } + break + } + if let nlIndex = chunk[0.. [String: Any] { + lock.lock() + defer { lock.unlock() } + + // Try once, reconnect on transport failure only, try again. + // Non-transport errors (application errors from the daemon) are + // re-thrown immediately to avoid double-executing non-idempotent + // operations like create, close, send_text, etc. + do { + try ensureConnected() + return try sendRPC(method: method, params: params, timeoutMs: timeoutMs) + } catch MCPError.transportError { + // Connection may be stale — reconnect and retry once + disconnect() + try ensureConnected() + return try sendRPC(method: method, params: params, timeoutMs: timeoutMs) + } + } + + /// Low-level: send a single RPC request and read the response. + private func sendRPC(method: String, params: [String: Any], timeoutMs: Int32) throws -> [String: Any] { + guard socketFd >= 0 else { + throw MCPError.executionFailed("Not connected to socket") + } + + requestId += 1 + let request: [String: Any] = [ + "id": requestId, + "method": method, + "params": params + ] + + let requestData = try JSONSerialization.data(withJSONObject: request) + var payload = requestData + payload.append(contentsOf: "\n".utf8) + + try writeAll(payload) + + // Read response (newline-terminated JSON) + let responseData = try readLine(timeoutMs: timeoutMs) + + guard let response = try JSONSerialization.jsonObject(with: responseData) as? [String: Any] else { + throw MCPError.executionFailed("Invalid response from socket") + } + + // cmux socket v2: {ok: bool, result: ..., error: ...} + guard let ok = response["ok"] as? Bool else { + throw MCPError.executionFailed("Missing 'ok' field in socket response") + } + + if !ok { + let errorInfo = response["error"] + if let errDict = errorInfo as? [String: Any] { + let code = errDict["code"] as? String ?? "unknown" + let message = errDict["message"] as? String ?? "Unknown error" + throw MCPError.executionFailed("\(code): \(message)") + } else if let errStr = errorInfo as? String { + throw MCPError.executionFailed(errStr) + } + throw MCPError.executionFailed("Unknown socket error") + } + + // Return the result dict, or wrap non-dict results (arrays, strings, etc.) + if let result = response["result"] as? [String: Any] { + return result + } else if let result = response["result"] { + return ["value": result] + } + return [:] + } + + // MARK: - Convenience + + /// Perform an RPC call and return the result as a JSON string. + public func rpcJSON(method: String, params: [String: Any] = [:]) throws -> String { + let result = try rpc(method: method, params: params) + let data = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]) + return String(data: data, encoding: .utf8) ?? "{}" + } + + /// Perform an RPC call and return a formatted text result for MCP tool output. + public func rpcForTool(method: String, params: [String: Any] = [:], timeoutMs: Int32 = 120_000) throws -> MCPToolCallResult { + let result = try rpc(method: method, params: params, timeoutMs: timeoutMs) + let data = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys, .prettyPrinted]) + let text = String(data: data, encoding: .utf8) ?? "{}" + return MCPToolCallResult(content: [.text(text)]) + } + + public func ping() throws -> Bool { + let result = try rpc(method: "system.ping") + return result["pong"] as? Bool == true + } +} diff --git a/CLI/MCPMain.swift b/CLI/MCPMain.swift new file mode 100644 index 000000000000..73d5a8dbca8c --- /dev/null +++ b/CLI/MCPMain.swift @@ -0,0 +1,125 @@ +// MCPMain.swift +// MCP Server main entry point: stdio loop and CLI integration + +import Foundation + +// MARK: - MCP Server Mode + +/// MCP Server mode entry point +public func runMCPServer(socketPath: String = "/tmp/cmux.sock", password: String? = nil) { + // Initialize backend + let backend = MCPBackend(socketPath: socketPath, password: password) + + // Initialize tool registry + let toolRegistry = MCPToolRegistry(backend: backend) + + // Initialize protocol handler + let protocolHandler = MCPProtocol(toolRegistry: toolRegistry) + + // Run stdio loop + runStdIOLoop(protocolHandler: protocolHandler) +} + +// MARK: - stdio Loop + +/// Run the stdio message loop +private func runStdIOLoop(protocolHandler: MCPProtocol) { + let outputStream = FileHandle.standardOutput + let errorStream = FileHandle.standardError + + // Use Swift stdlib readLine() for line-buffered stdin reading + while let line = Swift.readLine(strippingNewline: true) { + let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { continue } + + guard let data = trimmed.data(using: .utf8) else { + continue + } + + do { + if let responseData = try protocolHandler.processMessage(data) { + var output = responseData + output.append(contentsOf: "\n".utf8) + outputStream.write(output) + } + } catch { + // Return a JSON-RPC error response so the client doesn't hang. + // Also log to stderr for debugging. + errorStream.write("MCP error: \(error)\n".data(using: .utf8) ?? Data()) + // Try to extract the request id for proper correlation + let requestId: JSONRPCId + if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let rawId = json["id"] { + if let intId = rawId as? Int { + requestId = .number(intId) + } else if let strId = rawId as? String { + requestId = .string(strId) + } else { + requestId = .number(0) + } + } else { + requestId = .number(0) + } + let errResp = JSONRPCErrorResponse( + id: requestId, + error: JSONRPCError( + code: JSONRPCErrorCode.internalError.rawValue, + message: "Internal error: \(error.localizedDescription)" + ) + ) + if let errData = try? JSONEncoder().encode(errResp) { + var output = errData + output.append(contentsOf: "\n".utf8) + outputStream.write(output) + } + } + } +} + +// MARK: - CLI Integration + +/// Main entry point when running as `cmux --mcp` +public struct MCMain { + public static func main(args: [String] = CommandLine.arguments) { + // Parse arguments + var socketPath = "/tmp/cmux.sock" + var password: String? = nil + var debug = false + + var i = 1 + while i < args.count { + let arg = args[i] + switch arg { + case "--socket": + if i + 1 < args.count { + socketPath = args[i + 1] + i += 2 + } else { + i += 1 + } + case "--password": + if i + 1 < args.count { + password = args[i + 1] + i += 2 + } else { + i += 1 + } + case "--debug": + debug = true + i += 1 + default: + i += 1 + } + } + + if debug { + // Write debug messages to stderr + let stderr = FileHandle.standardError + let debugMsg = "cmux MCP Server starting...\n" + stderr.write(debugMsg.data(using: .utf8) ?? Data()) + } + + // Run MCP server + runMCPServer(socketPath: socketPath, password: password) + } +} diff --git a/CLI/MCPProtocol.swift b/CLI/MCPProtocol.swift new file mode 100644 index 000000000000..ba909ea1f7e3 --- /dev/null +++ b/CLI/MCPProtocol.swift @@ -0,0 +1,218 @@ +// MCPProtocol.swift +// MCP protocol handling: initialize, tools/list, tools/call + +import Foundation + +/// Protocol version supported by cmux MCP Server +public let mcpProtocolVersion = "2025-06-18" + +/// MCP Protocol Handler +public final class MCPProtocol { + + // MARK: - Properties + + private var isInitialized = false + private let toolRegistry: MCPToolRegistry + private let serverInfo: MCPServerInfo + + // MARK: - Initialization + + public init(toolRegistry: MCPToolRegistry, serverInfo: MCPServerInfo = MCPServerInfo(name: "cmux", version: "0.15.0")) { + self.toolRegistry = toolRegistry + self.serverInfo = serverInfo + } + + // MARK: - Message Handling + + /// Process an incoming JSON-RPC message and return the response + public func processMessage(_ messageData: Data) throws -> Data? { + // Try to decode as request first + if let request = try? JSONDecoder().decode(JSONRPCRequest.self, from: messageData) { + return try handleRequest(request) + } + + // Try to decode as notification (no response needed) + if let notification = try? JSONDecoder().decode(JSONRPCNotification.self, from: messageData) { + handleNotification(notification) + return nil + } + + // Invalid JSON + let error = JSONRPCErrorResponse( + id: .number(0), + error: JSONRPCError(code: JSONRPCErrorCode.parseError.rawValue, message: "Parse error") + ) + return try encodeResponse(error) + } + + // MARK: - Request Handling + + private func handleRequest(_ request: JSONRPCRequest) throws -> Data { + // Handle initialize specially (must be first) + if request.method == "initialize" { + return try handleInitialize(request) + } + + // Other methods require initialization + guard isInitialized else { + let error = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.serverError.rawValue, message: "Server not initialized. Call initialize first.") + ) + return try encodeResponse(error) + } + + // Route to appropriate handler + switch request.method { + case "tools/list": + return try handleToolsList(request) + case "tools/call", "tools/invoke": + return try handleToolsCall(request) + default: + let error = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.methodNotFound.rawValue, message: "Method not found: \(request.method)") + ) + return try encodeResponse(error) + } + } + + // MARK: - Initialize + + private func handleInitialize(_ request: JSONRPCRequest) throws -> Data { + // Parse parameters + guard let params = request.params, + let protocolVersion = params["protocolVersion"]?.value as? String else { + let error = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.invalidParams.rawValue, message: "Missing protocolVersion") + ) + return try encodeResponse(error) + } + + // Mark as initialized + isInitialized = true + + // Return capabilities + let capabilities = MCPCapabilities( + tools: MCPToolsCapability(listChanged: true), + resources: nil, + prompts: nil + ) + + let result = MCPInitializeResult( + protocolVersion: protocolVersion, + capabilities: capabilities, + serverInfo: serverInfo + ) + + let response = try JSONRPCResponse(id: request.id, result: result) + return try encodeResponse(response) + } + + // MARK: - Tools List + + private func handleToolsList(_ request: JSONRPCRequest) throws -> Data { + let tools = toolRegistry.listToolDefinitions() + let result = MCPToolsListResult(tools: tools) + let response = try JSONRPCResponse(id: request.id, result: result) + return try encodeResponse(response) + } + + // MARK: - Tools Call + + private func handleToolsCall(_ request: JSONRPCRequest) throws -> Data { + guard let params = request.params else { + let error = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.invalidParams.rawValue, message: "Missing params") + ) + return try encodeResponse(error) + } + + // Extract tool name + guard let toolName = params["name"]?.value as? String else { + let error = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.invalidParams.rawValue, message: "Missing tool name") + ) + return try encodeResponse(error) + } + + // Extract arguments + var arguments: [String: Any] = [:] + if let args = params["arguments"]?.value as? [String: Any] { + arguments = args + } + + // Execute tool + do { + let result = try toolRegistry.executeTool(name: toolName, arguments: arguments) + let response = try JSONRPCResponse(id: request.id, result: result) + return try encodeResponse(response) + } catch MCPError.toolNotFound(let name) { + let error = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.methodNotFound.rawValue, message: "Tool not found: \(name)") + ) + return try encodeResponse(error) + } catch MCPError.invalidParameters(let message) { + let error = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.invalidParams.rawValue, message: message) + ) + return try encodeResponse(error) + } catch { + let errResp = JSONRPCErrorResponse( + id: request.id, + error: JSONRPCError(code: JSONRPCErrorCode.internalError.rawValue, message: error.localizedDescription) + ) + return try encodeResponse(errResp) + } + } + + // MARK: - Notification Handling + + private func handleNotification(_ notification: JSONRPCNotification) { + // Handle initialized notification + if notification.method == "initialized" { + // Server side doesn't need to do anything special + return + } + + // Ignore other notifications + } + + // MARK: - Encoding + + private func encodeResponse(_ response: T) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return try encoder.encode(response) + } +} + +// MARK: - MCP Errors + +public enum MCPError: Error, LocalizedError { + case toolNotFound(String) + case invalidParameters(String) + case executionFailed(String) + case transportError(String) + case notInitialized + + public var errorDescription: String? { + switch self { + case .toolNotFound(let name): + return "Tool not found: \(name)" + case .invalidParameters(let message): + return "Invalid parameters: \(message)" + case .executionFailed(let message): + return "Execution failed: \(message)" + case .transportError(let message): + return "Transport error: \(message)" + case .notInitialized: + return "Server not initialized" + } + } +} diff --git a/CLI/MCPToolRegistry.swift b/CLI/MCPToolRegistry.swift new file mode 100644 index 000000000000..f5792f75b7b0 --- /dev/null +++ b/CLI/MCPToolRegistry.swift @@ -0,0 +1,636 @@ +// MCPToolRegistry.swift +// Tool registry and grouped tool implementations using direct socket RPC + +import Foundation + +// MARK: - MCPTool Protocol + +/// Protocol that all MCP tools must implement +public protocol MCPExecutionTool { + var name: String { get } + var description: String { get } + func execute(arguments: [String: Any]) throws -> MCPToolCallResult + var inputSchema: MCPToolInputSchema { get } +} + +// MARK: - Tool Registry + +public final class MCPToolRegistry { + + private var tools: [String: MCPExecutionTool] = [:] + private let backend: MCPBackend + + public init(backend: MCPBackend) { + self.backend = backend + registerDefaultTools() + } + + public func register(_ tool: MCPExecutionTool) { + tools[tool.name] = tool + } + + public func listTools() -> [MCPExecutionTool] { + Array(tools.values).sorted { $0.name < $1.name } + } + + public func listToolDefinitions() -> [MCPToolDefinition] { + listTools().map { MCPToolDefinition(name: $0.name, description: $0.description, inputSchema: $0.inputSchema) } + } + + public func getTool(name: String) -> MCPExecutionTool? { + tools[name] + } + + public func executeTool(name: String, arguments: [String: Any]) throws -> MCPToolCallResult { + guard let tool = tools[name] else { throw MCPError.toolNotFound(name) } + return try tool.execute(arguments: arguments) + } + + private func registerDefaultTools() { + register(SystemTool(backend: backend)) + register(WorkspaceTool(backend: backend)) + register(WindowTool(backend: backend)) + register(PaneTool(backend: backend)) + register(SurfaceTool(backend: backend)) + register(NotificationTool(backend: backend)) + register(TabTool(backend: backend)) + register(BrowserTool(backend: backend)) + } +} + +// MARK: - Action Definition & Grouped Tool Base + +/// Defines validation rules for a single action within a grouped tool. +struct ActionDef { + let required: [String] + let optional: [String] + /// Socket read timeout in milliseconds for this action. Long-running actions + /// (e.g. browser.wait, download.wait) should use a larger value. + let timeoutMs: Int32 + + init(required: [String] = [], optional: [String] = [], timeoutMs: Int32 = 120_000) { + self.required = required + self.optional = optional + self.timeoutMs = timeoutMs + } +} + +/// Base class for grouped MCP tools that map actions to socket RPC methods. +public class GroupedTool: MCPExecutionTool { + public let name: String + public let description: String + public let inputSchema: MCPToolInputSchema + let backend: MCPBackend + let namespace: String + let actions: [String: ActionDef] + + init(name: String, namespace: String, description: String, actions: [String: ActionDef], backend: MCPBackend) { + self.name = name + self.namespace = namespace + self.description = description + self.actions = actions + self.backend = backend + self.inputSchema = MCPToolInputSchema( + properties: [ + "action": MCPToolProperty(type: "string", description: "The action to perform. See tool description for available actions.") + ], + required: ["action"] + ) + } + + public func execute(arguments: [String: Any]) throws -> MCPToolCallResult { + guard let action = arguments["action"] as? String else { + throw MCPError.invalidParameters("Missing required parameter: action") + } + + guard let def = actions[action] else { + let available = actions.keys.sorted().joined(separator: ", ") + throw MCPError.invalidParameters("Unknown action '\(action)'. Available: \(available)") + } + + // Validate required params + for param in def.required { + guard arguments[param] != nil else { + throw MCPError.invalidParameters("Action '\(action)' requires parameter: \(param)") + } + } + + // Build params dict (everything except "action") + var params: [String: Any] = [:] + let allowed = Set(def.required + def.optional) + for (key, value) in arguments where key != "action" { + if allowed.contains(key) { + params[key] = value + } + } + + // Remap action_name -> action for *.action RPC methods + // The socket handler expects params.action, but we use action_name in MCP + // to avoid collision with the top-level action dispatch key. + if action == "action", let actionName = params.removeValue(forKey: "action_name") { + params["action"] = actionName + } + + let method = "\(namespace).\(action)" + return try backend.rpcForTool(method: method, params: params, timeoutMs: def.timeoutMs) + } +} + +// MARK: - System Tool + +public final class SystemTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_system", + namespace: "system", + description: """ + System utility commands for cmux. + + Actions: + - ping: Check if cmux is running. Params: (none) + - identify: Get focused window/workspace/pane/surface context. Params: workspace (optional), surface (optional), no_caller (optional bool) + - capabilities: List available socket methods and access mode. Params: (none) + """, + actions: [ + "ping": ActionDef(), + "identify": ActionDef(optional: ["workspace", "surface", "no_caller"]), + "capabilities": ActionDef(), + ], + backend: backend + ) + } +} + +// MARK: - Workspace Tool + +public final class WorkspaceTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_workspace", + namespace: "workspace", + description: """ + Manage cmux workspaces (tabs in the tab bar). + + Actions: + - list: List all workspaces. Params: (none) + - create: Create a new workspace. Params: command (optional) + - select: Switch to a workspace. Params: workspace_id (required) + - close: Close a workspace. Params: workspace_id (required) + - current: Get the active workspace. Params: (none) + - rename: Rename a workspace. Params: workspace_id (required), name (required) + - next: Switch to next workspace. Params: (none) + - previous: Switch to previous workspace. Params: (none) + - last: Switch to last active workspace. Params: (none) + - reorder: Reorder a workspace. Params: workspace_id (required), index (required) + - action: Run a workspace action. Params: workspace_id (required), action_name (required) + - move_to_window: Move workspace to another window. Params: workspace_id (required), window_id (optional) + """, + actions: [ + "list": ActionDef(), + "create": ActionDef(optional: ["command", "cwd"]), + "select": ActionDef(required: ["workspace_id"]), + "close": ActionDef(required: ["workspace_id"]), + "current": ActionDef(), + "rename": ActionDef(required: ["workspace_id", "name"]), + "next": ActionDef(), + "previous": ActionDef(), + "last": ActionDef(), + "reorder": ActionDef(required: ["workspace_id", "index"]), + "action": ActionDef(required: ["workspace_id", "action_name"]), + "move_to_window": ActionDef(required: ["workspace_id"], optional: ["window_id"]), + ], + backend: backend + ) + } +} + +// MARK: - Window Tool + +public final class WindowTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_window", + namespace: "window", + description: """ + Manage cmux windows. + + Actions: + - list: List all windows. Params: (none) + - create: Create a new window. Params: (none) + - close: Close a window. Params: window_id (required) + - focus: Focus a window. Params: window_id (required) + - current: Get the active window. Params: (none) + """, + actions: [ + "list": ActionDef(), + "create": ActionDef(), + "close": ActionDef(required: ["window_id"]), + "focus": ActionDef(required: ["window_id"]), + "current": ActionDef(), + ], + backend: backend + ) + } +} + +// MARK: - Pane Tool + +public final class PaneTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_pane", + namespace: "pane", + description: """ + Manage panes (split containers) within a workspace. + + Actions: + - list: List all panes in a workspace. Params: workspace_id (optional) + - surfaces: List surfaces in a pane. Params: pane_id (optional) + - focus: Focus a pane. Params: pane_id (required) + - create: Create a new pane. Params: direction (required: left/right/up/down), pane_id (optional) + - resize: Resize a pane. Params: pane_id (required), amount (required) + - swap: Swap two panes. Params: pane_id (required), target_pane_id (required) + - break: Break pane into its own workspace. Params: pane_id (required) + - join: Join a pane into another. Params: pane_id (required), target_pane_id (required), direction (required) + - last: Focus the last active pane. Params: (none) + """, + actions: [ + "list": ActionDef(optional: ["workspace_id"]), + "surfaces": ActionDef(optional: ["pane_id"]), + "focus": ActionDef(required: ["pane_id"]), + "create": ActionDef(required: ["direction"], optional: ["pane_id"]), + "resize": ActionDef(required: ["pane_id", "amount"]), + "swap": ActionDef(required: ["pane_id", "target_pane_id"]), + "break": ActionDef(required: ["pane_id"]), + "join": ActionDef(required: ["pane_id", "target_pane_id", "direction"]), + "last": ActionDef(), + ], + backend: backend + ) + } +} + +// MARK: - Surface Tool + +public final class SurfaceTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_surface", + namespace: "surface", + description: """ + Interact with terminal surfaces (individual terminal instances). + + Actions: + - list: List all surfaces. Params: workspace_id (optional) + - focus: Focus a surface. Params: surface_id (required) + - read_text: Read terminal screen text. Params: surface_id (optional), scrollback (optional bool), lines (optional number) + - send_text: Send text input to a surface. Params: text (required), surface_id (optional) + - send_key: Send a key press. Params: key (required, e.g. 'enter', 'ctrl-c', 'escape', 'tab', 'up', 'down'), surface_id (optional) + - split: Create a new split. Params: direction (required: left/right/up/down), surface_id (optional) + - close: Close a surface. Params: surface_id (required) + - create: Create a new surface. Params: (none) + - current: Get the focused surface. Params: (none) + - move: Move a surface. Params: surface_id (required), target_pane_id (required) + - reorder: Reorder surface within pane. Params: surface_id (required), index (required) + - trigger_flash: Flash a surface for attention. Params: surface_id (optional) + - clear_history: Clear scrollback history. Params: surface_id (optional) + - health: Check surface health. Params: surface_id (optional) + - action: Run a surface action. Params: surface_id (required), action_name (required) + - refresh: Refresh a surface. Params: surface_id (optional) + - drag_to_split: Drag surface to create split. Params: surface_id (required), direction (required) + """, + actions: [ + "list": ActionDef(optional: ["workspace_id"]), + "focus": ActionDef(required: ["surface_id"]), + "read_text": ActionDef(optional: ["surface_id", "scrollback", "lines"]), + "send_text": ActionDef(required: ["text"], optional: ["surface_id"]), + "send_key": ActionDef(required: ["key"], optional: ["surface_id"]), + "split": ActionDef(required: ["direction"], optional: ["surface_id"]), + "close": ActionDef(required: ["surface_id"]), + "create": ActionDef(), + "current": ActionDef(), + "move": ActionDef(required: ["surface_id", "target_pane_id"]), + "reorder": ActionDef(required: ["surface_id", "index"]), + "trigger_flash": ActionDef(optional: ["surface_id"]), + "clear_history": ActionDef(optional: ["surface_id"]), + "health": ActionDef(optional: ["surface_id"]), + "action": ActionDef(required: ["surface_id", "action_name"]), + "refresh": ActionDef(optional: ["surface_id"]), + "drag_to_split": ActionDef(required: ["surface_id", "direction"]), + ], + backend: backend + ) + } + + /// Override to extract just the text field from read_text responses. + public override func execute(arguments: [String: Any]) throws -> MCPToolCallResult { + guard let action = arguments["action"] as? String else { + throw MCPError.invalidParameters("Missing required parameter: action") + } + + // For read_text, return just the text content for cleaner output + if action == "read_text" { + guard let def = actions[action] else { + throw MCPError.invalidParameters("Unknown action '\(action)'") + } + for param in def.required { + guard arguments[param] != nil else { + throw MCPError.invalidParameters("Action '\(action)' requires parameter: \(param)") + } + } + var params: [String: Any] = [:] + let allowed = Set(def.required + def.optional) + for (key, value) in arguments where key != "action" { + if allowed.contains(key) { params[key] = value } + } + let result = try backend.rpc(method: "surface.read_text", params: params) + if let text = result["text"] as? String { + return MCPToolCallResult(content: [.text(text)]) + } + let data = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys, .prettyPrinted]) + let text = String(data: data, encoding: .utf8) ?? "{}" + return MCPToolCallResult(content: [.text(text)]) + } + + return try super.execute(arguments: arguments) + } +} + +// MARK: - Notification Tool + +public final class NotificationTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_notification", + namespace: "notification", + description: """ + Manage cmux notifications. + + Actions: + - create: Send a notification. Params: title (required), body (optional), subtitle (optional) + - create_for_surface: Notify for a surface. Params: surface_id (required), title (required), body (optional) + - create_for_target: Notify for a target. Params: target (required), title (required), body (optional) + - list: List all notifications. Params: (none) + - clear: Clear all notifications. Params: (none) + """, + actions: [ + "create": ActionDef(required: ["title"], optional: ["body", "subtitle"]), + "create_for_surface": ActionDef(required: ["surface_id", "title"], optional: ["body"]), + "create_for_target": ActionDef(required: ["target", "title"], optional: ["body"]), + "list": ActionDef(), + "clear": ActionDef(), + ], + backend: backend + ) + } +} + +// MARK: - Tab Tool + +public final class TabTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_tab", + namespace: "tab", + description: """ + Tab actions. + + Actions: + - action: Run a tab action. Params: tab_id (required), action_name (required) + """, + actions: [ + "action": ActionDef(required: ["tab_id", "action_name"]), + ], + backend: backend + ) + } +} + +// MARK: - Browser Tool + +public final class BrowserTool: GroupedTool { + public init(backend: MCPBackend) { + super.init( + name: "cmux_browser", + namespace: "browser", + description: """ + Browser automation for cmux web views. All actions target the focused browser surface unless surface_id is provided. + + Navigation: + - navigate: Go to URL. Params: url (required), surface_id (optional) + - back: Go back. Params: surface_id (optional) + - forward: Go forward. Params: surface_id (optional) + - reload: Reload page. Params: surface_id (optional) + + Finding elements: + - find.text: Find by text. Params: text (required), surface_id (optional) + - find.role: Find by ARIA role. Params: role (required), name (optional), surface_id (optional) + - find.label: Find by label. Params: label (required), surface_id (optional) + - find.placeholder: Find by placeholder. Params: placeholder (required), surface_id (optional) + - find.testid: Find by test ID. Params: testid (required), surface_id (optional) + - find.alt: Find by alt text. Params: alt (required), surface_id (optional) + - find.title: Find by title. Params: title (required), surface_id (optional) + - find.first: Find first element. Params: selector (required), surface_id (optional) + - find.last: Find last element. Params: selector (required), surface_id (optional) + - find.nth: Find nth element. Params: selector (required), index (required), surface_id (optional) + + Interaction: + - click: Click element. Params: selector (required), surface_id (optional) + - dblclick: Double-click. Params: selector (required), surface_id (optional) + - hover: Hover element. Params: selector (required), surface_id (optional) + - fill: Fill input. Params: selector (required), value (required), surface_id (optional) + - type: Type text. Params: selector (required), text (required), surface_id (optional) + - press: Press key. Params: key (required), surface_id (optional) + - check: Check checkbox. Params: selector (required), surface_id (optional) + - uncheck: Uncheck checkbox. Params: selector (required), surface_id (optional) + - select: Select option. Params: selector (required), value (required), surface_id (optional) + - focus: Focus element. Params: selector (required), surface_id (optional) + - scroll: Scroll. Params: selector (optional), x (optional), y (optional), surface_id (optional) + - scroll_into_view: Scroll element into view. Params: selector (required), surface_id (optional) + + Inspection: + - get.text: Get text content. Params: selector (required), surface_id (optional) + - get.html: Get HTML. Params: selector (required), surface_id (optional) + - get.attr: Get attribute. Params: selector (required), attribute (required), surface_id (optional) + - get.value: Get input value. Params: selector (required), surface_id (optional) + - get.title: Get page title. Params: surface_id (optional) + - get.box: Get bounding box. Params: selector (required), surface_id (optional) + - get.count: Count elements. Params: selector (required), surface_id (optional) + - get.styles: Get computed styles. Params: selector (required), properties (optional), surface_id (optional) + - url.get: Get current URL. Params: surface_id (optional) + - is.visible: Check visibility. Params: selector (required), surface_id (optional) + - is.enabled: Check enabled. Params: selector (required), surface_id (optional) + - is.checked: Check checked. Params: selector (required), surface_id (optional) + + Page: + - screenshot: Take screenshot. Params: selector (optional), path (optional), surface_id (optional) + - snapshot: Get accessibility snapshot. Params: surface_id (optional) + - eval: Evaluate JavaScript. Params: expression (required), surface_id (optional) + - wait: Wait for condition. Params: selector (optional), state (optional), timeout (optional), surface_id (optional) + - highlight: Highlight element. Params: selector (required), surface_id (optional) + + Tabs: + - tab.new: Open new tab. Params: url (optional), surface_id (optional) + - tab.list: List tabs. Params: surface_id (optional) + - tab.switch: Switch tab. Params: index (required), surface_id (optional) + - tab.close: Close tab. Params: index (optional), surface_id (optional) + + Advanced: + - cookies.get: Get cookies. Params: url (optional), surface_id (optional) + - cookies.set: Set cookie. Params: name (required), value (required), domain (optional), surface_id (optional) + - cookies.clear: Clear cookies. Params: surface_id (optional) + - storage.get: Get storage. Params: key (required), type (optional), surface_id (optional) + - storage.set: Set storage. Params: key (required), value (required), type (optional), surface_id (optional) + - storage.clear: Clear storage. Params: type (optional), surface_id (optional) + - console.list: List console messages. Params: surface_id (optional) + - console.clear: Clear console. Params: surface_id (optional) + - errors.list: List page errors. Params: surface_id (optional) + - network.requests: List network requests. Params: surface_id (optional) + - network.route: Set up network route. Params: pattern (required), response (optional), surface_id (optional) + - network.unroute: Remove network route. Params: pattern (required), surface_id (optional) + - viewport.set: Set viewport size. Params: width (required), height (required), surface_id (optional) + - geolocation.set: Set geolocation. Params: latitude (required), longitude (required), surface_id (optional) + - offline.set: Toggle offline mode. Params: offline (required), surface_id (optional) + + Scripts & Styles: + - addscript: Add script. Params: content (optional), url (optional), surface_id (optional) + - addinitscript: Add init script. Params: script (required), surface_id (optional) + - addstyle: Add stylesheet. Params: content (optional), url (optional), surface_id (optional) + + Input: + - input_keyboard: Raw keyboard input. Params: type (required), key (required), surface_id (optional) + - input_mouse: Raw mouse input. Params: type (required), x (required), y (required), button (optional), surface_id (optional) + - input_touch: Raw touch input. Params: type (required), x (required), y (required), surface_id (optional) + - keydown: Key down. Params: key (required), surface_id (optional) + - keyup: Key up. Params: key (required), surface_id (optional) + + State: + - state.save: Save browser state. Params: name (required), surface_id (optional) + - state.load: Load browser state. Params: name (required), surface_id (optional) + + Frames: + - frame.main: Switch to main frame. Params: surface_id (optional) + - frame.select: Switch to frame. Params: selector (required), surface_id (optional) + + Recording: + - screencast.start: Start screencast. Params: path (optional), surface_id (optional) + - screencast.stop: Stop screencast. Params: surface_id (optional) + - trace.start: Start trace. Params: path (optional), surface_id (optional) + - trace.stop: Stop trace. Params: surface_id (optional) + - download.wait: Wait for download. Params: surface_id (optional) + + Other: + - dialog.accept: Accept dialog. Params: text (optional), surface_id (optional) + - dialog.dismiss: Dismiss dialog. Params: surface_id (optional) + - open_split: Open browser in split. Params: url (optional), direction (optional), surface_id (optional) + - focus_webview: Focus the web view. Params: surface_id (optional) + - is_webview_focused: Check if web view is focused. Params: surface_id (optional) + """, + actions: [ + // Navigation + "navigate": ActionDef(required: ["url"], optional: ["surface_id"]), + "back": ActionDef(optional: ["surface_id"]), + "forward": ActionDef(optional: ["surface_id"]), + "reload": ActionDef(optional: ["surface_id"]), + // Finding elements + "find.text": ActionDef(required: ["text"], optional: ["surface_id"]), + "find.role": ActionDef(required: ["role"], optional: ["name", "surface_id"]), + "find.label": ActionDef(required: ["label"], optional: ["surface_id"]), + "find.placeholder": ActionDef(required: ["placeholder"], optional: ["surface_id"]), + "find.testid": ActionDef(required: ["testid"], optional: ["surface_id"]), + "find.alt": ActionDef(required: ["alt"], optional: ["surface_id"]), + "find.title": ActionDef(required: ["title"], optional: ["surface_id"]), + "find.first": ActionDef(required: ["selector"], optional: ["surface_id"]), + "find.last": ActionDef(required: ["selector"], optional: ["surface_id"]), + "find.nth": ActionDef(required: ["selector", "index"], optional: ["surface_id"]), + // Interaction + "click": ActionDef(required: ["selector"], optional: ["surface_id"]), + "dblclick": ActionDef(required: ["selector"], optional: ["surface_id"]), + "hover": ActionDef(required: ["selector"], optional: ["surface_id"]), + "fill": ActionDef(required: ["selector", "value"], optional: ["surface_id"]), + "type": ActionDef(required: ["selector", "text"], optional: ["surface_id"]), + "press": ActionDef(required: ["key"], optional: ["surface_id"]), + "check": ActionDef(required: ["selector"], optional: ["surface_id"]), + "uncheck": ActionDef(required: ["selector"], optional: ["surface_id"]), + "select": ActionDef(required: ["selector", "value"], optional: ["surface_id"]), + "focus": ActionDef(required: ["selector"], optional: ["surface_id"]), + "scroll": ActionDef(optional: ["selector", "x", "y", "surface_id"]), + "scroll_into_view": ActionDef(required: ["selector"], optional: ["surface_id"]), + // Inspection + "get.text": ActionDef(required: ["selector"], optional: ["surface_id"]), + "get.html": ActionDef(required: ["selector"], optional: ["surface_id"]), + "get.attr": ActionDef(required: ["selector", "attribute"], optional: ["surface_id"]), + "get.value": ActionDef(required: ["selector"], optional: ["surface_id"]), + "get.title": ActionDef(optional: ["surface_id"]), + "get.box": ActionDef(required: ["selector"], optional: ["surface_id"]), + "get.count": ActionDef(required: ["selector"], optional: ["surface_id"]), + "get.styles": ActionDef(required: ["selector"], optional: ["properties", "surface_id"]), + "url.get": ActionDef(optional: ["surface_id"]), + "is.visible": ActionDef(required: ["selector"], optional: ["surface_id"]), + "is.enabled": ActionDef(required: ["selector"], optional: ["surface_id"]), + "is.checked": ActionDef(required: ["selector"], optional: ["surface_id"]), + // Page + "screenshot": ActionDef(optional: ["selector", "path", "surface_id"]), + "snapshot": ActionDef(optional: ["surface_id"]), + "eval": ActionDef(required: ["expression"], optional: ["surface_id"]), + "wait": ActionDef(optional: ["selector", "state", "timeout", "surface_id"], timeoutMs: 300_000), + "highlight": ActionDef(required: ["selector"], optional: ["surface_id"]), + // Tabs + "tab.new": ActionDef(optional: ["url", "surface_id"]), + "tab.list": ActionDef(optional: ["surface_id"]), + "tab.switch": ActionDef(required: ["index"], optional: ["surface_id"]), + "tab.close": ActionDef(optional: ["index", "surface_id"]), + // Cookies + "cookies.get": ActionDef(optional: ["url", "surface_id"]), + "cookies.set": ActionDef(required: ["name", "value"], optional: ["domain", "surface_id"]), + "cookies.clear": ActionDef(optional: ["surface_id"]), + // Storage + "storage.get": ActionDef(required: ["key"], optional: ["type", "surface_id"]), + "storage.set": ActionDef(required: ["key", "value"], optional: ["type", "surface_id"]), + "storage.clear": ActionDef(optional: ["type", "surface_id"]), + // Console & errors + "console.list": ActionDef(optional: ["surface_id"]), + "console.clear": ActionDef(optional: ["surface_id"]), + "errors.list": ActionDef(optional: ["surface_id"]), + // Network + "network.requests": ActionDef(optional: ["surface_id"]), + "network.route": ActionDef(required: ["pattern"], optional: ["response", "surface_id"]), + "network.unroute": ActionDef(required: ["pattern"], optional: ["surface_id"]), + // Viewport & environment + "viewport.set": ActionDef(required: ["width", "height"], optional: ["surface_id"]), + "geolocation.set": ActionDef(required: ["latitude", "longitude"], optional: ["surface_id"]), + "offline.set": ActionDef(required: ["offline"], optional: ["surface_id"]), + // Scripts & styles + "addscript": ActionDef(optional: ["content", "url", "surface_id"]), + "addinitscript": ActionDef(required: ["script"], optional: ["surface_id"]), + "addstyle": ActionDef(optional: ["content", "url", "surface_id"]), + // Raw input + "input_keyboard": ActionDef(required: ["type", "key"], optional: ["surface_id"]), + "input_mouse": ActionDef(required: ["type", "x", "y"], optional: ["button", "surface_id"]), + "input_touch": ActionDef(required: ["type", "x", "y"], optional: ["surface_id"]), + "keydown": ActionDef(required: ["key"], optional: ["surface_id"]), + "keyup": ActionDef(required: ["key"], optional: ["surface_id"]), + // State + "state.save": ActionDef(required: ["name"], optional: ["surface_id"]), + "state.load": ActionDef(required: ["name"], optional: ["surface_id"]), + // Frames + "frame.main": ActionDef(optional: ["surface_id"]), + "frame.select": ActionDef(required: ["selector"], optional: ["surface_id"]), + // Recording + "screencast.start": ActionDef(optional: ["path", "surface_id"]), + "screencast.stop": ActionDef(optional: ["surface_id"]), + "trace.start": ActionDef(optional: ["path", "surface_id"]), + "trace.stop": ActionDef(optional: ["surface_id"]), + "download.wait": ActionDef(optional: ["surface_id"], timeoutMs: 300_000), + // Dialog + "dialog.accept": ActionDef(optional: ["text", "surface_id"]), + "dialog.dismiss": ActionDef(optional: ["surface_id"]), + // Other + "open_split": ActionDef(optional: ["url", "direction", "surface_id"]), + "focus_webview": ActionDef(optional: ["surface_id"]), + "is_webview_focused": ActionDef(optional: ["surface_id"]), + ], + backend: backend + ) + } +} diff --git a/CLI/MCPTypes.swift b/CLI/MCPTypes.swift new file mode 100644 index 000000000000..d70bf661a4d6 --- /dev/null +++ b/CLI/MCPTypes.swift @@ -0,0 +1,404 @@ +// MCPTypes.swift +// JSON-RPC 2.0 and MCP protocol types + +import Foundation + +// MARK: - JSON-RPC 2.0 Types + +/// JSON-RPC 2.0 Request +public struct JSONRPCRequest: Codable { + public let jsonrpc: String + public let id: JSONRPCId + public let method: String + public let params: [String: AnyCodable]? + + public init(id: JSONRPCId, method: String, params: [String: AnyCodable]? = nil) { + self.jsonrpc = "2.0" + self.id = id + self.method = method + self.params = params + } +} + +/// JSON-RPC 2.0 Response (success) +/// Uses pre-encoded JSON Data for the result field to avoid AnyCodable serialization issues. +public struct JSONRPCResponse: Encodable { + public let jsonrpc: String + public let id: JSONRPCId + /// Pre-encoded JSON bytes for the result value. + public let resultData: Data + + public init(id: JSONRPCId, result: T) throws { + self.jsonrpc = "2.0" + self.id = id + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + self.resultData = try encoder.encode(result) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(jsonrpc, forKey: .jsonrpc) + try container.encode(id, forKey: .id) + // Embed pre-encoded JSON as raw value + let rawResult = try JSONDecoder().decode(AnyCodable.self, from: resultData) + try container.encode(rawResult, forKey: .result) + } + + private enum CodingKeys: String, CodingKey { + case jsonrpc, id, result + } +} + +/// JSON-RPC 2.0 Response (error) +public struct JSONRPCError: Codable { + public let code: Int + public let message: String + public let data: AnyCodable? + + public init(code: Int, message: String, data: Any? = nil) { + self.code = code + self.message = message + self.data = data.map { AnyCodable($0) } + } +} + +/// JSON-RPC 2.0 Error Response +public struct JSONRPCErrorResponse: Codable { + public let jsonrpc: String + public let id: JSONRPCId + public let error: JSONRPCError + + public init(id: JSONRPCId, error: JSONRPCError) { + self.jsonrpc = "2.0" + self.id = id + self.error = error + } +} + +/// JSON-RPC 2.0 Notification (no id) +public struct JSONRPCNotification: Codable { + public let jsonrpc: String + public let method: String + public let params: [String: AnyCodable]? + + public init(method: String, params: [String: AnyCodable]? = nil) { + self.jsonrpc = "2.0" + self.method = method + self.params = params + } +} + +/// JSON-RPC ID (can be string or number) +public enum JSONRPCId: Codable, Equatable, Hashable { + case number(Int) + case string(String) + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let intValue = try? container.decode(Int.self) { + self = .number(intValue) + } else if let stringValue = try? container.decode(String.self) { + self = .string(stringValue) + } else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid JSON-RPC id") + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .number(let value): + try container.encode(value) + case .string(let value): + try container.encode(value) + } + } +} + +/// JSON-RPC Error Codes +public enum JSONRPCErrorCode: Int { + case parseError = -32700 + case invalidRequest = -32600 + case methodNotFound = -32601 + case invalidParams = -32602 + case internalError = -32603 + case serverError = -32000 +} + +// MARK: - AnyCodable Helper + +/// Type-erased Codable wrapper for dynamic JSON values +public struct AnyCodable: Codable, Equatable, Hashable { + public let value: Any + + public init(_ value: Any) { + self.value = value + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + if container.decodeNil() { + self.value = NSNull() + } else if let bool = try? container.decode(Bool.self) { + self.value = bool + } else if let int = try? container.decode(Int.self) { + self.value = int + } else if let double = try? container.decode(Double.self) { + self.value = double + } else if let string = try? container.decode(String.self) { + self.value = string + } else if let array = try? container.decode([AnyCodable].self) { + self.value = array.map { $0.value } + } else if let dictionary = try? container.decode([String: AnyCodable].self) { + self.value = dictionary.mapValues { $0.value } + } else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported type") + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + + switch value { + case is NSNull: + try container.encodeNil() + case let bool as Bool: + try container.encode(bool) + case let int as Int: + try container.encode(int) + case let double as Double: + try container.encode(double) + case let string as String: + try container.encode(string) + case let array as [Any]: + try container.encode(array.map { AnyCodable($0) }) + case let dictionary as [String: Any]: + try container.encode(dictionary.mapValues { AnyCodable($0) }) + default: + let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "Unsupported type") + throw EncodingError.invalidValue(value, context) + } + } + + public static func == (lhs: AnyCodable, rhs: AnyCodable) -> Bool { + switch (lhs.value, rhs.value) { + case (let l as NSNull, let r as NSNull): + return true + case (let l as Bool, let r as Bool): + return l == r + case (let l as Int, let r as Int): + return l == r + case (let l as Double, let r as Double): + return l == r + case (let l as String, let r as String): + return l == r + case (let l as [Any], let r as [Any]): + return l.count == r.count && zip(l, r).allSatisfy { AnyCodable($0) == AnyCodable($1) } + case (let l as [String: Any], let r as [String: Any]): + return l.count == r.count && l.keys.allSatisfy { key in + guard let lv = l[key], let rv = r[key] else { return false } + return AnyCodable(lv) == AnyCodable(rv) + } + default: + return false + } + } + + public func hash(into hasher: inout Hasher) { + switch value { + case is NSNull: + hasher.combine(0) + case let bool as Bool: + hasher.combine(bool) + case let int as Int: + hasher.combine(int) + case let double as Double: + hasher.combine(double) + case let string as String: + hasher.combine(string) + default: + // For complex types, use description + hasher.combine(String(describing: value)) + } + } +} + +// MARK: - MCP Protocol Types + +/// MCP Initialize parameters +public struct MCPInitializeParams: Codable { + public let protocolVersion: String + public let capabilities: MCPCapabilities + public let clientInfo: MCPClientInfo + + enum CodingKeys: String, CodingKey { + case protocolVersion = "protocolVersion" + case capabilities + case clientInfo = "clientInfo" + } +} + +/// MCP Client Info +public struct MCPClientInfo: Codable { + public let name: String + public let version: String +} + +/// MCP Server Info +public struct MCPServerInfo: Codable { + public let name: String + public let version: String + + public init(name: String, version: String) { + self.name = name + self.version = version + } +} + +/// MCP Capabilities +public struct MCPCapabilities: Codable { + public let tools: MCPToolsCapability? + public let resources: MCPResourcesCapability? + public let prompts: MCPPromptsCapability? + + public init(tools: MCPToolsCapability? = nil, resources: MCPResourcesCapability? = nil, prompts: MCPPromptsCapability? = nil) { + self.tools = tools + self.resources = resources + self.prompts = prompts + } +} + +/// MCP Tools Capability +public struct MCPToolsCapability: Codable { + public let listChanged: Bool? + + public init(listChanged: Bool? = nil) { + self.listChanged = listChanged + } +} + +/// MCP Resources Capability +public struct MCPResourcesCapability: Codable { + public let subscribe: Bool? + public let listChanged: Bool? +} + +/// MCP Prompts Capability +public struct MCPPromptsCapability: Codable { + public let listChanged: Bool? +} + +/// MCP Initialize Result +public struct MCPInitializeResult: Codable { + public let protocolVersion: String + public let capabilities: MCPCapabilities + public let serverInfo: MCPServerInfo + + enum CodingKeys: String, CodingKey { + case protocolVersion = "protocolVersion" + case capabilities + case serverInfo = "serverInfo" + } + + public init(protocolVersion: String, capabilities: MCPCapabilities, serverInfo: MCPServerInfo) { + self.protocolVersion = protocolVersion + self.capabilities = capabilities + self.serverInfo = serverInfo + } +} + +// MARK: - MCP Tool Types + +/// MCP Tool definition +public struct MCPToolDefinition: Codable { + public let name: String + public let description: String + public let inputSchema: MCPToolInputSchema + + public init(name: String, description: String, inputSchema: MCPToolInputSchema) { + self.name = name + self.description = description + self.inputSchema = inputSchema + } +} + +/// MCP Tool Input Schema +public struct MCPToolInputSchema: Codable { + public let type: String + public let properties: [String: MCPToolProperty]? + public let required: [String]? + + public init(type: String = "object", properties: [String: MCPToolProperty]? = nil, required: [String]? = nil) { + self.type = type + self.properties = properties + self.required = required + } +} + +/// MCP Tool Property +public struct MCPToolProperty: Codable { + public let type: String + public let description: String? + public let items: MCPToolPropertyItems? + + public init(type: String, description: String? = nil, items: MCPToolPropertyItems? = nil) { + self.type = type + self.description = description + self.items = items + } +} + +/// MCP Tool Property Items (for arrays) +public struct MCPToolPropertyItems: Codable { + public let type: String + + public init(type: String) { + self.type = type + } +} + +/// MCP Tools List Result +public struct MCPToolsListResult: Codable { + public let tools: [MCPToolDefinition] + + public init(tools: [MCPToolDefinition]) { + self.tools = tools + } +} + +/// MCP Tool Call Parameters +public struct MCPToolCallParams: Codable { + public let name: String + public let arguments: [String: AnyCodable]? + + public init(name: String, arguments: [String: AnyCodable]? = nil) { + self.name = name + self.arguments = arguments + } +} + +/// MCP Tool Call Result +public struct MCPToolCallResult: Codable { + public let content: [MCPContentBlock] + + public init(content: [MCPContentBlock]) { + self.content = content + } +} + +/// MCP Content Block (for tool results) +public struct MCPContentBlock: Codable { + public let type: String + public let text: String? + + public init(type: String = "text", text: String? = nil) { + self.type = type + self.text = text + } + + public static func text(_ text: String) -> MCPContentBlock { + MCPContentBlock(type: "text", text: text) + } +} diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 4475f3417626..1f59d1feade0 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -451,6 +451,20 @@ private enum SocketPasswordResolver { } } +/// Check if the MCP server is enabled in the app's UserDefaults. +/// Tries both release and debug bundle identifiers since the CLI binary +/// doesn't share the app's bundle ID automatically. +private func mcpServerIsEnabled() -> Bool { + let key = "mcpServerEnabled" + for suite in ["com.cmuxterm.app", "com.cmuxterm.app.debug"] { + if let defaults = UserDefaults(suiteName: suite), + defaults.object(forKey: key) != nil { + return defaults.bool(forKey: key) + } + } + return true // default enabled +} + private enum CLISocketPathSource { case explicitFlag case environment @@ -809,6 +823,7 @@ struct CMUXCLI { var idFormatArg: String? = nil var windowId: String? = nil var socketPasswordArg: String? = nil + var mcpMode = false var index = 1 while index < args.count { @@ -859,9 +874,32 @@ struct CMUXCLI { print(usage()) return } + if arg == "--mcp" { + mcpMode = true + index += 1 + continue + } break } + if mcpMode { + // Check if MCP server is enabled in app settings + if !mcpServerIsEnabled() { + FileHandle.standardError.write( + "MCP server is disabled in cmux settings.\n".data(using: .utf8) ?? Data() + ) + let errorResponse = """ + {"jsonrpc":"2.0","id":null,"error":{"code":-32000,"message":"MCP server is disabled in cmux settings. Enable it in Settings > Automation."}} + """ + print(errorResponse) + Foundation.exit(1) + } + // Run MCP server mode (all flags like --socket/--password are fully parsed above) + let resolvedPassword = SocketPasswordResolver.resolve(explicit: socketPasswordArg) + runMCPServer(socketPath: socketPath, password: resolvedPassword) + return + } + guard index < args.count else { print(usage()) throw CLIError(message: "Missing command") diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index 9b977a9b0193..e4d6f6d27088 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -66,6 +66,11 @@ A5001100 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A5001101 /* Assets.xcassets */; }; A5001230 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = A5001231 /* Sparkle */; }; B9000002A1B2C3D4E5F60719 /* cmux.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000001A1B2C3D4E5F60719 /* cmux.swift */; }; + 243B3E44AC275A78C3BAF5C0 /* MCPTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCA15693F84B14C6AC4D9AE1 /* MCPTypes.swift */; }; + 31C1EAB308E18D1A993BED6C /* MCPProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = D86CFFFD2606490315F9B31E /* MCPProtocol.swift */; }; + 32D70A3BF76F739044CAFAC5 /* MCPToolRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = F948F2D6E93413373C43A5EC /* MCPToolRegistry.swift */; }; + 50B61F52049A28102138F522 /* MCPMain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54663DAD2AA26C0267C9AB1C /* MCPMain.swift */; }; + F153290401B7D581368680E3 /* MCPBackend.swift in Sources */ = {isa = PBXBuildFile; fileRef = A02574EA3CBE62F9A447CC5D /* MCPBackend.swift */; }; B900000BA1B2C3D4E5F60719 /* cmux in Copy CLI */ = {isa = PBXBuildFile; fileRef = B9000004A1B2C3D4E5F60719 /* cmux */; }; C1ADE00002A1B2C3D4E5F719 /* claude in Copy CLI */ = {isa = PBXBuildFile; fileRef = C1ADE00001A1B2C3D4E5F719 /* claude */; }; D1BEF00002A1B2C3D4E5F719 /* open in Copy CLI */ = {isa = PBXBuildFile; fileRef = D1BEF00001A1B2C3D4E5F719 /* open */; }; @@ -210,6 +215,11 @@ D1BEF00001A1B2C3D4E5F719 /* open */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "Resources/bin/open"; sourceTree = SOURCE_ROOT; }; A5002001 /* THIRD_PARTY_LICENSES.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = THIRD_PARTY_LICENSES.md; sourceTree = SOURCE_ROOT; }; B9000001A1B2C3D4E5F60719 /* cmux.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = cmux.swift; sourceTree = ""; }; + 54663DAD2AA26C0267C9AB1C /* MCPMain.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MCPMain.swift; sourceTree = ""; }; + A02574EA3CBE62F9A447CC5D /* MCPBackend.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MCPBackend.swift; sourceTree = ""; }; + CCA15693F84B14C6AC4D9AE1 /* MCPTypes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MCPTypes.swift; sourceTree = ""; }; + D86CFFFD2606490315F9B31E /* MCPProtocol.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MCPProtocol.swift; sourceTree = ""; }; + F948F2D6E93413373C43A5EC /* MCPToolRegistry.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MCPToolRegistry.swift; sourceTree = ""; }; B9000004A1B2C3D4E5F60719 /* cmux */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = cmux; sourceTree = BUILT_PRODUCTS_DIR; }; B9000011A1B2C3D4E5F60719 /* AutomationSocketUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutomationSocketUITests.swift; sourceTree = ""; }; B9000013A1B2C3D4E5F60719 /* JumpToUnreadUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JumpToUnreadUITests.swift; sourceTree = ""; }; @@ -397,6 +407,11 @@ isa = PBXGroup; children = ( B9000001A1B2C3D4E5F60719 /* cmux.swift */, + CCA15693F84B14C6AC4D9AE1 /* MCPTypes.swift */, + D86CFFFD2606490315F9B31E /* MCPProtocol.swift */, + F948F2D6E93413373C43A5EC /* MCPToolRegistry.swift */, + A02574EA3CBE62F9A447CC5D /* MCPBackend.swift */, + 54663DAD2AA26C0267C9AB1C /* MCPMain.swift */, ); path = CLI; sourceTree = ""; @@ -695,6 +710,11 @@ buildActionMask = 2147483647; files = ( B9000002A1B2C3D4E5F60719 /* cmux.swift in Sources */, + 243B3E44AC275A78C3BAF5C0 /* MCPTypes.swift in Sources */, + 31C1EAB308E18D1A993BED6C /* MCPProtocol.swift in Sources */, + 32D70A3BF76F739044CAFAC5 /* MCPToolRegistry.swift in Sources */, + F153290401B7D581368680E3 /* MCPBackend.swift in Sources */, + 50B61F52049A28102138F522 /* MCPMain.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/README.md b/README.md index 9093268db652..85f9d9af155a 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,32 @@ On relaunch, cmux currently restores app layout and metadata only: cmux does **not** restore live process state inside terminal apps. For example, active Claude Code/tmux/vim sessions are not resumed after restart yet. +## MCP Server + +cmux includes a built-in [MCP](https://modelcontextprotocol.io/) server that lets AI tools (Claude Desktop, Claude Code, etc.) control workspaces, terminals, browser, and notifications. + +```bash +# Start the MCP server (stdio transport) +cmux --mcp +``` + +Claude Code auto-discovers cmux when running inside a cmux terminal. For Claude Desktop, add to your config: + +```json +{ + "mcpServers": { + "cmux": { + "command": "/Applications/cmux.app/Contents/Resources/bin/cmux", + "args": ["--mcp"] + } + } +} +``` + +The server exposes 8 grouped tools: `cmux_system`, `cmux_workspace`, `cmux_window`, `cmux_pane`, `cmux_surface`, `cmux_notification`, `cmux_tab`, and `cmux_browser`. Each tool accepts an `action` parameter for the specific operation. See [docs/MCP-SERVER.md](docs/MCP-SERVER.md) for details. + +Toggle the MCP server on/off in **Settings > Automation > MCP Server**. + ## Star History @@ -231,6 +257,94 @@ cmux does **not** restore live process state inside terminal apps. For example, ## Contributing +### Development Guide + +#### Prerequisites + +- **Xcode** - Full Xcode installation (not just Command Line Tools) + ```bash + sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer + ``` +- **zig 0.14.x** - Required for building GhosttyKit + ```bash + brew install zig@0.14 + ``` +- **xcodeproj gem** - For adding files to Xcode project + ```bash + sudo gem install xcodeproj + ``` + +#### Initial Setup + +```bash +# Initialize submodules +git submodule update --init --recursive + +# Build GhosttyKit (required for full app) +cd ghostty +zig build -Demit-xcframework=true -Doptimize=ReleaseFast +cd .. +``` + +#### Building + +```bash +# Build CLI only (fastest, for testing CLI changes) +xcodebuild -project GhosttyTabs.xcodeproj \ + -scheme cmux-cli \ + -configuration Debug \ + -destination 'platform=macOS' \ + build + +# Build full app +xcodebuild -project GhosttyTabs.xcodeproj \ + -scheme cmux \ + -configuration Debug \ + -destination 'platform=macOS' \ + build + +# Build with tag (for parallel development) +./scripts/reload.sh --tag your-feature +``` + +#### Adding New Code + +When adding new Swift files to the project, you need to add them to the Xcode target: + +```bash +# Using Ruby xcodeproj +ruby -e ' +require "xcodeproj" + +project = Xcodeproj::Project.open("GhosttyTabs.xcodeproj") +target = project.targets.find { |t| t.name == "cmux-cli" } +cli_group = project.main_group.find_subpath("CLI", true) + +files = ["YourNewFile.swift"] +files.each do |file| + file_ref = cli_group.new_file(file) + target.add_file_references([file_ref]) +end + +project.save +' +``` + +#### Running and Testing + +```bash +# Binary location after build +~/Library/Developer/Xcode/DerivedData/GhosttyTabs-*/Build/Products/Debug/cmux + +# Run in MCP mode (for testing MCP tools) +./cmux --mcp + +# Run reload script to launch Debug app +./scripts/reload.sh --tag your-feature +``` + +--- + Ways to get involved: - Follow us on X for updates [@manaflowai](https://x.com/manaflowai) or [@lawrencecchen](https://x.com/lawrencecchen) diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index ff392c1f94de..e58548b366d8 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -2778,6 +2778,18 @@ enum ClaudeCodeIntegrationSettings { } } +enum MCPServerSettings { + static let enabledKey = "mcpServerEnabled" + static let defaultEnabled = true + + static func isEnabled(defaults: UserDefaults = .standard) -> Bool { + if defaults.object(forKey: enabledKey) == nil { + return defaultEnabled + } + return defaults.bool(forKey: enabledKey) + } +} + enum TelemetrySettings { static let sendAnonymousTelemetryKey = "sendAnonymousTelemetry" static let defaultSendAnonymousTelemetry = true @@ -2803,6 +2815,8 @@ struct SettingsView: View { @AppStorage(SocketControlSettings.appStorageKey) private var socketControlMode = SocketControlSettings.defaultMode.rawValue @AppStorage(ClaudeCodeIntegrationSettings.hooksEnabledKey) private var claudeCodeHooksEnabled = ClaudeCodeIntegrationSettings.defaultHooksEnabled + @AppStorage(MCPServerSettings.enabledKey) + private var mcpServerEnabled = MCPServerSettings.defaultEnabled @AppStorage(TelemetrySettings.sendAnonymousTelemetryKey) private var sendAnonymousTelemetry = TelemetrySettings.defaultSendAnonymousTelemetry @AppStorage("cmuxPortBase") private var cmuxPortBase = 9100 @@ -3656,6 +3670,36 @@ struct SettingsView: View { SettingsCardNote(String(localized: "settings.automation.claudeCode.note", defaultValue: "When enabled, cmux wraps the claude command to inject session tracking and notification hooks. Disable if you prefer to manage Claude Code hooks yourself.")) } + SettingsCard { + SettingsCardRow( + "MCP Server", + subtitle: mcpServerEnabled + ? "External AI tools can connect via stdio." + : "The MCP server is disabled. `cmux --mcp` will exit with an error." + ) { + Toggle("", isOn: $mcpServerEnabled) + .labelsHidden() + .controlSize(.small) + } + + SettingsCardDivider() + + HStack(spacing: 6) { + Circle() + .fill(mcpServerEnabled ? Color.green : Color.red) + .frame(width: 8, height: 8) + Text(mcpServerEnabled ? "Enabled" : "Disabled") + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.secondary) + } + .padding(.horizontal, 14) + .padding(.vertical, 8) + + SettingsCardDivider() + + SettingsCardNote("When enabled, `cmux --mcp` serves the Model Context Protocol over stdio for AI tool integration (e.g. Claude Desktop, Claude Code).") + } + SettingsCard { SettingsCardRow(String(localized: "settings.automation.portBase", defaultValue: "Port Base"), subtitle: String(localized: "settings.automation.portBase.subtitle", defaultValue: "Starting port for CMUX_PORT env var."), controlWidth: pickerColumnWidth) { TextField("", value: $cmuxPortBase, format: .number) @@ -4087,6 +4131,7 @@ struct SettingsView: View { AppIconSettings.applyIcon(.automatic) socketControlMode = SocketControlSettings.defaultMode.rawValue claudeCodeHooksEnabled = ClaudeCodeIntegrationSettings.defaultHooksEnabled + mcpServerEnabled = MCPServerSettings.defaultEnabled sendAnonymousTelemetry = TelemetrySettings.defaultSendAnonymousTelemetry browserSearchEngine = BrowserSearchSettings.defaultSearchEngine.rawValue browserSearchSuggestionsEnabled = BrowserSearchSettings.defaultSearchSuggestionsEnabled diff --git a/docs/MCP-SERVER.md b/docs/MCP-SERVER.md new file mode 100644 index 000000000000..a8c083081229 --- /dev/null +++ b/docs/MCP-SERVER.md @@ -0,0 +1,97 @@ +# cmux MCP Server + +The cmux MCP Server exposes cmux functionality through the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), allowing AI tools like Claude Desktop and Claude Code to control terminal workspaces, panes, surfaces, browser, and notifications. + +## Architecture + +``` ++-----------------+ stdio +-----------------+ Unix Socket +--------------+ +| AI Tool |<──────────────>| cmux --mcp |<───────────────────>| cmux daemon | +| (MCP Client) | | (MCP Server) | | | ++-----------------+ +-----------------+ +--------------+ +``` + +- **Transport**: stdio (JSON-RPC 2.0 over stdin/stdout) +- **Backend**: Direct Unix socket RPC to the cmux daemon (no subprocess spawning) +- **Authentication**: Inherits socket password from explicit flag, `CMUX_SOCKET_PASSWORD` env var, or stored credential file + +## Setup + +### Claude Code + +Claude Code auto-discovers cmux when running inside a cmux terminal. No manual configuration needed. + +### Claude Desktop + +Add to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json`): + +```json +{ + "mcpServers": { + "cmux": { + "command": "/Applications/cmux.app/Contents/Resources/bin/cmux", + "args": ["--mcp"] + } + } +} +``` + +### Custom socket path or password + +```bash +cmux --mcp --socket /path/to/cmux.sock --password +``` + +## Tools + +The MCP server exposes 8 grouped tools. Each tool accepts an `action` parameter that maps to a socket RPC method, plus action-specific parameters. + +| Tool | Namespace | Description | +|------|-----------|-------------| +| `cmux_system` | `system.*` | Ping, identify context, list capabilities | +| `cmux_workspace` | `workspace.*` | List, create, select, close, rename workspaces | +| `cmux_window` | `window.*` | List, create, close, focus windows | +| `cmux_pane` | `pane.*` | List, focus, create, resize, swap panes | +| `cmux_surface` | `surface.*` | Read terminal output, send input/keys, split, manage surfaces | +| `cmux_notification` | `notification.*` | Create, list, clear notifications | +| `cmux_tab` | `tab.*` | Run tab actions | +| `cmux_browser` | `browser.*` | Navigate, click, fill, screenshot, evaluate JS, and 50+ browser automation actions | + +### Example: Read terminal output + +```json +{ + "name": "cmux_surface", + "arguments": { + "action": "read_text", + "surface_id": "surface:3" + } +} +``` + +### Example: Send text to a terminal + +```json +{ + "name": "cmux_surface", + "arguments": { + "action": "send_text", + "text": "ls -la\n" + } +} +``` + +## Settings + +The MCP server can be enabled or disabled in **Settings > Automation > MCP Server**. When disabled, `cmux --mcp` exits immediately with a JSON-RPC error. + +## File Structure + +``` +CLI/ +├── MCPMain.swift # stdio entry point, CLI integration +├── MCPProtocol.swift # JSON-RPC 2.0 protocol handler +├── MCPToolRegistry.swift # Grouped tool definitions with action validation +├── MCPBackend.swift # Direct Unix socket RPC to cmux daemon +└── MCPTypes.swift # JSON-RPC types and MCP message structures +``` diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py new file mode 100644 index 000000000000..dec6032a7bec --- /dev/null +++ b/tests/test_mcp_server.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +""" +Smoke tests for the cmux MCP server. + +Tests the JSON-RPC 2.0 protocol layer and grouped tool definitions by running +the cmux-mcp binary in --mcp mode via stdin/stdout. + +No cmux daemon required — tool *calls* will fail (no socket), but we +verify the command dispatch and error handling work correctly. + +Usage: + python3 tests/test_mcp_server.py [path-to-cmux-binary] +""" + +import json +import os +import subprocess +import sys + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +CMUX_BIN = None # Set in main() + + +def mcp_session(messages: list[dict]) -> list[dict | None]: + """Send a sequence of JSON-RPC messages and collect responses.""" + input_text = "\n".join(json.dumps(m) for m in messages) + "\n" + + proc = subprocess.run( + [CMUX_BIN, "--mcp"], + input=input_text, + capture_output=True, + text=True, + timeout=10, + ) + + responses = [] + for line in proc.stdout.strip().split("\n"): + line = line.strip() + if not line: + continue + responses.append(json.loads(line)) + return responses + + +def init_msg(id=1): + return { + "jsonrpc": "2.0", + "id": id, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "1.0"}, + }, + } + + +def tools_list_msg(id=2): + return {"jsonrpc": "2.0", "id": id, "method": "tools/list"} + + +def tools_call_msg(name, arguments=None, id=3): + return { + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": {"name": name, "arguments": arguments or {}}, + } + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + +passed = 0 +failed = 0 + + +def check(name, condition, detail=""): + global passed, failed + if condition: + passed += 1 + print(f" PASS {name}") + else: + failed += 1 + print(f" FAIL {name} {detail}") + + +def test_initialize(): + """initialize returns correct protocol version, capabilities, serverInfo.""" + print("\n--- test_initialize ---") + responses = mcp_session([init_msg()]) + check("got 1 response", len(responses) == 1, f"got {len(responses)}") + if not responses: + return + + r = responses[0] + check("jsonrpc is 2.0", r.get("jsonrpc") == "2.0") + check("id matches", r.get("id") == 1) + result = r.get("result", {}) + check("protocolVersion present", "protocolVersion" in result) + check("capabilities.tools present", "tools" in result.get("capabilities", {})) + si = result.get("serverInfo", {}) + check("serverInfo.name is cmux", si.get("name") == "cmux", f"got {si}") + check("serverInfo.version present", "version" in si) + + +def test_tools_list(): + """tools/list returns the 8 grouped tools with correct structure.""" + print("\n--- test_tools_list ---") + responses = mcp_session([init_msg(1), tools_list_msg(2)]) + check("got 2 responses", len(responses) == 2, f"got {len(responses)}") + if len(responses) < 2: + return + + r = responses[1] + check("id matches", r.get("id") == 2) + tools = r.get("result", {}).get("tools", []) + check("8 grouped tools registered", len(tools) == 8, f"got {len(tools)}") + + names = {t["name"] for t in tools} + expected_names = { + "cmux_system", + "cmux_workspace", + "cmux_window", + "cmux_pane", + "cmux_surface", + "cmux_notification", + "cmux_tab", + "cmux_browser", + } + check("all tool names present", names == expected_names, + f"missing={expected_names - names}, extra={names - expected_names}") + + # Each tool should have name, description, inputSchema + for t in tools: + has_fields = all(k in t for k in ("name", "description", "inputSchema")) + if not has_fields: + check(f"tool {t.get('name')} has required fields", False, str(t.keys())) + return + check("all tools have name/description/inputSchema", True) + + # All grouped tools require 'action' param + for t in tools: + schema = t.get("inputSchema", {}) + required = schema.get("required") or [] + check(f"{t['name']} requires 'action'", "action" in required, + f"required={required}") + + +def test_tool_call_dispatches(): + """tools/call dispatches to backend (will fail with socket error, which is expected).""" + print("\n--- test_tool_call_dispatches ---") + tools_to_test = [ + ("cmux_system", {"action": "ping"}), + ("cmux_system", {"action": "identify"}), + ("cmux_workspace", {"action": "list"}), + ("cmux_surface", {"action": "read_text"}), + ("cmux_surface", {"action": "send_key", "key": "enter"}), + ("cmux_surface", {"action": "send_text", "text": "hello"}), + ("cmux_window", {"action": "list"}), + ("cmux_pane", {"action": "list"}), + ("cmux_notification", {"action": "list"}), + ] + + for tool_name, args in tools_to_test: + label = f"{tool_name}/{args.get('action')}" + msgs = [init_msg(1), tools_call_msg(tool_name, args, id=2)] + responses = mcp_session(msgs) + if len(responses) < 2: + check(f"{label} got response", False, f"only {len(responses)} responses") + continue + + r = responses[1] + has_result = "result" in r + has_error = "error" in r + check(f"{label} returns result or error", has_result or has_error, str(r)) + + if has_error: + err_msg = r["error"].get("message", "") + is_connection_error = any(kw in err_msg.lower() for kw in [ + "failed to connect", "execution failed", "connection refused", + "socket", "not connected", + ]) + check(f"{label} error is backend failure (not param error)", + is_connection_error, f"error: {err_msg}") + + +def test_action_validation(): + """Grouped tools validate action names and required params. + + Note: MCPBackend transport-layer fixes (retry-only-on-transport-error, + 30s poll() read timeout) are exercised in tests/test_mcp_socket_rpc.py + which connects to a live cmux daemon socket. + """ + print("\n--- test_action_validation ---") + + # Missing action + msgs = [init_msg(1), tools_call_msg("cmux_surface", {}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("missing 'action' returns error", err.get("code") == -32602, + f"code={err.get('code')}, msg={err.get('message')}") + + # Unknown action + msgs = [init_msg(1), tools_call_msg("cmux_surface", {"action": "bogus"}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("unknown action returns error", err.get("code") == -32602, + f"code={err.get('code')}, msg={err.get('message')}") + + # Missing required param: surface.send_text needs 'text' + msgs = [init_msg(1), tools_call_msg("cmux_surface", {"action": "send_text"}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("missing required 'text' returns error", err.get("code") == -32602, + f"code={err.get('code')}, msg={err.get('message')}") + + # Missing required param: surface.send_key needs 'key' + msgs = [init_msg(1), tools_call_msg("cmux_surface", {"action": "send_key"}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("missing required 'key' returns error", err.get("code") == -32602, + f"code={err.get('code')}, msg={err.get('message')}") + + # Missing required param: surface.close needs 'surface_id' + msgs = [init_msg(1), tools_call_msg("cmux_surface", {"action": "close"}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("missing required 'surface_id' for close returns error", + err.get("code") == -32602, + f"code={err.get('code')}, msg={err.get('message')}") + + # Missing required param: workspace.select needs 'workspace_id' + msgs = [init_msg(1), tools_call_msg("cmux_workspace", {"action": "select"}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("missing required 'workspace_id' for select returns error", + err.get("code") == -32602, + f"code={err.get('code')}, msg={err.get('message')}") + + +def test_method_not_found(): + """Unknown method returns methodNotFound error.""" + print("\n--- test_method_not_found ---") + msgs = [ + init_msg(1), + {"jsonrpc": "2.0", "id": 2, "method": "unknown/method"}, + ] + responses = mcp_session(msgs) + check("got 2 responses", len(responses) == 2, f"got {len(responses)}") + if len(responses) < 2: + return + + r = responses[1] + err = r.get("error", {}) + check("error code is -32601 (methodNotFound)", err.get("code") == -32601) + + +def test_tool_not_found(): + """tools/call with unknown tool returns error.""" + print("\n--- test_tool_not_found ---") + msgs = [init_msg(1), tools_call_msg("cmux_nonexistent", {"action": "test"}, id=2)] + responses = mcp_session(msgs) + if len(responses) < 2: + check("tool not found response", False, "no response") + return + + r = responses[1] + err = r.get("error", {}) + check("returns error for unknown tool", err.get("code") == -32601, + f"got code={err.get('code')}") + + +def test_not_initialized(): + """Calling tools/list without initialize returns error.""" + print("\n--- test_not_initialized ---") + msgs = [tools_list_msg(1)] # Skip initialize + responses = mcp_session(msgs) + check("got 1 response", len(responses) == 1, f"got {len(responses)}") + if not responses: + return + + r = responses[0] + err = r.get("error", {}) + check("returns server error for uninitialized", err.get("code") == -32000, + f"got code={err.get('code')}, msg={err.get('message')}") + + +def test_socket_ownership_error(): + """Socket ownership validation prevents connecting to sockets owned by other users. + + This test documents the socket ownership (st_uid) check added to + MCPBackend.connect(). The actual validation requires a real Unix socket + owned by a different user, which cannot be reliably set up in this + protocol-level test suite. See tests/test_mcp_socket_rpc.py for the + integration test that exercises the ownership check against a live socket. + """ + print("\n--- test_socket_ownership_error ---") + check("socket ownership check documented (tested in test_mcp_socket_rpc.py)", True) + + +def test_action_name_remapping(): + """Test that action_name is remapped to action for *.action RPC methods.""" + print("\n--- test_action_name_remapping ---") + # workspace.action should remap action_name -> action + msgs = [init_msg(1), tools_call_msg("cmux_workspace", {"action": "action", "workspace_id": "test", "action_name": "close"}, id=2)] + responses = mcp_session(msgs) + # The call will fail (no socket) but should NOT fail with "missing required parameter" + if len(responses) >= 2: + err = responses[1].get("error", {}) + # Should get a backend/socket error, not an invalid params error + check("workspace.action remaps action_name", err.get("code") != -32602, + f"got invalid_params instead of backend error: {err.get('message')}") + + # surface.action should also remap action_name -> action + msgs = [init_msg(1), tools_call_msg("cmux_surface", {"action": "action", "surface_id": "test", "action_name": "close"}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("surface.action remaps action_name", err.get("code") != -32602, + f"got invalid_params instead of backend error: {err.get('message')}") + + # tab.action should also remap action_name -> action + msgs = [init_msg(1), tools_call_msg("cmux_tab", {"action": "action", "tab_id": "test", "action_name": "close"}, id=2)] + responses = mcp_session(msgs) + if len(responses) >= 2: + err = responses[1].get("error", {}) + check("tab.action remaps action_name", err.get("code") != -32602, + f"got invalid_params instead of backend error: {err.get('message')}") + + +def test_error_id_correlation(): + """Test that error responses use the request id, not a fixed id.""" + print("\n--- test_error_id_correlation ---") + # Send a request that will fail to a method that doesn't exist + msgs = [init_msg(1)] + responses = mcp_session(msgs) + if responses: + check("init response has correct id", responses[0].get("id") == 1, + f"expected id=1, got id={responses[0].get('id')}") + + # Test with a string id + msgs = [init_msg("abc")] + responses = mcp_session(msgs) + if responses: + check("string id is preserved", responses[0].get("id") == "abc", + f"expected id='abc', got id={responses[0].get('id')}") + + # Test with a higher numeric id + msgs = [init_msg(42)] + responses = mcp_session(msgs) + if responses: + check("numeric id is preserved", responses[0].get("id") == 42, + f"expected id=42, got id={responses[0].get('id')}") + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main(): + global CMUX_BIN + + if len(sys.argv) > 1: + CMUX_BIN = sys.argv[1] + else: + import glob + candidates = [ + os.path.expanduser("~/.local/bin/cmux-mcp"), + *glob.glob(os.path.expanduser( + "~/Library/Developer/Xcode/DerivedData/GhosttyTabs-*/Build/Products/Debug/cmux" + )), + "/Applications/cmux.app/Contents/Resources/bin/cmux", + ] + for c in candidates: + if os.path.isfile(c) and os.access(c, os.X_OK): + CMUX_BIN = c + break + + if not CMUX_BIN: + print("ERROR: cmux binary not found. Pass path as argument.") + sys.exit(1) + + print(f"Testing MCP server: {CMUX_BIN}") + + test_initialize() + test_tools_list() + test_tool_call_dispatches() + test_action_validation() + test_method_not_found() + test_tool_not_found() + test_not_initialized() + test_socket_ownership_error() + test_action_name_remapping() + test_error_id_correlation() + + print(f"\n{'='*50}") + print(f"Results: {passed} passed, {failed} failed") + print(f"{'='*50}") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main() diff --git a/tests/test_mcp_socket_rpc.py b/tests/test_mcp_socket_rpc.py new file mode 100644 index 000000000000..bba2d6db59bc --- /dev/null +++ b/tests/test_mcp_socket_rpc.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +""" +Integration tests for the cmux MCP server redesign. + +Validates that all grouped tool actions work correctly via direct socket RPC. +This tests the SAME code path the new MCPBackend.swift will use. + +Requires a running cmux instance with socket at /tmp/cmux.sock. + +Usage: + python3 tests/test_mcp_socket_rpc.py +""" + +import json +import os +import socket +import sys + +SOCKET_PATH = os.environ.get("CMUX_SOCKET_PATH", "/tmp/cmux.sock") + +passed = 0 +failed = 0 +skipped = 0 +req_id = 0 + + +def rpc(method, params=None): + """Send a JSON-RPC request to the cmux socket and return parsed response.""" + global req_id + req_id += 1 + payload = {"id": req_id, "method": method, "params": params or {}} + + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(5) + sock.connect(SOCKET_PATH) + sock.sendall(json.dumps(payload).encode("utf-8") + b"\n") + + data = b"" + while b"\n" not in data: + chunk = sock.recv(65536) + if not chunk: + break + data += chunk + sock.close() + + return json.loads(data.decode("utf-8")) + + +def check(name, condition, detail=""): + global passed, failed + if condition: + passed += 1 + print(f" PASS {name}") + else: + failed += 1 + print(f" FAIL {name} {detail}") + + +def skip(name, reason=""): + global skipped + skipped += 1 + print(f" SKIP {name} {reason}") + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + +def test_socket_v2_format(): + """Verify socket uses v2 format (ok/result), NOT JSON-RPC 2.0.""" + print("\n--- test_socket_v2_format ---") + r = rpc("system.ping") + check("has 'ok' field", "ok" in r) + check("ok is True", r.get("ok") is True) + check("has 'result' field", "result" in r) + check("no 'jsonrpc' field", "jsonrpc" not in r, f"found jsonrpc={r.get('jsonrpc')}") + check("result has pong", r.get("result", {}).get("pong") is True) + + +def test_socket_v2_error_format(): + """Verify error responses use v2 format.""" + print("\n--- test_socket_v2_error_format ---") + r = rpc("nonexistent.method") + check("ok is False", r.get("ok") is False) + check("has 'error' field", "error" in r) + err = r.get("error", {}) + check("error has 'code'", "code" in err) + check("error has 'message'", "message" in err) + + +def test_system_actions(): + """Test system.* methods.""" + print("\n--- test_system_actions ---") + + # ping + r = rpc("system.ping") + check("system.ping ok", r.get("ok") is True) + + # identify + r = rpc("system.identify") + check("system.identify ok", r.get("ok") is True) + result = r.get("result", {}) + check("identify has focused", "focused" in result) + + # capabilities + r = rpc("system.capabilities") + check("system.capabilities ok", r.get("ok") is True) + result = r.get("result", {}) + check("capabilities has methods", "methods" in result) + methods = result.get("methods", []) + check("methods is non-empty list", len(methods) > 0) + + +def test_workspace_actions(): + """Test workspace.* methods.""" + print("\n--- test_workspace_actions ---") + + # list + r = rpc("workspace.list") + check("workspace.list ok", r.get("ok") is True) + + # current + r = rpc("workspace.current") + check("workspace.current ok", r.get("ok") is True) + result = r.get("result", {}) + ws_ref = result.get("workspace_ref", "") + check("current has workspace_ref", ws_ref.startswith("workspace:"), f"got {ws_ref}") + + # create + close (create, then immediately close to clean up) + r = rpc("workspace.create") + check("workspace.create ok", r.get("ok") is True) + new_ws = r.get("result", {}).get("workspace_ref", "") + if new_ws: + # Switch back to original workspace before closing + rpc("workspace.select", {"workspace_id": ws_ref}) + r2 = rpc("workspace.close", {"workspace_id": new_ws}) + check("workspace.close ok", r2.get("ok") is True) + else: + skip("workspace.close", "no workspace_ref from create") + + # next/previous (just verify they don't error) + r = rpc("workspace.next") + check("workspace.next ok", r.get("ok") is True) + r = rpc("workspace.previous") + check("workspace.previous ok", r.get("ok") is True) + + +def test_window_actions(): + """Test window.* methods.""" + print("\n--- test_window_actions ---") + + r = rpc("window.list") + check("window.list ok", r.get("ok") is True) + + r = rpc("window.current") + check("window.current ok", r.get("ok") is True) + + +def test_pane_actions(): + """Test pane.* methods.""" + print("\n--- test_pane_actions ---") + + r = rpc("pane.list") + check("pane.list ok", r.get("ok") is True) + + r = rpc("pane.surfaces") + check("pane.surfaces ok", r.get("ok") is True) + + # pane.focus requires pane_id - test with invalid to check error handling + r = rpc("pane.focus", {}) + check("pane.focus without pane_id fails", r.get("ok") is False) + + +def test_surface_actions(): + """Test surface.* methods — the most critical group.""" + print("\n--- test_surface_actions ---") + + # list + r = rpc("surface.list") + check("surface.list ok", r.get("ok") is True) + + # current + r = rpc("surface.current") + check("surface.current ok", r.get("ok") is True) + + # read_text (THE BUG that started all this) + r = rpc("surface.read_text") + check("surface.read_text ok", r.get("ok") is True) + result = r.get("result", {}) + check("read_text has 'text' field", "text" in result) + check("read_text text is string", isinstance(result.get("text"), str)) + + # read_text with specific surface (use current surface dynamically) + cur = rpc("surface.current") + cur_ref = cur.get("result", {}).get("surface_ref", "") + if cur_ref: + r2 = rpc("surface.read_text", {"surface_id": cur_ref}) + check(f"surface.read_text with surface_id '{cur_ref}' ok", r2.get("ok") is True) + else: + skip("surface.read_text with surface_id", "no current surface") + + # send_text requires text param + r = rpc("surface.send_text", {}) + check("surface.send_text without text fails", r.get("ok") is False) + + # send_key requires key param + r = rpc("surface.send_key", {}) + check("surface.send_key without key fails", r.get("ok") is False) + + # split requires direction + r = rpc("surface.split", {}) + check("surface.split without direction fails", r.get("ok") is False) + + # trigger_flash (safe, no side effects) + r = rpc("surface.trigger_flash") + check("surface.trigger_flash ok", r.get("ok") is True) + + # health + r = rpc("surface.health") + check("surface.health ok", r.get("ok") is True) + + +def test_notification_actions(): + """Test notification.* methods.""" + print("\n--- test_notification_actions ---") + + # create + r = rpc("notification.create", {"title": "MCP Test", "body": "Socket RPC test"}) + check("notification.create ok", r.get("ok") is True) + + # list + r = rpc("notification.list") + check("notification.list ok", r.get("ok") is True) + + # clear + r = rpc("notification.clear") + check("notification.clear ok", r.get("ok") is True) + + +def test_ref_ids_accepted(): + """Verify socket accepts ref-format IDs (workspace:N, surface:N).""" + print("\n--- test_ref_ids_accepted ---") + + # Get current IDs first + r = rpc("system.identify") + result = r.get("result", {}).get("focused", {}) + ws_ref = result.get("workspace_ref", "") + surface_ref = result.get("surface_ref", "") + + if ws_ref: + r = rpc("workspace.select", {"workspace_id": ws_ref}) + check(f"workspace.select with ref '{ws_ref}' ok", r.get("ok") is True) + else: + skip("workspace ref test", "no workspace_ref") + + if surface_ref: + r = rpc("surface.read_text", {"surface_id": surface_ref}) + check(f"surface.read_text with ref '{surface_ref}' ok", r.get("ok") is True) + else: + skip("surface ref test", "no surface_ref") + + +def test_unknown_method(): + """Verify unknown methods return proper error.""" + print("\n--- test_unknown_method ---") + r = rpc("totally.bogus.method") + check("unknown method returns ok=false", r.get("ok") is False) + err = r.get("error", {}) + check("error code is method_not_found", err.get("code") == "method_not_found") + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main(): + if not os.path.exists(SOCKET_PATH): + print(f"ERROR: Socket not found at {SOCKET_PATH}") + print("Make sure cmux is running.") + sys.exit(1) + + # Quick connectivity check + try: + r = rpc("system.ping") + if not r.get("ok"): + print(f"ERROR: Socket ping failed: {r}") + sys.exit(1) + except Exception as e: + print(f"ERROR: Cannot connect to {SOCKET_PATH}: {e}") + sys.exit(1) + + print(f"Testing direct socket RPC at {SOCKET_PATH}") + + test_socket_v2_format() + test_socket_v2_error_format() + test_system_actions() + test_workspace_actions() + test_window_actions() + test_pane_actions() + test_surface_actions() + test_notification_actions() + test_ref_ids_accepted() + test_unknown_method() + + print(f"\n{'='*50}") + print(f"Results: {passed} passed, {failed} failed, {skipped} skipped") + print(f"{'='*50}") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main()