From 37e1593537df35173b957d16742814a5c1ad3583 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Tue, 24 Nov 2026 21:38:02 +0000 Subject: [PATCH 1/2] feat(mcp): stack-nudge's events over MCP Events, push and poll --- .../MCPEventsTests.swift | 215 ++++++++++++++++ docs/design/local-mcp.md | 24 +- panel/MCPAppContext.swift | 57 +++++ panel/MCPEvents.swift | 229 ++++++++++++++++++ panel/MCPServer.swift | 46 +++- panel/MCPSession.swift | 146 ++++++++++- panel/Panel.swift | 25 +- 7 files changed, 723 insertions(+), 19 deletions(-) create mode 100644 Tests/StackNudgePanelCoreTests/MCPEventsTests.swift create mode 100644 panel/MCPEvents.swift diff --git a/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift b/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift new file mode 100644 index 0000000..312f5a4 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift @@ -0,0 +1,215 @@ +import XCTest + +@testable import StackNudgePanelCore + +// MCP Events: the ring, cursors and replay, and push and poll through the +// protocol core. +final class MCPEventHubTests: XCTestCase { + + private var clock = Date(timeIntervalSince1970: 1_000_000) + + private func hub() -> MCPEventHub { + MCPEventHub(epoch: "e1", now: { [unowned self] in self.clock }) + } + + func testANullCursorStartsFromNow() { + let hub = hub() + hub.emit("session.stopped", data: ["agent": "claude"]) + let replay = hub.replay(name: "session.stopped", arguments: [:], cursor: nil, maxAgeMs: nil) + XCTAssertTrue(replay.events.isEmpty) + XCTAssertEqual(hub.cursor(replay.cursor), "e1.1") + XCTAssertFalse(replay.truncated) + } + + func testACursorReplaysWhatWasMissedThatMatches() { + let hub = hub() + hub.emit("session.stopped", data: ["agent": "claude"]) + hub.emit("session.stopped", data: ["agent": "codex"]) + hub.emit("nudge.raised", data: ["source": "mcp", "title": "x"]) + hub.emit("session.stopped", data: ["agent": "claude"]) + let replay = hub.replay(name: "session.stopped", arguments: ["agent": "claude"], cursor: "e1.1", maxAgeMs: nil) + XCTAssertEqual(replay.events.map(\.sequence), [4]) + XCTAssertEqual(replay.cursor, 4) + XCTAssertFalse(replay.truncated) + } + + // Another launch's cursor, one older than the ring, or one behind the + // maxAgeMs floor is a gap, never an error. + func testAGapIsTruncatedNotAnError() { + let hub = hub() + hub.emit("session.stopped", data: ["agent": "claude"]) + XCTAssertTrue(hub.replay(name: "session.stopped", arguments: [:], cursor: "old.3", maxAgeMs: nil).truncated) + XCTAssertTrue(hub.replay(name: "session.stopped", arguments: [:], cursor: "nonsense", maxAgeMs: nil).truncated) + for _ in 0..<(MCPEventHub.ringSize + 5) { hub.emit("session.stopped", data: ["agent": "claude"]) } + XCTAssertTrue(hub.replay(name: "session.stopped", arguments: [:], cursor: "e1.1", maxAgeMs: nil).truncated) + + let aged = self.hub() + aged.emit("session.stopped", data: ["agent": "claude"]) + clock = clock.addingTimeInterval(600) + aged.emit("session.stopped", data: ["agent": "claude"]) + let replay = aged.replay(name: "session.stopped", arguments: [:], cursor: "e1.0", maxAgeMs: 60_000) + XCTAssertEqual(replay.events.map(\.sequence), [2]) + XCTAssertTrue(replay.truncated) + } + + func testABacklogComesInBatches() { + let hub = hub() + for _ in 0..<5 { hub.emit("session.stopped", data: ["agent": "claude"]) } + let first = hub.replay(name: "session.stopped", arguments: [:], cursor: "e1.0", maxAgeMs: nil, maxEvents: 2) + XCTAssertEqual(first.events.map(\.sequence), [1, 2]) + XCTAssertTrue(first.hasMore) + XCTAssertEqual(first.cursor, 2) + } + + func testArgumentsAreTheTypesFilters() { + let stopped = MCPEventHub.appTypes.first { $0.name == "session.stopped" }! + XCTAssertEqual(try MCPEventHub.arguments(["agent": "claude"], for: stopped).get(), ["agent": "claude"]) + XCTAssertThrowsError(try MCPEventHub.arguments(["colour": "red"], for: stopped).get()) + XCTAssertThrowsError(try MCPEventHub.arguments(["agent": 3], for: stopped).get()) + XCTAssertEqual(try MCPEventHub.arguments(nil, for: stopped).get(), [:]) + } + + func testAnExtensionsTypesComeAndGo() { + let hub = hub() + let type = MCPEventHub.EventType(name: "pylon.sla", description: "d", filters: [:], payloadSchema: [:]) + XCTAssertTrue(hub.setExtensionTypes([type], for: "pylon")) + XCTAssertFalse(hub.setExtensionTypes([type], for: "pylon"), "the same list again is no change") + XCTAssertEqual(hub.type(named: "pylon.sla")?.owner, "pylon") + XCTAssertTrue(hub.setExtensionTypes([], for: "pylon")) + XCTAssertNil(hub.type(named: "pylon.sla")) + } +} + +final class MCPEventsSessionTests: XCTestCase { + + private var sent: [[String: Any]] = [] + private var hub = MCPEventHub(epoch: "e1") + + private func session() -> MCPSession { + sent = [] + hub = MCPEventHub(epoch: "e1") + return MCPSession(context: MCPSessionTests.FakeContext(), events: hub, caller: MCPCaller()) { [unowned self] in + self.sent.append($0) + } + } + + private func request(_ id: Any, _ method: String, _ params: [String: Any]) -> [String: Any] { + var params = params + params["_meta"] = [MCPProtocol.metaProtocolVersion: MCPProtocol.currentVersion] + return ["jsonrpc": "2.0", "id": id, "method": method, "params": params] + } + + private func params(_ message: [String: Any]?) -> [String: Any]? { message?["params"] as? [String: Any] } + private func subscription(_ message: [String: Any]?) -> Int? { + (params(message)?["_meta"] as? [String: Any])?[MCPProtocol.metaSubscriptionID] as? Int + } + + func testTheExtensionIsAdvertisedAndItsTypesListed() { + let session = session() + session.receive(request("d", "server/discover", [:])) + let capabilities = (sent.last?["result"] as? [String: Any])?["capabilities"] as? [String: Any] + XCTAssertNotNil((capabilities?["extensions"] as? [String: Any])?[MCPEventHub.extensionID]) + + session.receive(request(1, "events/list", [:])) + let types = (sent.last?["result"] as? [String: Any])?["events"] as? [[String: Any]] + XCTAssertEqual(types?.count, MCPEventHub.appTypes.count) + XCTAssertEqual(types?.first?["delivery"] as? [String], ["push", "poll"]) + } + + func testAPollStartsFromNowThenGetsWhatHappened() { + let session = session() + session.receive(request(1, "events/poll", ["name": "session.waiting", "cursor": NSNull()])) + let start = sent.last?["result"] as? [String: Any] + XCTAssertEqual((start?["events"] as? [Any])?.count, 0) + let cursor = start?["cursor"] as? String + hub.emit("session.waiting", data: ["agent": "claude"]) + session.receive(request(2, "events/poll", ["name": "session.waiting", "cursor": cursor as Any])) + let next = sent.last?["result"] as? [String: Any] + XCTAssertEqual(((next?["events"] as? [[String: Any]])?.first?["data"] as? [String: Any])?["agent"] as? String, "claude") + XCTAssertEqual(next?["nextPollMs"] as? Int, MCPEventHub.defaultPollMs) + } + + func testAnUnknownTypeIsNotFound() { + let session = session() + session.receive(request(1, "events/poll", ["name": "nope"])) + XCTAssertEqual((sent.last?["error"] as? [String: Any])?["code"] as? Int, MCPEventHub.notFound) + session.receive(request(2, "events/stream", ["name": "session.waiting", "arguments": ["colour": "red"]])) + XCTAssertEqual((sent.last?["error"] as? [String: Any])?["code"] as? Int, MCPProtocol.invalidParams) + } + + // Active first, with the granted heartbeat; then the backlog; then live + // events that match, each tagged with the stream; nothing after cancel. + func testAStreamIsActiveThenReplaysThenGoesLive() { + let session = session() + hub.emit("session.stopped", data: ["agent": "claude"]) + hub.emit("session.stopped", data: ["agent": "claude"]) + session.receive(request(7, "events/stream", ["name": "session.stopped", "arguments": ["agent": "claude"], + "cursor": "e1.1", "heartbeatMs": 10])) + XCTAssertEqual(sent.first?["method"] as? String, "notifications/events/active") + XCTAssertEqual(params(sent.first)?["heartbeatMs"] as? Int, 5000, "clamped to the server's floor") + XCTAssertEqual(subscription(sent.first), 7) + XCTAssertEqual(sent.count, 2, "the one event since e1.1") + XCTAssertEqual(params(sent.last)?["cursor"] as? String, "e1.2") + + sent = [] + session.deliver(hub.emit("session.stopped", data: ["agent": "codex"])) + XCTAssertTrue(sent.isEmpty, "filtered out") + session.deliver(hub.emit("session.stopped", data: ["agent": "claude"])) + XCTAssertEqual(sent.first?["method"] as? String, "notifications/events/event") + XCTAssertEqual(subscription(sent.first), 7) + + session.receive(["jsonrpc": "2.0", "method": "notifications/cancelled", "params": ["requestId": 7]]) + sent = [] + session.deliver(hub.emit("session.stopped", data: ["agent": "claude"])) + XCTAssertTrue(sent.isEmpty) + } + + func testTheListChangesOnlyOnAStreamThatAskedForIt() { + let session = session() + session.eventsListChanged() + XCTAssertTrue(sent.isEmpty) + session.receive(request(3, "subscriptions/listen", ["notifications": ["eventsListChanged": true]])) + XCTAssertEqual((params(sent.first)?["notifications"] as? [String: Any])?["eventsListChanged"] as? Bool, true) + sent = [] + session.eventsListChanged() + XCTAssertEqual(sent.first?["method"] as? String, "notifications/events/list_changed") + XCTAssertEqual(subscription(sent.first), 3) + } +} + +final class MCPAppEventsTests: XCTestCase { + + // No prompt text, tool input or message body: a prompt says who's + // waiting, not what it asks. + func testAPromptBecomesSessionWaitingWithoutItsText() { + let prompt = NudgeEvent(agent: "claude", kind: .permission, title: "Claude Code", message: "Bash(rm -rf /tmp/x)", + projectPath: "/Users/me/api", agentPID: 42, claudeSessionID: "s-1") + let (name, data) = MCPAppEvents.occurrence(for: prompt)! + XCTAssertEqual(name, "session.waiting") + XCTAssertEqual(data["project"] as? String, "api") + XCTAssertEqual(data["sessionPid"] as? Int, 42) + XCTAssertFalse(data.values.contains { ($0 as? String)?.contains("rm -rf") == true }) + } + + func testStopsAndFeedEventsMapToTheirTypes() { + let stop = NudgeEvent(agent: "codex", kind: .stop, title: "Codex", message: "Done") + XCTAssertEqual(MCPAppEvents.occurrence(for: stop)?.name, "session.stopped") + let feed = NudgeEvent.feed(source: .github, tag: "ci", title: "CI failed", message: "api#9", + url: URL(string: "https://github.com/o/r/pull/9")) + let (name, data) = MCPAppEvents.occurrence(for: feed)! + XCTAssertEqual(name, "nudge.raised") + XCTAssertEqual(data["source"] as? String, "github") + XCTAssertEqual(data["url"] as? String, "https://github.com/o/r/pull/9") + XCTAssertNil(MCPAppEvents.occurrence(for: NudgeEvent(agent: "claude", kind: .other, title: "t", message: "m"))) + } + + func testAWriteIsCreditedOnlyBriefly() { + let attribution = MCPAttribution() + let at = Date() + attribution.note("STACKNUDGE_VOICE", by: "Claude Code", at: at) + XCTAssertEqual(attribution.take("STACKNUDGE_VOICE", now: at.addingTimeInterval(1)), "Claude Code") + XCTAssertNil(attribution.take("STACKNUDGE_VOICE", now: at.addingTimeInterval(1)), "taken once") + attribution.note("STACKNUDGE_VOICE", by: "Claude Code", at: at) + XCTAssertNil(attribution.take("STACKNUDGE_VOICE", now: at.addingTimeInterval(10))) + } +} diff --git a/docs/design/local-mcp.md b/docs/design/local-mcp.md index fb9e908..afdb586 100644 --- a/docs/design/local-mcp.md +++ b/docs/design/local-mcp.md @@ -1,9 +1,10 @@ # A local MCP server -Status: phases 1 and 2 are built: the bridge, the server on its own socket, the +Status: phases 1 to 3 are built: the bridge, the server on its own socket, the settings registry, every tool below, the resources with their update -notifications, the write switch and the audit lines. Later phases are marked -*not yet delivered*. Each phase is its own PR, and this doc is updated as they land, the +notifications, the write switch, the audit lines, and the app's events over +push and poll. Extension contributions (phase 4) are marked *not yet +delivered*. Each phase is its own PR, and this doc is updated as they land, the way [service-extensions.md](service-extensions.md) was. ## Why @@ -165,10 +166,19 @@ Payloads are minimal: no prompt text, tool input or message bodies, by default. untrusted input to a model, and a permission prompt's text is exactly what prompt injection would aim for. -Cursors come from the event log's sequence when Event history is on, so a -client that reconnects gets what it missed, with `truncated: true` past the -log's window. With history off the cursor is `null` and a reconnect starts from -now, as the spec allows for types with no addressable history. +Cursors are positions in a ring of the last 500 occurrences, stamped with an +epoch that changes every launch, so a client that reconnects gets what it +missed while it's still in the ring. A cursor from before a relaunch, older +than the ring, or behind the client's `maxAgeMs` floor comes back as a gap +(`truncated: true` and a fresh cursor), never an error. The ring is in memory on +purpose: replaying events from before a relaunch would replay prompts long since +answered. Push streams are confirmed with `notifications/events/active`, carry a +heartbeat with the current cursor every interval that passes in silence +(30 seconds unless the client asks, between 5 seconds and 5 minutes), and end +when the client cancels. + +A change from an MCP client is credited to it in `settings.changed`'s `by`; +anything else (Settings, the config file) is credited to `stack-nudge`. ## Writes diff --git a/panel/MCPAppContext.swift b/panel/MCPAppContext.swift index c8b44ba..da96e42 100644 --- a/panel/MCPAppContext.swift +++ b/panel/MCPAppContext.swift @@ -12,6 +12,8 @@ final class MCPAppContext: MCPContext { // The controller's mute, which owns the timer and the menu-bar badge. private let muteFor: (Int, Bool) -> Void private let resume: () -> Void + // Set once the server exists: writes credit their client through it. + weak var server: MCPServer? init(nav: PanelNav, store: EventStore, sessions: SessionStore, muteFor: @escaping (Int, Bool) -> Void, resume: @escaping () -> Void) { @@ -41,6 +43,7 @@ final class MCPAppContext: MCPContext { onMain { guard let nav else { return .failure(.unknownKey(key)) } let before = SettingsRegistry.snapshot(nav).first { $0.key == key }?.value + server?.attribution.note(key, by: caller.displayName) let result = SettingsRegistry.write(key: key, raw: value, nav: nav) // Every change shows in Events, so one you didn't ask for is seen. if case .success(let setting) = result, setting.value != before { @@ -129,6 +132,13 @@ final class MCPChangeWatcher { guard let nav else { return } let snapshot = SettingsRegistry.snapshot(nav) let changed = snapshot.filter { lastSettings[$0.key] != $0.value } + for setting in changed { + var data: [String: Any] = ["key": setting.key, "label": setting.label, + "value": SettingsRegistry.describe(setting.value), + "by": server.attribution.take(setting.key) ?? "stack-nudge"] + if let previous = lastSettings[setting.key] { data["previous"] = SettingsRegistry.describe(previous) } + server.emit("settings.changed", data: data) + } lastSettings = Self.values(snapshot) var uris = MCPSession.settingsURIs(changed: changed) let sessions = currentSessions() @@ -148,3 +158,50 @@ final class MCPChangeWatcher { return MCPSessions.list(sessionStore.sessions, events: store?.events ?? []) } } + +// What stack-nudge tells MCP event subscribers about, built from what the app +// already has. Minimal by design: no prompt text, tool input or message body +// (docs/design/local-mcp.md, "Events"). Pure, for tests. +enum MCPAppEvents { + + static func project(_ path: String?) -> String? { + path.map { ($0 as NSString).lastPathComponent } + } + + // An event arriving in Events: a prompt is a session waiting, a finished + // turn a session stopping, and anything else a nudge. + static func occurrence(for event: NudgeEvent) -> (name: String, data: [String: Any])? { + if event.isFeed { + var data: [String: Any] = ["source": event.source.rawValue, "client": event.agent, "title": event.title] + if let tag = event.tag { data["tag"] = tag } + if let url = event.url { data["url"] = url.absoluteString } + return ("nudge.raised", data) + } + var data: [String: Any] = ["agent": event.agent] + if let path = event.projectPath { data["path"] = path; data["project"] = project(path) } + if let id = event.claudeSessionID { data["claudeSessionId"] = id } + switch event.kind { + case .permission: + if let pid = event.agentPID { data["sessionPid"] = pid } + data["since"] = MCPEventHub.iso.string(from: event.timestamp) + return ("session.waiting", data) + case .stop: + return ("session.stopped", data) + case .other: + return nil + } + } + + static func stalled(_ session: Session, quietMinutes: Int) -> [String: Any] { + var data: [String: Any] = ["agent": session.agent, "sessionPid": session.pid, "quietMinutes": quietMinutes] + if let path = session.projectPath { data["path"] = path } + if let project = session.projectName ?? project(session.projectPath) { data["project"] = project } + return data + } + + static func quota(label: String, percent: Int, resetsAt: Date?) -> [String: Any] { + var data: [String: Any] = ["label": label, "percent": percent] + if let resetsAt { data["resetsAt"] = MCPEventHub.iso.string(from: resetsAt) } + return data + } +} diff --git a/panel/MCPEvents.swift b/panel/MCPEvents.swift new file mode 100644 index 0000000..71cf7a0 --- /dev/null +++ b/panel/MCPEvents.swift @@ -0,0 +1,229 @@ +import Foundation + +// MCP Events (io.modelcontextprotocol/events, SEP-3415) for the local server: +// the event types stack-nudge offers, a ring of recent occurrences, and the +// cursors that let a client resume. Push (events/stream) and poll +// (events/poll) are offered; webhook needs an authenticated principal and an +// https callback, and is the relay's to add (docs/design/local-mcp.md, +// "Events"). +// +// Cursors are ".". The epoch changes with every launch, so a +// cursor from a previous run reads as a gap rather than a position in this +// one's ring. Replay is bounded by the ring; anything older is a gap too. +final class MCPEventHub { + + static let extensionID = "io.modelcontextprotocol/events" + static let notFound = -32023 + static let unsupported = -32026 + static let ringSize = 500 + static let defaultPollMs = 5000 + static let defaultHeartbeatMs = 30000 + + struct EventType { + let name: String + let description: String + // Subscription arguments: each one narrows to occurrences whose data + // has that field equal to the argument. + let filters: [String: String] + let payloadSchema: [String: Any] + // An extension's, by its id; nil for the app's own. + var owner: String? = nil + + var json: [String: Any] { + var properties: [String: Any] = [:] + for (name, description) in filters { + properties[name] = ["type": "string", "description": description] + } + var entry: [String: Any] = [ + "name": name, "description": description, "delivery": ["push", "poll"], + "inputSchema": ["type": "object", "properties": properties, "additionalProperties": false], + "payloadSchema": payloadSchema, + ] + if let owner { entry["_meta"] = ["stack-nudge/extension": owner] } + return entry + } + } + + struct Occurrence { + let sequence: Int + let eventID: String + let name: String + let timestamp: Date + let data: [String: Any] + + func json(cursor: String?) -> [String: Any] { + var entry: [String: Any] = ["eventId": eventID, "name": name, + "timestamp": MCPEventHub.iso.string(from: timestamp), "data": data] + if let cursor { entry["cursor"] = cursor } + return entry + } + + func matches(name: String, arguments: [String: String]) -> Bool { + guard self.name == name else { return false } + return arguments.allSatisfy { key, value in (data[key] as? String) == value } + } + } + + static let iso: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter + }() + + private let lock = NSLock() + let epoch: String + private var ring: [Occurrence] = [] + private var sequence = 0 + private var extensionTypes: [EventType] = [] + private let now: () -> Date + + init(epoch: String = String(UUID().uuidString.prefix(8)).lowercased(), now: @escaping () -> Date = Date.init) { + self.epoch = epoch + self.now = now + } + + // MARK: Types + + var types: [EventType] { + lock.lock() + defer { lock.unlock() } + return Self.appTypes + extensionTypes + } + + func type(named name: String) -> EventType? { + types.first { $0.name == name } + } + + // An extension's event types replace whatever it offered before. Returns + // whether the list changed, so the server can say so. + @discardableResult + func setExtensionTypes(_ types: [EventType], for owner: String) -> Bool { + lock.lock() + defer { lock.unlock() } + let before = extensionTypes.filter { $0.owner == owner }.map(\.name) + extensionTypes.removeAll { $0.owner == owner } + extensionTypes += types.map { var type = $0; type.owner = owner; return type } + return before != types.map(\.name) + } + + private static let sessionFilters = ["agent": "Only this agent: claude, codex, gemini, agy or pi.", + "project": "Only sessions in the project with this folder name."] + + private static func object(_ fields: [String: String], required: [String]) -> [String: Any] { + ["type": "object", "required": required, + "properties": fields.mapValues { type -> [String: Any] in ["type": type] }] + } + + static let appTypes: [EventType] = [ + EventType(name: "session.waiting", + description: "An agent session is blocked on the user: a permission prompt or a question.", + filters: sessionFilters, + payloadSchema: object(["agent": "string", "project": "string", "path": "string", + "sessionPid": "integer", "claudeSessionId": "string", "since": "string"], + required: ["agent"])), + EventType(name: "session.stopped", + description: "An agent session finished its turn.", + filters: sessionFilters, + payloadSchema: object(["agent": "string", "project": "string", "path": "string", + "claudeSessionId": "string"], required: ["agent"])), + EventType(name: "session.stalled", + description: "A session the agent still reports as busy has produced nothing for the stall window.", + filters: sessionFilters, + payloadSchema: object(["agent": "string", "project": "string", "path": "string", + "sessionPid": "integer", "quietMinutes": "integer"], required: ["agent"])), + EventType(name: "nudge.raised", + description: "A nudge that isn't an agent's own arrived in Events: GitHub, a script, an extension, " + + "or an MCP client's notify.", + filters: ["source": "Only nudges from this source: github, calendar, script, mcp.", + "tag": "Only nudges with this tag."], + payloadSchema: object(["source": "string", "client": "string", "title": "string", + "tag": "string", "url": "string"], required: ["source", "title"])), + EventType(name: "quota.threshold", + description: "A usage window crossed the quota alert threshold.", + filters: [:], + payloadSchema: object(["label": "string", "percent": "integer", "resetsAt": "string"], + required: ["label", "percent"])), + EventType(name: "settings.changed", + description: "A stack-nudge setting changed, from Settings, the config file or an MCP client.", + filters: ["key": "Only this STACKNUDGE_ key."], + payloadSchema: object(["key": "string", "label": "string", "value": "string", + "previous": "string", "by": "string"], required: ["key", "value"])), + ] + + // MARK: Emitting + + // Records an occurrence and returns it for live delivery. Payloads are + // kept minimal by the callers: no prompt text or tool input. + @discardableResult + func emit(_ name: String, data: [String: Any], eventID: String? = nil) -> Occurrence { + lock.lock() + defer { lock.unlock() } + sequence += 1 + let occurrence = Occurrence(sequence: sequence, eventID: eventID ?? "\(epoch)-\(sequence)", + name: name, timestamp: now(), data: data) + ring.append(occurrence) + if ring.count > Self.ringSize { ring.removeFirst(ring.count - Self.ringSize) } + return occurrence + } + + func cursor(_ sequence: Int) -> String { "\(epoch).\(sequence)" } + + var head: Int { + lock.lock() + defer { lock.unlock() } + return sequence + } + + // MARK: Replay + + struct Replay { + let events: [Occurrence] + let cursor: Int + let truncated: Bool + let hasMore: Bool + } + + // What a subscription missed since `cursor`: none for a null cursor (start + // from now), and a gap when the cursor is from another launch, older than + // the ring, or behind the maxAgeMs floor. + func replay(name: String, arguments: [String: String], cursor: String?, + maxAgeMs: Int?, maxEvents: Int = 100) -> Replay { + lock.lock() + defer { lock.unlock() } + guard let cursor else { return Replay(events: [], cursor: sequence, truncated: false, hasMore: false) } + let parts = cursor.split(separator: ".", maxSplits: 1).map(String.init) + guard parts.count == 2, parts[0] == epoch, let from = Int(parts[1]), from <= sequence else { + return Replay(events: [], cursor: sequence, truncated: true, hasMore: false) + } + let oldest = ring.first?.sequence ?? sequence + 1 + var truncated = from + 1 < oldest + var pending = ring.filter { $0.sequence > from } + if let maxAgeMs { + let floor = now().addingTimeInterval(-Double(maxAgeMs) / 1000) + let kept = pending.filter { $0.timestamp >= floor } + if kept.count < pending.count { truncated = true } + pending = kept + } + let matching = pending.filter { $0.matches(name: name, arguments: arguments) } + let batch = Array(matching.prefix(max(1, maxEvents))) + let hasMore = matching.count > batch.count + return Replay(events: batch, cursor: hasMore ? batch.last!.sequence : sequence, + truncated: truncated, hasMore: hasMore) + } + + // A subscription's arguments, checked against its type: only declared + // filters, each a string. + static func arguments(_ raw: Any?, for type: EventType) -> Result<[String: String], MCPSession.MCPFailure> { + guard let raw else { return .success([:]) } + guard let object = raw as? [String: Any] else { return .failure(.invalidParams("arguments must be an object")) } + var arguments: [String: String] = [:] + for (key, value) in object { + guard type.filters[key] != nil else { + return .failure(.invalidParams("\(type.name) has no argument \(key)")) + } + guard let string = value as? String else { return .failure(.invalidParams("\(key) must be a string")) } + arguments[key] = string + } + return .success(arguments) + } +} diff --git a/panel/MCPServer.swift b/panel/MCPServer.swift index 10b84ac..380f137 100644 --- a/panel/MCPServer.swift +++ b/panel/MCPServer.swift @@ -13,6 +13,11 @@ final class MCPServer { private let socketPath: String private let context: MCPContext + // What every connection's event streams and polls read from. + let events = MCPEventHub() + // Who changed a setting, for settings.changed: an MCP client's write + // names it here just before the change watcher sees the new value. + let attribution = MCPAttribution() private var serverFD: Int32 = -1 private var boundInode: ino_t? private let lock = NSLock() @@ -88,7 +93,7 @@ final class MCPServer { if errno == EINTR { continue } return } - let connection = MCPConnection(fd: client, context: context) { [weak self] closed in + let connection = MCPConnection(fd: client, context: context, events: events) { [weak self] closed in self?.forget(closed) } lock.lock() @@ -119,6 +124,17 @@ final class MCPServer { func toolsListChanged() { sessions.forEach { $0.toolsListChanged() } } + + // Records an event and hands it to every stream that matches. Main thread, + // from wherever the app notices the thing happening. + func emit(_ name: String, data: [String: Any], eventID: String? = nil) { + let occurrence = events.emit(name, data: data, eventID: eventID) + sessions.forEach { $0.deliver(occurrence) } + } + + func eventsListChanged() { + sessions.forEach { $0.eventsListChanged() } + } } // One bridge's connection: the hello line, then JSON-RPC lines both ways. @@ -126,6 +142,7 @@ final class MCPConnection { private let fd: Int32 private let context: MCPContext + private let events: MCPEventHub private let onClose: (MCPConnection) -> Void private let writer = DispatchQueue(label: "stack-nudge.mcp.writer") private let lock = NSLock() @@ -133,9 +150,10 @@ final class MCPConnection { private var closed = false private(set) var session: MCPSession? - init(fd: Int32, context: MCPContext, onClose: @escaping (MCPConnection) -> Void) { + init(fd: Int32, context: MCPContext, events: MCPEventHub, onClose: @escaping (MCPConnection) -> Void) { self.fd = fd self.context = context + self.events = events self.onClose = onClose } @@ -150,6 +168,7 @@ final class MCPConnection { guard !closed else { lock.unlock(); return } closed = true lock.unlock() + session?.close() Darwin.shutdown(fd, SHUT_RDWR) writer.async { [fd] in Darwin.close(fd) } onClose(self) @@ -160,7 +179,7 @@ final class MCPConnection { defer { close() } guard let first = reader.next(), let hello = MCPProtocol.parse(first), hello["type"] as? String == "hello" else { return } - let session = MCPSession(context: context, caller: .fromHello(hello)) { [weak self] message in + let session = MCPSession(context: context, events: events, caller: .fromHello(hello)) { [weak self] message in self?.write(message) } lock.lock() @@ -233,3 +252,24 @@ struct MCPLineReader { } } } + +// Which client last changed which setting, for a few seconds: long enough for +// the debounced change watcher to credit the change, short enough that a later +// edit in Settings isn't credited to it. +final class MCPAttribution { + private let lock = NSLock() + private var writes: [String: (by: String, at: Date)] = [:] + + func note(_ key: String, by: String, at: Date = Date()) { + lock.lock() + writes[key] = (by, at) + lock.unlock() + } + + func take(_ key: String, now: Date = Date()) -> String? { + lock.lock() + defer { lock.unlock() } + guard let write = writes.removeValue(forKey: key), now.timeIntervalSince(write.at) < 5 else { return nil } + return write.by + } +} diff --git a/panel/MCPSession.swift b/panel/MCPSession.swift index 5b407b5..aefaf09 100644 --- a/panel/MCPSession.swift +++ b/panel/MCPSession.swift @@ -29,6 +29,7 @@ final class MCPSession { static let settingsCategoryPrefix = "stacknudge://settings/" private let context: MCPContext + private let events: MCPEventHub private let send: ([String: Any]) -> Void private let lock = NSLock() private(set) var caller: MCPCaller @@ -48,14 +49,48 @@ final class MCPSession { let resourceURIs: Set let toolsListChanged: Bool let resourcesListChanged: Bool + var eventsListChanged = false } - init(context: MCPContext, caller: MCPCaller, send: @escaping ([String: Any]) -> Void) { + // events/stream subscriptions, one per request. + private var streams: [EventStream] = [] + + private final class EventStream { + let id: Any + let name: String + let arguments: [String: String] + let heartbeatMs: Int + var lastSequence: Int + var lastSentAt = Date() + var timer: DispatchSourceTimer? + + init(id: Any, name: String, arguments: [String: String], heartbeatMs: Int, lastSequence: Int) { + self.id = id + self.name = name + self.arguments = arguments + self.heartbeatMs = heartbeatMs + self.lastSequence = lastSequence + } + } + + init(context: MCPContext, events: MCPEventHub = MCPEventHub(), caller: MCPCaller, + send: @escaping ([String: Any]) -> Void) { self.context = context + self.events = events self.caller = caller self.send = send } + // The connection closed: stop every stream's heartbeat. + func close() { + lock.lock() + let open = streams + streams.removeAll() + listeners.removeAll() + lock.unlock() + open.forEach { $0.timer?.cancel() } + } + // MARK: - Incoming func receive(_ message: [String: Any]) { @@ -98,6 +133,9 @@ final class MCPSession { case "resources/subscribe": respond(id, try subscribe(params), modern: modern) case "resources/unsubscribe": respond(id, unsubscribe(params), modern: modern) case "subscriptions/listen": listen(id: id, params: params) + case "events/list": respond(id, ["events": events.types.map(\.json)], modern: modern) + case "events/poll": respond(id, try poll(params), modern: modern) + case "events/stream": try stream(id: id, params: params) default: send(MCPProtocol.error(id: id, code: MCPProtocol.methodNotFound, message: "Method not found: \(method)")) } @@ -165,7 +203,8 @@ final class MCPSession { private var capabilities: [String: Any] { ["tools": ["listChanged": true], - "resources": ["subscribe": true, "listChanged": true]] + "resources": ["subscribe": true, "listChanged": true], + "extensions": [MCPEventHub.extensionID: ["listChanged": true]]] } private func initialize(_ params: [String: Any]) -> [String: Any] { @@ -363,11 +402,13 @@ final class MCPSession { let filter = params["notifications"] as? [String: Any] ?? [:] let asked = filter["resourceSubscriptions"] as? [String] ?? [] let uris = Set(asked.filter(Self.isKnownURI)) - let listener = Listener(id: id, resourceURIs: uris, + var listener = Listener(id: id, resourceURIs: uris, toolsListChanged: filter["toolsListChanged"] as? Bool ?? false, resourcesListChanged: filter["resourcesListChanged"] as? Bool ?? false) + listener.eventsListChanged = filter["eventsListChanged"] as? Bool ?? false var acknowledged: [String: Any] = [:] if listener.toolsListChanged { acknowledged["toolsListChanged"] = true } + if listener.eventsListChanged { acknowledged["eventsListChanged"] = true } if listener.resourcesListChanged { acknowledged["resourcesListChanged"] = true } if !uris.isEmpty { acknowledged["resourceSubscriptions"] = asked.filter(Self.isKnownURI) } lock.lock() @@ -381,7 +422,106 @@ final class MCPSession { private func cancel(_ requestID: Any?) { lock.lock() listeners.removeAll { MCPProtocol.sameID($0.id, requestID) } + let cancelled = streams.filter { MCPProtocol.sameID($0.id, requestID) } + streams.removeAll { MCPProtocol.sameID($0.id, requestID) } + lock.unlock() + cancelled.forEach { $0.timer?.cancel() } + } + + // MARK: - Events + + private func eventType(_ params: [String: Any]) throws -> (MCPEventHub.EventType, [String: String]) { + guard let name = params["name"] as? String else { throw MCPFailure.invalidParams("Missing event name") } + guard let type = events.type(named: name) else { + throw MCPFailure(code: MCPEventHub.notFound, message: "No event type \(name)") + } + switch MCPEventHub.arguments(params["arguments"], for: type) { + case .success(let arguments): return (type, arguments) + case .failure(let failure): throw failure + } + } + + private func poll(_ params: [String: Any]) throws -> [String: Any] { + let (type, arguments) = try eventType(params) + let replay = events.replay(name: type.name, arguments: arguments, cursor: params["cursor"] as? String, + maxAgeMs: (params["maxAgeMs"] as? NSNumber)?.intValue, + maxEvents: (params["maxEvents"] as? NSNumber)?.intValue ?? 100) + return ["events": replay.events.map { $0.json(cursor: nil) }, "cursor": events.cursor(replay.cursor), + "truncated": replay.truncated, "hasMore": replay.hasMore, "nextPollMs": MCPEventHub.defaultPollMs] + } + + // Confirmed with notifications/events/active, then what was missed since + // the cursor, then live events as they happen, with a heartbeat carrying + // the cursor whenever a heartbeat interval passes in silence. The request + // stays open until the client cancels it. + private func stream(id: Any, params: [String: Any]) throws { + let (type, arguments) = try eventType(params) + let suggested = (params["heartbeatMs"] as? NSNumber)?.intValue ?? MCPEventHub.defaultHeartbeatMs + let heartbeatMs = min(max(suggested, 5000), 300_000) + lock.lock() + let replay = events.replay(name: type.name, arguments: arguments, cursor: params["cursor"] as? String, + maxAgeMs: (params["maxAgeMs"] as? NSNumber)?.intValue, maxEvents: MCPEventHub.ringSize) + let stream = EventStream(id: id, name: type.name, arguments: arguments, heartbeatMs: heartbeatMs, + lastSequence: replay.events.last?.sequence ?? replay.cursor) + streams.append(stream) + let tag: [String: Any] = [MCPProtocol.metaSubscriptionID: id] + send(MCPProtocol.notification("notifications/events/active", + params: ["cursor": events.cursor(replay.cursor), "truncated": replay.truncated, + "heartbeatMs": heartbeatMs, "_meta": tag])) + for occurrence in replay.events { + var body = occurrence.json(cursor: events.cursor(occurrence.sequence)) + body["_meta"] = tag + send(MCPProtocol.notification("notifications/events/event", params: body)) + } + lock.unlock() + startHeartbeat(stream) + } + + private func startHeartbeat(_ stream: EventStream) { + let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .utility)) + let interval = DispatchTimeInterval.milliseconds(stream.heartbeatMs) + timer.schedule(deadline: .now() + interval, repeating: interval) + timer.setEventHandler { [weak self, weak stream] in + guard let self, let stream else { return } + self.lock.lock() + let quiet = Date().timeIntervalSince(stream.lastSentAt) * 1000 >= Double(stream.heartbeatMs) * 0.9 + if quiet { + stream.lastSentAt = Date() + self.send(MCPProtocol.notification("notifications/events/heartbeat", + params: ["cursor": self.events.cursor(self.events.head), + "_meta": [MCPProtocol.metaSubscriptionID: stream.id]])) + } + self.lock.unlock() + } + stream.timer = timer + timer.resume() + } + + // A new occurrence: each of this client's streams it matches hears it, + // once. + func deliver(_ occurrence: MCPEventHub.Occurrence) { + lock.lock() + defer { lock.unlock() } + for stream in streams where occurrence.sequence > stream.lastSequence + && occurrence.matches(name: stream.name, arguments: stream.arguments) { + stream.lastSequence = occurrence.sequence + stream.lastSentAt = Date() + var body = occurrence.json(cursor: events.cursor(occurrence.sequence)) + body["_meta"] = [MCPProtocol.metaSubscriptionID: stream.id] + send(MCPProtocol.notification("notifications/events/event", params: body)) + } + } + + // The event types changed (an extension's came or went): only on a + // listen stream that asked, as the extension says. + func eventsListChanged() { + lock.lock() + let ids = listeners.filter(\.eventsListChanged).map(\.id) lock.unlock() + for id in ids { + send(MCPProtocol.notification("notifications/events/list_changed", + params: ["_meta": [MCPProtocol.metaSubscriptionID: id]])) + } } // MARK: - Change notifications diff --git a/panel/Panel.swift b/panel/Panel.swift index 54e9c3f..1ebc214 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1766,6 +1766,9 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, self?.captureHandoff(for: event) self?.noteHistory(event) self?.nav.reactToEvent(event.kind) + if let (name, data) = MCPAppEvents.occurrence(for: event) { + self?.mcpServer?.emit(name, data: data, eventID: event.id.uuidString) + } // Only live arrivals reach onAppend, so events restored at launch never nod. MainActor.assumeIsolated { self?.companion?.noteArrival(event) } } @@ -3011,6 +3014,9 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, postQuotaBanner(label: label, percent: Int(tier.utilization.rounded()), resetsAt: tier.resetsAt) + mcpServer?.emit("quota.threshold", data: MCPAppEvents.quota(label: label, + percent: Int(tier.utilization.rounded()), + resetsAt: tier.resetsAt)) state.maxBucketFired = currentBucket } quotaLastFired[name] = state @@ -4280,6 +4286,12 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, else { return nil } return SessionPersistence.key(for: session) }) + // Newly stalled only: one event per stall, not one per tick. + let newlyStalled = stalled.subtracting(nav.stalledSessionKeys) + for session in sessions.sessions { + guard let key = SessionPersistence.key(for: session), newlyStalled.contains(key) else { continue } + mcpServer?.emit("session.stalled", data: MCPAppEvents.stalled(session, quietMinutes: nav.stalledMinutes)) + } if stalled != nav.stalledSessionKeys { nav.stalledSessionKeys = stalled } } @@ -6490,12 +6502,13 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // A failure only costs MCP clients their server: the hook socket and // everything else carry on, so it's logged rather than shown. private func startMCPServer() { - let server = MCPServer(socketPath: MCPServer.defaultSocketPath, - context: MCPAppContext(nav: nav, store: store, sessions: sessions, - muteFor: { [weak self] minutes, sparing in - self?.muteFor(minutes: minutes, sparingPrompts: sparing) - }, - resume: { [weak self] in self?.resumeNotifications() })) + let context = MCPAppContext(nav: nav, store: store, sessions: sessions, + muteFor: { [weak self] minutes, sparing in + self?.muteFor(minutes: minutes, sparingPrompts: sparing) + }, + resume: { [weak self] in self?.resumeNotifications() }) + let server = MCPServer(socketPath: MCPServer.defaultSocketPath, context: context) + context.server = server do { try server.start() mcpServer = server From 876480d43779900c0c9ee9279cb40dcc517fc99a Mon Sep 17 00:00:00 2001 From: StuBehan Date: Wed, 25 Nov 2026 00:27:35 +0000 Subject: [PATCH 2/2] fix(mcp): session events name the repo, never its path As sessions_list and event:session do, and as the design lists them. The filter is repo too. --- Tests/StackNudgePanelCoreTests/MCPEventsTests.swift | 3 ++- panel/MCPAppContext.swift | 9 +++++---- panel/MCPEvents.swift | 8 ++++---- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift b/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift index 312f5a4..4f4ce1b 100644 --- a/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift +++ b/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift @@ -186,7 +186,8 @@ final class MCPAppEventsTests: XCTestCase { projectPath: "/Users/me/api", agentPID: 42, claudeSessionID: "s-1") let (name, data) = MCPAppEvents.occurrence(for: prompt)! XCTAssertEqual(name, "session.waiting") - XCTAssertEqual(data["project"] as? String, "api") + XCTAssertEqual(data["repo"] as? String, "api") + XCTAssertNil(data["path"], "the repo's name, never its path") XCTAssertEqual(data["sessionPid"] as? Int, 42) XCTAssertFalse(data.values.contains { ($0 as? String)?.contains("rm -rf") == true }) } diff --git a/panel/MCPAppContext.swift b/panel/MCPAppContext.swift index da96e42..385b4fe 100644 --- a/panel/MCPAppContext.swift +++ b/panel/MCPAppContext.swift @@ -164,7 +164,9 @@ final class MCPChangeWatcher { // (docs/design/local-mcp.md, "Events"). Pure, for tests. enum MCPAppEvents { - static func project(_ path: String?) -> String? { + // The repo's folder name, as sessions_list and event:session give it: + // never the path. + static func repo(_ path: String?) -> String? { path.map { ($0 as NSString).lastPathComponent } } @@ -178,7 +180,7 @@ enum MCPAppEvents { return ("nudge.raised", data) } var data: [String: Any] = ["agent": event.agent] - if let path = event.projectPath { data["path"] = path; data["project"] = project(path) } + if let repo = repo(event.projectPath) { data["repo"] = repo } if let id = event.claudeSessionID { data["claudeSessionId"] = id } switch event.kind { case .permission: @@ -194,8 +196,7 @@ enum MCPAppEvents { static func stalled(_ session: Session, quietMinutes: Int) -> [String: Any] { var data: [String: Any] = ["agent": session.agent, "sessionPid": session.pid, "quietMinutes": quietMinutes] - if let path = session.projectPath { data["path"] = path } - if let project = session.projectName ?? project(session.projectPath) { data["project"] = project } + if let repo = session.projectName ?? repo(session.projectPath) { data["repo"] = repo } return data } diff --git a/panel/MCPEvents.swift b/panel/MCPEvents.swift index 71cf7a0..c7cb836 100644 --- a/panel/MCPEvents.swift +++ b/panel/MCPEvents.swift @@ -107,7 +107,7 @@ final class MCPEventHub { } private static let sessionFilters = ["agent": "Only this agent: claude, codex, gemini, agy or pi.", - "project": "Only sessions in the project with this folder name."] + "repo": "Only sessions in the repo with this folder name."] private static func object(_ fields: [String: String], required: [String]) -> [String: Any] { ["type": "object", "required": required, @@ -118,18 +118,18 @@ final class MCPEventHub { EventType(name: "session.waiting", description: "An agent session is blocked on the user: a permission prompt or a question.", filters: sessionFilters, - payloadSchema: object(["agent": "string", "project": "string", "path": "string", + payloadSchema: object(["agent": "string", "repo": "string", "sessionPid": "integer", "claudeSessionId": "string", "since": "string"], required: ["agent"])), EventType(name: "session.stopped", description: "An agent session finished its turn.", filters: sessionFilters, - payloadSchema: object(["agent": "string", "project": "string", "path": "string", + payloadSchema: object(["agent": "string", "repo": "string", "claudeSessionId": "string"], required: ["agent"])), EventType(name: "session.stalled", description: "A session the agent still reports as busy has produced nothing for the stall window.", filters: sessionFilters, - payloadSchema: object(["agent": "string", "project": "string", "path": "string", + payloadSchema: object(["agent": "string", "repo": "string", "sessionPid": "integer", "quietMinutes": "integer"], required: ["agent"])), EventType(name: "nudge.raised", description: "A nudge that isn't an agent's own arrived in Events: GitHub, a script, an extension, "