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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
364 changes: 364 additions & 0 deletions Tests/StackNudgePanelCoreTests/MCPServerTests.swift

Large diffs are not rendered by default.

302 changes: 302 additions & 0 deletions docs/design/local-mcp.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions docs/design/service-extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ you), `active` (running, but the agent reports no live state) or `ended`.
name someone chose) and `claude_session` are left out when unknown. No paths,
tab names or prompt text: `pid` and `claude_session` are there so a caller seen
elsewhere, such as an MCP bridge, can be matched to its session. The shape is
`SessionSnapshot`, which the MCP server is to read too, so the two can't
disagree about what waiting means. It's worked out again whenever Events or the
`SessionSnapshot`, which the MCP server's `sessions_list` reads too, so the
two can't disagree about what waiting means. It's worked out again whenever Events or the
session poll changes, so `waiting` can still show for up to one poll (10 s while
the panel is hidden) after a hook has given up on its prompt.

Expand Down
110 changes: 110 additions & 0 deletions panel/MCPAppContext.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import Combine
import Foundation

// The MCP server's view of the running app. Requests arrive on connection
// threads, and nav and the stores are main-thread objects, so every read hops
// to main.
final class MCPAppContext: MCPContext {

private weak var nav: PanelNav?
private weak var store: EventStore?
private weak var sessionStore: SessionStore?

init(nav: PanelNav, store: EventStore, sessions: SessionStore) {
self.nav = nav
self.store = store
self.sessionStore = sessions
}

var serverVersion: String {
BuildVersion.current()?.string ?? "unknown"
}

func settings() -> [SettingSnapshot] {
onMain { nav.map(SettingsRegistry.snapshot) ?? [] }
}

func sessions() -> [[String: Any]] {
onMain {
guard let sessionStore else { return [] }
return MCPSessions.list(sessionStore.sessions, events: store?.events ?? []).map(MCPSessions.json)
}
}

private func onMain<T>(_ work: () -> T) -> T {
Thread.isMainThread ? work() : DispatchQueue.main.sync(execute: work)
}
}

// The sessions as a client sees them: the shape `event:session` sends, so the
// two agree on what waiting means, without the ones that have ended. Pure, for
// tests.
enum MCPSessions {

static func list(_ sessions: [Session], events: [NudgeEvent],
isBlocking: (NudgeEvent) -> Bool = { $0.isStillBlocking }) -> [SessionSnapshot] {
SessionSnapshot.list(sessions: sessions, events: events, isBlocking: isBlocking).filter { $0.state != .ended }
}

static func json(_ snapshot: SessionSnapshot) -> [String: Any] {
var entry: [String: Any] = ["session": snapshot.handle, "pid": snapshot.pid, "agent": snapshot.agent,
"state": snapshot.state.rawValue]
if let repo = snapshot.repo { entry["repo"] = repo }
if let name = snapshot.name { entry["name"] = name }
if let id = snapshot.claudeSessionID { entry["claudeSessionId"] = id }
return entry
}
}

// Watches the app for changes the server's resources describe and tells every
// connected client: a setting's value, and the sessions list. Debounced, and
// compared against what was last sent, so a burst of @Published changes that
// leaves the values as they were sends nothing.
final class MCPChangeWatcher {

private let server: MCPServer
private weak var nav: PanelNav?
private weak var store: EventStore?
private weak var sessionStore: SessionStore?
private var lastSettings: [String: SettingValue] = [:]
private var lastSessions: [SessionSnapshot] = []
private var cancellables = Set<AnyCancellable>()

init(server: MCPServer, nav: PanelNav, store: EventStore, sessions: SessionStore) {
self.server = server
self.nav = nav
self.store = store
self.sessionStore = sessions
lastSettings = Self.values(SettingsRegistry.snapshot(nav))
lastSessions = currentSessions()
Publishers.Merge3(nav.objectWillChange.map { _ in () },
store.objectWillChange.map { _ in () },
sessions.objectWillChange.map { _ in () })
.debounce(for: .milliseconds(250), scheduler: DispatchQueue.main)
.sink { [weak self] in self?.publish() }
.store(in: &cancellables)
}

private func publish() {
guard let nav else { return }
let snapshot = SettingsRegistry.snapshot(nav)
let changed = snapshot.filter { lastSettings[$0.key] != $0.value }
lastSettings = Self.values(snapshot)
var uris = MCPSession.settingsURIs(changed: changed)
let sessions = currentSessions()
if sessions != lastSessions {
lastSessions = sessions
uris.insert(MCPSession.sessionsURI)
}
server.resourcesUpdated(uris)
}

private static func values(_ snapshot: [SettingSnapshot]) -> [String: SettingValue] {
Dictionary(snapshot.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
}

private func currentSessions() -> [SessionSnapshot] {
guard let sessionStore else { return [] }
return MCPSessions.list(sessionStore.sessions, events: store?.events ?? [])
}
}
156 changes: 156 additions & 0 deletions panel/MCPBridge.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import Darwin
import Foundation

// `stack-nudge --mcp`: what an MCP client launches. It speaks no MCP itself.
// It tells the running app who launched it, then relays JSON-RPC lines
// between the client's stdio and ~/.stack-nudge/mcp.sock until either side
// closes, so the server lives in one place, the app (docs/design/local-mcp.md,
// "Transport").
//
// claude mcp add stack-nudge -- ~/Applications/StackNudge.app/Contents/MacOS/stack-nudge --mcp
enum MCPBridge {

static let flag = "--mcp"

static func runIfAsked() {
guard CommandLine.arguments.contains(flag) else { return }
exit(run(socketPath: MCPServer.defaultSocketPath))
}

// The first line on the socket: what the bridge can tell about its client
// from its own process. The app trusts this rather than anything a model
// says, because it comes from the process the client launched.
static func hello(environment: [String: String] = ProcessInfo.processInfo.environment,
parentPID: Int32 = getppid()) -> [String: Any] {
var hello: [String: Any] = ["type": "hello", "parentPid": Int(parentPID)]
if let session = environment["CLAUDE_CODE_SESSION_ID"], !session.isEmpty {
hello["claudeSessionId"] = session
}
if let app = appName(forPID: parentPID) { hello["parentApp"] = app }
return hello
}

// "Claude" for /Applications/Claude.app/Contents/..., nil for a process
// that isn't inside an app bundle (a CLI such as claude or codex).
static func appName(forPID pid: Int32) -> String? {
var buffer = [CChar](repeating: 0, count: 4096) // PROC_PIDPATHINFO_MAXSIZE
guard proc_pidpath(pid, &buffer, UInt32(buffer.count)) > 0 else { return nil }
return appName(fromExecutablePath: String(cString: buffer))
}

static func appName(fromExecutablePath path: String) -> String? {
guard let range = path.range(of: ".app/") else { return nil }
return (String(path[..<range.lowerBound]) as NSString).lastPathComponent
}

// Exit status: 0 when either side closes normally.
static func run(socketPath: String) -> Int32 {
guard let socket = connect(to: socketPath) else {
serveNotRunning()
return 0
}
guard let helloLine = MCPProtocol.encode(hello()), writeAll(socket, helloLine) else { return 1 }
let done = DispatchSemaphore(value: 0)
let toApp = Thread {
relay(from: STDIN_FILENO, to: socket)
Darwin.shutdown(socket, SHUT_WR)
done.signal()
}
let toClient = Thread {
relay(from: socket, to: STDOUT_FILENO)
done.signal()
}
toApp.start()
toClient.start()
// Either direction ending ends the bridge: the client went away, or the
// app quit.
done.wait()
Darwin.close(socket)
return 0
}

private static func connect(to path: String) -> Int32? {
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
guard fd >= 0 else { return nil }
var addr = sockaddr_un()
addr.sun_family = sa_family_t(AF_UNIX)
let bytes = path.utf8CString
guard bytes.count <= MemoryLayout.size(ofValue: addr.sun_path) else { Darwin.close(fd); return nil }
withUnsafeMutableBytes(of: &addr.sun_path) { dst in
bytes.withUnsafeBytes { src in _ = memcpy(dst.baseAddress, src.baseAddress, bytes.count) }
}
let status = withUnsafePointer(to: &addr) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}
guard status == 0 else { Darwin.close(fd); return nil }
return fd
}

private static func relay(from source: Int32, to destination: Int32) {
var chunk = [UInt8](repeating: 0, count: 16384)
while true {
let n = read(source, &chunk, chunk.count)
if n <= 0 { return }
guard writeAll(destination, Data(chunk[0..<n])) else { return }
}
}

@discardableResult
private static func writeAll(_ fd: Int32, _ data: Data) -> Bool {
data.withUnsafeBytes { buffer in
var offset = 0
while offset < buffer.count {
let n = write(fd, buffer.baseAddress! + offset, buffer.count - offset)
if n <= 0 { return false }
offset += n
}
return true
}
}

// MARK: - The app isn't running

static let notRunning = "stack-nudge isn't running, so none of its tools are available. Open StackNudge "
+ "and restart this MCP server."

// Answers the client so its startup doesn't fail, with no tools and a line
// saying why. It never launches the app.
private static func serveNotRunning() {
var reader = MCPLineReader(fd: STDIN_FILENO)
while let line = reader.next() {
guard let message = MCPProtocol.parse(line),
let reply = notRunningReply(to: message),
let data = MCPProtocol.encode(reply)
else { continue }
writeAll(STDOUT_FILENO, data)
}
}

static func notRunningReply(to message: [String: Any]) -> [String: Any]? {
guard let id = MCPProtocol.requestID(of: message), let method = message["method"] as? String else { return nil }
let info: [String: Any] = ["name": "stack-nudge", "version": "not running"]
switch method {
case "initialize":
let asked = (message["params"] as? [String: Any])?["protocolVersion"] as? String ?? ""
let version = MCPProtocol.legacyVersions.contains(asked) ? asked : MCPProtocol.legacyVersions[0]
return MCPProtocol.response(id: id, result: ["protocolVersion": version, "capabilities": ["tools": [:] as [String: Any]],
"serverInfo": info, "instructions": notRunning])
case "server/discover":
return MCPProtocol.response(id: id, result: ["resultType": "complete",
"supportedVersions": [MCPProtocol.currentVersion],
"capabilities": ["tools": [:] as [String: Any]],
"instructions": notRunning,
"_meta": [MCPProtocol.metaServerInfo: info]])
case "ping":
return MCPProtocol.response(id: id, result: [:])
case "tools/list":
return MCPProtocol.response(id: id, result: ["tools": [] as [Any], "resultType": "complete"])
case "resources/list":
return MCPProtocol.response(id: id, result: ["resources": [] as [Any], "resultType": "complete"])
default:
return MCPProtocol.error(id: id, code: MCPProtocol.methodNotFound, message: notRunning)
}
}
}
Loading
Loading