Repository navigation
feat: MCP Server with direct socket RPC #794
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 10 commits
1b263ad
a30d0cf
b8d8656
6bd78ef
ffd177c
e6dd17f
4c5f88f
04dc146
6789eb5
5c2c8a3
5848480
3c3f3bc
d8ca8d2
cbd5dd7
fe12f3c
f63197e
906da06
c2177b1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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") { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| self.socketPath = socketPath | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| self.password = password | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This backend now connects directly to any socket path without checking file ownership, unlike Useful? React with 👍 / 👎.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)))") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
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
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if let nlIndex = chunk[0..<bytesRead].firstIndex(of: newline) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| buffer.append(contentsOf: chunk[0..<nlIndex]) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| break | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } else { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| buffer.append(contentsOf: chunk[0..<bytesRead]) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 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) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // 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 |
There was a problem hiding this comment.
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.
Copilot
AI
Mar 3, 2026
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
Copilot
AI
Mar 3, 2026
There was a problem hiding this comment.
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.
| // 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 |
There was a problem hiding this comment.
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.
| 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) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use the shared socket-path resolver instead of hardcoded Current defaults can diverge from normal socket selection (environment overrides/debug paths), causing MCP mode to connect to the wrong daemon unless 💡 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 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // 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), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| error: JSONRPCError( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| code: JSONRPCErrorCode.internalError.rawValue, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| message: "Internal error: \(error.localizedDescription)" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
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)!) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. force unwrap could crash if UTF-8 encoding fails
Suggested change
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // 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) | |
| } | |
| } |
There was a problem hiding this comment.
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.
Uh oh!
There was an error while loading. Please reload this page.