Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
270 changes: 270 additions & 0 deletions CLI/MCPBackend.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
// 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, idFormat: String = "refs") {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
self.socketPath = socketPath
self.password = password
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Copilot AI Mar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idFormat is accepted by MCPBackend but never used. This makes cmux --mcp --id-format ... appear supported while being silently ignored. Either remove the parameter (and related CLI flag passthrough) or implement the intended behavior (or at least document that MCP/socket mode only supports ref IDs).

Copilot uses AI. Check for mistakes.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — idFormat parameter removed entirely. See commit 3c3f3bc.


deinit {
disconnect()
}

// MARK: - Connection Management

/// Connect to the cmux Unix socket.
private func connect() throws {
disconnect()

let fd = socket(AF_UNIX, SOCK_STREAM, 0)
Comment on lines +57 to +71

ghost Mar 3, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Verify socket ownership before connecting

This backend now connects directly to any socket path without checking file ownership, unlike SocketClient.connect in CLI/cmux.swift which guards st_uid == getuid() to prevent fake-socket attacks. With the default /tmp/cmux.sock, a different local user can pre-create a socket and receive MCP traffic (including optional auth password), so the new transport regresses a previously enforced security boundary.

Useful? React with 👍 / 👎.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — socket ownership validation (stat + st_uid == getuid()) added in MCPBackend.connect(). See commit 3c3f3bc.

guard fd >= 0 else {
throw MCPError.executionFailed("Failed to create socket: \(String(cString: strerror(errno)))")
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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.executionFailed("Socket path too long: \(socketPath)")
}
Comment on lines +56 to +83

Copilot AI Mar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

connect() does not verify the Unix socket file is owned by the current user. The existing CLI SocketClient.connect() performs an ownership check (stat + st_uid == getuid()) to avoid fake-socket attacks. For parity and security, add the same validation here (or reuse SocketClient) before connecting to a user-provided socketPath.

Copilot uses AI. Check for mistakes.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — socket ownership validation (stat + st_uid == getuid()) added in MCPBackend.connect(). See commit 3c3f3bc.


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<sockaddr_un>.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.executionFailed("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
throw MCPError.executionFailed("Socket write failed: \(String(cString: strerror(errno)))")
}
if written == 0 {
throw MCPError.executionFailed("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.
private func readLine() throws -> Data {
var buffer = Data()
let newline = UInt8(ascii: "\n")
var chunk = [UInt8](repeating: 0, count: 4096)

while true {
let bytesRead = Darwin.read(socketFd, &chunk, chunk.count)
if bytesRead < 0 {
if errno == EINTR { continue } // interrupted by signal, retry
disconnect()
throw MCPError.executionFailed("Socket read failed: \(String(cString: strerror(errno)))")
}
if bytesRead == 0 {
// EOF — connection closed by daemon
disconnect()
if buffer.isEmpty {
throw MCPError.executionFailed("Socket connection closed")
}
break
}
Comment on lines +185 to +192

ghost Mar 5, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don’t return partial frames when the daemon closes the socket.

At Line 185-Line 192, EOF with a non-empty buffer currently returns partial payload, which then fails later as a non-transport parse error and skips the reconnect path.

🧯 Suggested fix
             if bytesRead == 0 {
                 // EOF — connection closed by daemon
                 disconnect()
-                if buffer.isEmpty {
-                    throw MCPError.transportError("Socket connection closed")
-                }
-                break
+                throw MCPError.transportError(
+                    buffer.isEmpty
+                        ? "Socket connection closed"
+                        : "Socket connection closed mid-response"
+                )
             }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CLI/MCPBackend.swift` around lines 185 - 192, On EOF (bytesRead == 0) inside
the read loop in MCPBackend.swift, don't allow a non-empty buffer to be returned
as a partial frame; instead after calling disconnect() detect if buffer.isEmpty
is false and throw a transport-level error (use MCPError.transportError with a
clear message like "Socket closed with partial frame") so the caller treats this
as a transport failure and triggers reconnect logic; locate the bytesRead == 0
branch, the buffer variable, the disconnect() call and replace the current
behavior that proceeds with a partial payload by throwing
MCPError.transportError.

if let nlIndex = chunk[0..<bytesRead].firstIndex(of: newline) {
buffer.append(contentsOf: chunk[0..<nlIndex])
break
} else {
buffer.append(contentsOf: chunk[0..<bytesRead])
}
}

Copilot AI Mar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

readLine() blocks on a plain read() loop with no timeout/polling. If the daemon never replies (or the connection stalls), the MCP server can hang indefinitely waiting for a newline. Consider using poll/select with a reasonable timeout (similar to SocketClient.send() in CLI/cmux.swift) and surface a timeout error so the client can recover.

Copilot uses AI. Check for mistakes.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — readLine() now uses poll() with a 30-second timeout before each read() call. See commit 3c3f3bc.


return buffer
}

// MARK: - RPC

/// Send an RPC request to the cmux socket and return the result.
///
/// The cmux socket v2 protocol uses `{id, method, params}` requests and
/// `{id, ok, result}` or `{id, ok, error}` responses — NOT JSON-RPC 2.0.
public func rpc(method: String, params: [String: Any] = [:]) throws -> [String: Any] {
lock.lock()
defer { lock.unlock() }

// Try once, reconnect on failure, try again
do {
try ensureConnected()
return try sendRPC(method: method, params: params)
} catch {
// Connection may be stale — reconnect and retry once
disconnect()
try ensureConnected()
return try sendRPC(method: method, params: params)

Copilot AI Mar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rpc(method:params:) retries the RPC on any thrown error, including legitimate remote errors (ok=false). This can cause non-idempotent actions (create/close/move/etc.) to be executed twice and can mask the original failure. Only retry on transport-level failures (connect/read/write) and propagate application-level errors without retrying (e.g., differentiate error types or inspect where the error originated).

Suggested change
// Try once, reconnect on failure, try again
do {
try ensureConnected()
return try sendRPC(method: method, params: params)
} catch {
// Connection may be stale — reconnect and retry once
disconnect()
try ensureConnected()
return try sendRPC(method: method, params: params)
// Try once, reconnect on transport-level failure, try again
do {
try ensureConnected()
return try sendRPC(method: method, params: params)
} catch let transportError as POSIXError {
// Transport-level POSIX error: connection may be stale — reconnect and retry once
disconnect()
try ensureConnected()
return try sendRPC(method: method, params: params)
} catch let transportNSError as NSError where transportNSError.domain == NSPOSIXErrorDomain {
// Transport-level NSError in NSPOSIXErrorDomain: reconnect and retry once
disconnect()
try ensureConnected()
return try sendRPC(method: method, params: params)
} catch {
// Application-level or unknown error: do not retry
throw error

Copilot uses AI. Check for mistakes.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — rpc() now only retries on MCPError.transportError, not on application errors. Non-idempotent operations will not be double-executed. See commit 3c3f3bc.

}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// Low-level: send a single RPC request and read the response.
private func sendRPC(method: String, params: [String: Any]) 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()

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")
}
Comment on lines +235 to +258

Copilot AI Mar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The RPC layer never validates that the response id matches the request id. If the socket ever returns a stale/out-of-order response (or if the connection is reused across calls in the future), this can associate the wrong response with a request. It would be safer to check the id field and treat mismatches as a protocol/transport error.

Copilot uses AI. Check for mistakes.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — error response now extracts and preserves request id from raw JSON. See commit d8ca8d2.

Comment on lines +251 to +258

ghost Mar 3, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Validate response id matches the in-flight request.

sendRPC sends an id but never verifies the response id. A stale/misaligned frame can be accepted as the current response.

🔧 Suggested correlation check
-        requestId += 1
+        requestId += 1
+        let currentRequestId = requestId
         let request: [String: Any] = [
-            "id": requestId,
+            "id": currentRequestId,
             "method": method,
             "params": params
         ]
@@
         guard let response = try JSONSerialization.jsonObject(with: responseData) as? [String: Any] else {
             throw MCPError.executionFailed("Invalid response from socket")
         }
+        let responseId = (response["id"] as? NSNumber)?.intValue
+        guard responseId == currentRequestId else {
+            disconnect()
+            throw MCPError.transportError("Mismatched response id (expected \(currentRequestId), got \(String(describing: response["id"])))")
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CLI/MCPBackend.swift` around lines 250 - 257, The response parsing in sendRPC
currently trusts the socket frame without correlating request/response ids;
update sendRPC to extract the response["id"] from the parsed response (response
variable from responseData) and verify it matches the request id you sent (the
id variable used when sending the RPC); if it is missing or does not match,
throw MCPError.executionFailed with a clear message like "Mismatched or missing
response id" to reject stale/aligned frames and only proceed when response["id"]
== id and response["ok"] is true.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — error response now extracts and preserves request id from raw JSON. See commit d8ca8d2.

ghost Mar 4, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
git show d8ca8d2 -- CLI/MCPBackend.swift

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Check recent commits
git log --oneline -10

# Also check current state of sendRPC in MCPBackend.swift
rg -n "responseId|response\[.id.\]|currentRequestId|Mismatched" CLI/MCPBackend.swift

Length of output: 654


🏁 Script executed:

#!/bin/bash
# Show the sendRPC function and surrounding context in current file
rg -n "sendRPC|requestId|response\[" CLI/MCPBackend.swift -A 3

# Also check the diff introduced in d8ca8d2 for MCPBackend.swift via GitHub CLI
gh api repos/manaflow-ai/cmux/commits/d8ca8d2 --jq '.files[] | select(.filename == "CLI/MCPBackend.swift") | .patch'

Length of output: 1717


🏁 Script executed:

#!/bin/bash
# Get list of files changed in d8ca8d2
gh api repos/manaflow-ai/cmux/commits/d8ca8d2 --jq '.files[].filename'

# Get the patch for MCPBackend specifically
gh api repos/manaflow-ai/cmux/commits/d8ca8d2 --jq '.files[] | select(.filename | contains("MCP")) | {file: .filename, patch: .patch}'

Length of output: 2992


@Efan404, thanks for the update! I reviewed commit d8ca8d2 and can see the fix in CLI/MCPMain.swift, which now extracts the request id from the raw JSON before constructing the JSONRPCErrorResponse — that's a good improvement for client-facing error correlation.

However, that addresses a slightly different concern from the original flag. The original issue was about MCPBackend.sendRPC not validating the response id received from the cmux daemon socket. Looking at the current CLI/MCPBackend.swift, sendRPC is still unchanged:

requestId += 1
let request: [String: Any] = [
    "id": requestId,   // sent to daemon
    ...
]
// ... writeAll / readLine ...
// response["id"] is never compared to requestId
guard let ok = response["ok"] as? Bool else { ... }

To summarize the distinction:

Concern File Status
MCP stdio error response carries correct client request id MCPMain.swift ✅ Fixed in d8ca8d2
sendRPC validates daemon response id matches sent request id MCPBackend.swift ❌ Still missing

The socket-level check in MCPBackend.sendRPC would catch a misaligned frame from the daemon (e.g., a stale buffered response after a reconnect). The suggested fix from the original comment still applies here:

requestId += 1
let currentRequestId = requestId
let request: [String: Any] = [
    "id": currentRequestId,
    "method": method,
    "params": params
]

// ... after parsing response ...

let responseId = (response["id"] as? NSNumber)?.intValue
guard responseId == currentRequestId else {
    disconnect()
    throw MCPError.transportError(
        "Mismatched response id (expected \(currentRequestId), got \(String(describing: response["id"])))"
    )
}

Would you like to address this remaining check in MCPBackend.swift, or should I open a follow-up issue for it?


🧠 Learnings used
Learnt from: CR
Repo: manaflow-ai/cmux PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-03-03T05:48:04.237Z
Learning: Applies to **/*Socket*.swift : Do not use `DispatchQueue.main.sync` for high-frequency socket telemetry commands (`report_*`, `ports_kick`, status/progress/log metadata updates); parse/validate/dedupe off-main and schedule UI/model mutation with `DispatchQueue.main.async` only when needed

Learnt from: CR
Repo: manaflow-ai/cmux PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-03-03T05:48:04.237Z
Learning: Applies to **/*Socket*.swift : Socket/CLI commands must not steal macOS app focus (no app activation/window raising side effects); only explicit focus-intent commands may mutate in-app focus/selection


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 empty dict for simple ok responses
if let result = response["result"] as? [String: Any] {
return result
}

Copilot AI Mar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sendRPC only returns response["result"] when it is a [String: Any], and otherwise returns [:]. The socket v2 protocol supports arbitrary JSON results (arrays/strings/numbers/etc.), so this will silently drop valid responses for methods that return non-dictionary payloads. Consider returning Any (or AnyCodable) from rpc/sendRPC, and have rpcForTool JSON-encode that value for output.

Suggested change
// Return the result dict, or empty dict for simple ok responses
if let result = response["result"] as? [String: Any] {
return result
}
// Return the result dict when present, or wrap non-dict results to avoid data loss.
if let resultDict = response["result"] as? [String: Any] {
return resultDict
} else if let resultValue = response["result"] {
// For scalar/array results, wrap in a dictionary so callers still receive the data.
return ["value": resultValue]
}
// No result field: return empty dict for simple ok responses

Copilot uses AI. Check for mistakes.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — sendRPC() now wraps non-dict results (arrays, strings, etc.) in ["value": result]. See commit 3c3f3bc.

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] = [:]) throws -> MCPToolCallResult {
let result = try rpc(method: method, params: params)
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
}
}
119 changes: 119 additions & 0 deletions CLI/MCPMain.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// 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, idFormat: String = "refs") {
// Initialize backend
let backend = MCPBackend(socketPath: socketPath, password: password, idFormat: idFormat)

ghost Mar 3, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Use the shared socket-path resolver instead of hardcoded /tmp/cmux.sock.

Current defaults can diverge from normal socket selection (environment overrides/debug paths), causing MCP mode to connect to the wrong daemon unless --socket is always provided.

💡 Suggested fix
-public func runMCPServer(socketPath: String = "/tmp/cmux.sock", password: String? = nil, idFormat: String = "refs") {
+public func runMCPServer(
+    socketPath: String = SocketControlSettings.socketPath(),
+    password: String? = nil,
+    idFormat: String = "refs"
+) {
@@
-        var socketPath = "/tmp/cmux.sock"
+        var socketPath = SocketControlSettings.socketPath()

Also applies to: 71-73

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CLI/MCPMain.swift` around lines 9 - 12, The default socketPath argument in
runMCPServer is hardcoded to "/tmp/cmux.sock", causing MCP mode to bypass the
shared socket-path resolver; change runMCPServer's default to use the
common/shared resolver function (the same utility used by the rest of the CLI)
instead of the literal "/tmp/cmux.sock" and ensure MCPBackend is constructed
with that resolved path (update the runMCPServer declaration and any other
occurrence constructing MCPBackend in this file, e.g., the other MCP startup
call that currently passes "/tmp/cmux.sock").

// 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())
let errResp = JSONRPCErrorResponse(
id: .number(0),
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
error: JSONRPCError(
code: JSONRPCErrorCode.internalError.rawValue,
message: "Internal error: \(error.localizedDescription)"
)
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 idFormat = "refs"
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 "--id-format":
if i + 1 < args.count {
idFormat = 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)!)

ghost Mar 3, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

force unwrap could crash if UTF-8 encoding fails

Suggested change
stderr.write(debugMsg.data(using: .utf8)!)
stderr.write((debugMsg.data(using: .utf8) ?? Data()))

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — replaced force unwrap with ?? Data(). See commit d8ca8d2.

}

// Run MCP server
runMCPServer(socketPath: socketPath, password: password, idFormat: idFormat)
}
}
Comment on lines +79 to +125

Copilot AI Mar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MCMain appears to be unused (the actual entrypoint is CMUXTermMain in CLI/cmux.swift, which calls runMCPServer directly). Keeping a second, slightly different argument parser here can drift from the real behavior and confuse future edits (the name also looks like it may have been intended as MCPMain). Consider removing it or wiring it up so there’s a single source of truth for MCP CLI parsing.

Suggested change
// 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 idFormat = "refs"
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 "--id-format":
if i + 1 < args.count {
idFormat = 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)!)
}
// Run MCP server
runMCPServer(socketPath: socketPath, password: password, idFormat: idFormat)
}
}

Copilot uses AI. Check for mistakes.

ghost Mar 4, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MCMain is kept as an alternative entry point for standalone use (e.g. symlinked as cmux-mcp). The primary entry is through cmux --mcp in CLI/cmux.swift.

Loading