From 71450d200954573c110d0c777a5d3235189cb6fc Mon Sep 17 00:00:00 2001 From: StuBehan Date: Tue, 24 Nov 2026 21:05:10 +0000 Subject: [PATCH 1/4] docs(design): a local MCP server for settings, nudges and events --- docs/design/local-mcp.md | 294 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 294 insertions(+) create mode 100644 docs/design/local-mcp.md diff --git a/docs/design/local-mcp.md b/docs/design/local-mcp.md new file mode 100644 index 0000000..bb0a96c --- /dev/null +++ b/docs/design/local-mcp.md @@ -0,0 +1,294 @@ +# A local MCP server + +Status: design. Nothing here is built yet. Each phase at the end is its own PR, +and this doc is updated as they land, the way +[service-extensions.md](service-extensions.md) was. + +## Why + +Coding agents and chat apps can't tell stack-nudge anything except through the +hooks we install, and those only cover the agents we wrote hooks for, at the +moments those hooks fire. stack-nudge can't be asked anything either: its +settings live in a panel and a config file, and an agent that wants to change +one has to edit `~/.stack-nudge/config` by hand. + +An MCP server inside stack-nudge fixes both, with one surface every agent +already speaks: + +1. **Any client can raise a nudge.** Claude Code, Codex, Claude Desktop and the + web apps call a tool to say "done", "waiting on you" or "look at this", and + it lands in Events like a hook's would. Acting on it takes you back to where + it came from: the terminal tab, the app, or the conversation's page. +2. **Settings are readable and writable by agents.** "Turn voice off for the + rest of the day", "mute this repo", "switch me to nightly" become tool calls, + which is the main use so far. +3. **What stack-nudge knows is subscribable.** A session waiting on you, a + session stalling, a quota crossing its threshold, a setting changing, and + whatever extensions add, as MCP events. + +It also replaces the CLI and command channel proposed in #274, which covered a +subset of the same ground over a bespoke protocol. + +## What the spec gives us + +The current revision is +[2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/changelog). +It drops the `initialize` session handshake for `server/discover` plus +per-request `_meta`, and replaces `resources/subscribe` with one long-lived +[`subscriptions/listen`](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/subscriptions.md) +request whose filter asks for `toolsListChanged`, `resourcesListChanged` and +`resourceSubscriptions`. The server acknowledges with +`notifications/subscriptions/acknowledged` and tags every notification with +`_meta["io.modelcontextprotocol/subscriptionId"]`. + +[Events](https://modelcontextprotocol.io/extensions/events/overview) +(`io.modelcontextprotocol/events`, [SEP-3415](https://modelcontextprotocol.io/seps/3415-events-extension), +spec in [ext-events](https://github.com/modelcontextprotocol/ext-events)) is an +official extension, Beta. A server lists event types with `events/list` +(`name`, `inputSchema`, `payloadSchema`, `delivery`), and each occurrence is +`{eventId, name, timestamp, data, cursor}`. Of its three delivery modes we use +two: + +- **push**, `events/stream`: one long-lived request per subscription, + confirmed by `notifications/events/active`, then `notifications/events/event`, + `heartbeat`, `error` and finally `terminated`. Made for local stdio servers. +- **poll**, `events/poll`: no server state, for clients that can't hold a + stream. + +Webhook delivery needs an authenticated principal and an `https` callback, so it +only comes in with the relay (below). + +Client support is thin today. The +[extension matrix](https://modelcontextprotocol.io/extensions/client-matrix) +lists Events in no client we care about except ChatGPT, and there webhook only. +Tools and resources work in all of them now, so every feature here has a +tools-first path, and events are built to the spec so they light up as clients +adopt it. + +The official Swift SDK doesn't claim 2026-07-28. We write the JSON-RPC layer +ourselves: stack-nudge already speaks JSON-RPC to `codex app-server`, the +surface is small, and it keeps the app free of a dependency we'd have to track. + +## Transport: a stdio bridge to the running app + +MCP clients launch local servers as child processes over stdio. Ours is the app +binary in a bridge mode: + +``` +claude mcp add stack-nudge -- ~/Applications/StackNudge.app/Contents/MacOS/stack-nudge --mcp +``` + +The bridge does no MCP itself. It connects to the running app over +`~/.stack-nudge/panel.sock`, the socket the hooks already use (user-only, 0600), +sends a hello naming who launched it (below), then copies JSON-RPC lines both +ways until either side closes. Everything else lives in the app, once: one +settings model, one event store, one place to audit. + +- **No port.** Nothing listens on TCP, so there's no DNS rebinding, Origin check + or bearer token to get right. The trust boundary is the one the socket has + today: processes running as you. +- **The app isn't running.** The bridge answers `server/discover` and + `initialize` itself with no tools and an `instructions` string saying + stack-nudge isn't running, rather than failing the client's startup. It + doesn't launch the app. +- **Both protocol revisions.** Claude Code, Codex and Claude Desktop still speak + 2025-11-25 with `initialize`, so the server answers both that and + `server/discover`, and both `resources/subscribe` and `subscriptions/listen`. + It drops the older revision once the clients have. + +### Knowing who's calling + +A nudge is only useful if acting on it takes you back, so every bridge +connection opens with what it can learn about its client. The model can't +supply this: it doesn't know its own conversation or session ID, and Claude +Code puts only a per-call `claudecode/toolUseId` in `_meta` +([anthropics/claude-code#41836](https://github.com/anthropics/claude-code/issues/41836)). + +| Client | What the bridge learns | Where acting on a nudge takes you | +|---|---|---| +| Claude Code | `CLAUDE_CODE_SESSION_ID` in its environment (checked: Claude Code sets it for the processes it starts), and its parent's PID | the session's terminal tab, through the same session match and focus the hooks use | +| Codex | its parent PID, the `codex` process | the session's terminal tab, matched by PID as SessionStore does today | +| Claude Desktop | its parent is Claude.app | Claude Desktop, brought forward. Not the conversation: Desktop passes nothing that names it | +| claude.ai, ChatGPT | through the relay, the connector's identity | the site. A conversation link only when the tool call carries one | + +`clientInfo` from the handshake names the client for the feed row ("Claude +Code ยท Done"). The `notify` tool also takes an optional `url`: an `https` link +a client that knows where it is can pass, which wins over the table. Only +`https` is accepted, as on the socket today (`EventStore.webURL`). + +## What the server exposes + +### Tools + +| Tool | Does | +|---|---| +| `notify` | raises a nudge: `title`, `message`, `kind` (`done`, `waiting`, `info`), optional `url` and `tag`. It lands as a feed event with source `mcp:`, so it can never be a permission prompt and has its own cap in the queue, like extension feed events | +| `settings_list` | every setting: key, label, category, type, allowed values, current value, whether MCP may write it | +| `settings_get` | one setting's current value | +| `settings_set` | changes one, through the same code the Settings row runs, so side effects happen (launch at login, event history, re-checking the update channel) | +| `sessions_list` | the sessions stack-nudge sees, what each is doing and whether it's waiting on you. Replaces #274's `busy` | +| `mute` | mutes for a duration, or until resumed. Separate from `settings_set` because it's timed and app state, not config | + +### Resources + +- `stacknudge://settings` and `stacknudge://settings/`: the same data + as `settings_list`, subscribable. Any change, from Settings, the config file + or a tool, sends `notifications/resources/updated`. +- `stacknudge://sessions`: as `sessions_list`, updated as sessions change. + +### Events + +Advertised under `io.modelcontextprotocol/events` with `listChanged: true`, +since extensions add and remove types. + +| Event | Payload | Fires when | +|---|---|---| +| `session.waiting` | agent, repo, session id, since | an agent blocks on you: a permission prompt or a question | +| `session.stopped` | agent, repo, session id | a turn finishes | +| `session.stalled` | agent, repo, session id, quiet for | the stalled-session rule fires | +| `nudge.raised` | source, client, title, url | anything lands in Events, including another client's `notify` | +| `quota.threshold` | client, window, utilization | a quota crosses the alert threshold | +| `settings.changed` | key, old value, new value, who changed it | a setting changes | +| `.` | the extension's schema | an extension emits it (below) | + +Payloads are minimal: no prompt text, tool input or message bodies, by default. +`session.waiting` with the prompt's text needs its own opt-in, like +`event:nudge` does for extensions. The spec's security model says payloads are +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. + +## Writes + +Settings writes are the main use, so v1 has them. One switch governs them, +Settings โ†’ Actions โ†’ **MCP clients can change settings**, on by default once +you've added the server. It is a client-side opt-in already: nothing reaches +stack-nudge until you run `claude mcp add`. + +Any process running as you could already change these by editing the config +file, so writes aren't a new privilege. What's new is an agent doing it in one +tool call, possibly steered by injected text. So: + +- **Never writable by MCP:** anything that stops a permission prompt reaching + you (banners for prompts, the reminder rule, Focus holding prompts), hooks + and agent wiring, installing or removing extensions, uninstall, and the MCP + switch itself. These are refused with a reason naming Settings as the place + to change them. +- **Secrets are never readable:** the Slack and GitHub tokens live in the + Keychain and aren't settings. Identifiers that behave like secrets (the Slack + member ID) are listed as set or unset only. +- **Every write is visible.** It posts a feed event, "Claude Code set Voice to + Off", so a change you didn't ask for shows up where you'll see it, and + `settings.changed` carries who made it. +- **Mute is bounded and leaves prompts alone.** A mute from the panel silences + every banner, permission prompts included (docs/notifications.md). One from + `mute` lasts at most a day and doesn't: an agent that could silence its own + prompts could hide what it's asking for, which is the hole #274's Focus mute + had. + +The settings model behind this is new. Today each setting is a hand-written +case in PanelNav. Phase 1 adds a registry: one entry per `STACKNUDGE_*` key with +its type, allowed values, label, category and whether MCP may read or write it. +The Settings rows keep their own drawing and keys, but read and write through +the registry, so the panel and MCP can't drift apart. + +## Extensions + +Both directions, built on what service extensions already have. + +**Contributing to the server.** A service extension's manifest gains an `mcp` +block declaring the tools, resources and event types it offers, each named +under its ID (`pylon.sla_breach`). The NDJSON protocol gains `mcp.call` and +`mcp.result` for tool calls, `mcp.event` to emit an occurrence and +`mcp.resource.updated`. The host checks every call's arguments and every +event's payload against the declared schemas before passing them on. +Installing, removing, updating or a crash sends `tools/list_changed` and +`events/list_changed`. Contributing needs a new capability, `mcp`, granted at +service tier and above and listed in the install prompt like the others. + +**Consuming events.** An extension that wants to react to a nudge from Claude +Desktop or a setting changing doesn't speak MCP. It gets them on the event path +it already has, behind `event:*` capabilities: `event:nudge` (already designed) +and a new `event:settings`. That's the straight path, and it keeps extensions +out of the MCP client business. + +Extension output reaches a model marked with where it came from, and payloads +are treated like tool results, per the spec's security model. + +## The web apps: a relay + +claude.ai and ChatGPT connect to MCP servers from their own cloud, so they need +a server on the public internet +([Claude's connector docs](https://claude.com/docs/connectors/custom/remote-mcp)). +That's a relay we host: a remote MCP endpoint with OAuth per user, and the app +holding an outbound connection to it, so nothing on your Mac listens. + +The relay is emit-only at first: `notify` and nothing else. A cloud endpoint +that can change settings on your Mac is a bigger trust question than a local +socket, and the web apps' main need is telling you a long task finished. It's +the last phase, and gets its own design once the local server has settled. + +## Replacing #274's CLI + +#274 adds a `stack-nudge` shell CLI and a command channel on the socket: +`say`, `state`, `focus`, `settings`, `poll`, `busy` and `ping`. The MCP server +covers all of it for agents, through tools they already know how to call: + +| #274 | Here | +|---|---| +| `say` | `notify` | +| `settings` | `settings_list`, `settings_get`, `settings_set` | +| `busy` | `sessions_list`, `stacknudge://sessions` | +| `focus` | a setting, `focus_mute`, except that Focus never holds permission prompts | +| `state`, `poll` | dropped: nothing backed them in #274 either | +| `ping` | the handshake | + +Scripts outside an agent can still use the socket's event format, as they do +today. If a human-facing CLI turns out to be needed, it becomes a thin MCP +client over the same bridge rather than a second protocol. #274's Focus summary +and per-tag quiet list carry over as settings. + +## Security, in one place + +- Local only: stdio plus a 0600 socket, no port. The relay is separate, + emit-only, and comes last. +- Read and write as you, which is what the config file allows already, plus a + denylist for what protects permission prompts, a visible feed event for every + write, and no secrets. +- Nudges from MCP are feed events with their own source and cap: never a + permission prompt, never able to push the user's own events out of the queue. +- Only `https` links are opened. +- Payloads are minimal and treated as untrusted. Prompt text needs its own + opt-in. + +## Phases + +1. **Read.** The settings registry, the bridge, the app-side JSON-RPC server for + both revisions, `settings_list` and `settings_get`, `sessions_list`, the + resources and their update notifications. Tested with MCP Inspector and + golden JSON-RPC transcripts. +2. **Write and notify.** `settings_set` and `mute` with the switch, denylist and + audit events, `notify` with the client-identity table, and Settings โ†’ Actions + showing the `claude mcp add` line to copy. #274's CLI is closed in favour of + this. +3. **Events.** The app's event types over `events/stream` and `events/poll`, + cursors from the event log, `subscriptions/listen` for the list changes. +4. **Extensions.** The manifest `mcp` block, the NDJSON messages, schema + checks, the `mcp` capability and tier gating, and `event:settings` for + consuming. +5. **The relay** for claude.ai and ChatGPT, emit-only, in its own design. + +## Open questions + +- **Codex's session.** Codex may pass a session ID to MCP children as Claude + Code does. Until that's checked, Codex nudges match by PID. +- **Claude Desktop conversations.** Desktop passes nothing naming the + conversation, so its nudges bring the app forward but can't open the chat. A + `_meta` key from Desktop would fix it; worth asking for. +- **One server per client.** Each client launches its own bridge, so three + clients mean three connections to the app. That's fine for a socket, but the + event store has to fan out per subscription, not per client. From 05660e1e7293fa975b0498dc07fa6fa594574a00 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Tue, 24 Nov 2026 21:23:57 +0000 Subject: [PATCH 2/4] feat(mcp): a local MCP server for reading settings and sessions --- .../MCPServerTests.swift | 348 +++++++++++++++++ docs/design/local-mcp.md | 20 +- panel/MCPAppContext.swift | 132 +++++++ panel/MCPBridge.swift | 156 ++++++++ panel/MCPProtocol.swift | 139 +++++++ panel/MCPServer.swift | 235 ++++++++++++ panel/MCPSession.swift | 354 ++++++++++++++++++ panel/Panel.swift | 20 + panel/SettingsRegistry.swift | 205 ++++++++++ panel/main.swift | 4 + 10 files changed, 1607 insertions(+), 6 deletions(-) create mode 100644 Tests/StackNudgePanelCoreTests/MCPServerTests.swift create mode 100644 panel/MCPAppContext.swift create mode 100644 panel/MCPBridge.swift create mode 100644 panel/MCPProtocol.swift create mode 100644 panel/MCPServer.swift create mode 100644 panel/MCPSession.swift create mode 100644 panel/SettingsRegistry.swift diff --git a/Tests/StackNudgePanelCoreTests/MCPServerTests.swift b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift new file mode 100644 index 0000000..2a8625c --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift @@ -0,0 +1,348 @@ +import XCTest + +@testable import StackNudgePanelCore + +// The local MCP server: the protocol core against a fake app, the bridge's +// pure parts, the settings registry, and one real round trip over a socket. +final class MCPSessionTests: XCTestCase { + + final class FakeContext: MCPContext { + var serverVersion = "9.9.9" + var settingsList: [SettingSnapshot] = [ + SettingSnapshot(key: "STACKNUDGE_VOICE", label: "Voice notifications", category: "voice", + value: .bool(true), kindJSON: ["type": "boolean"], readOnlyReason: nil), + SettingSnapshot(key: "STACKNUDGE_BANNER", label: "Banner notifications", category: "notifications", + value: .bool(true), kindJSON: ["type": "boolean"], + readOnlyReason: SettingsRegistry.protectsPrompts), + ] + var sessionsList: [[String: Any]] = [["pid": 42, "agent": "claude", "waitingOnUser": true]] + func settings() -> [SettingSnapshot] { settingsList } + func sessions() -> [[String: Any]] { sessionsList } + } + + private var sent: [[String: Any]] = [] + + private func session(_ caller: MCPCaller = MCPCaller()) -> MCPSession { + sent = [] + return MCPSession(context: FakeContext(), caller: caller) { [unowned self] in self.sent.append($0) } + } + + private func request(_ id: Any, _ method: String, _ params: [String: Any] = [:], modern: Bool = false) -> [String: Any] { + var params = params + if modern { + params["_meta"] = [MCPProtocol.metaProtocolVersion: MCPProtocol.currentVersion, + MCPProtocol.metaClientInfo: ["name": "claude-code", "version": "2.1"]] + } + return ["jsonrpc": "2.0", "id": id, "method": method, "params": params] + } + + private var lastResult: [String: Any]? { sent.last?["result"] as? [String: Any] } + private var lastError: [String: Any]? { sent.last?["error"] as? [String: Any] } + + // MARK: Handshakes + + func testAnOlderClientGetsTheVersionItAskedForWhenWeSpeakIt() { + let session = session() + session.receive(request(1, "initialize", ["protocolVersion": "2025-06-18", + "clientInfo": ["name": "codex", "version": "0.9"]])) + XCTAssertEqual(lastResult?["protocolVersion"] as? String, "2025-06-18") + XCTAssertEqual((lastResult?["serverInfo"] as? [String: Any])?["version"] as? String, "9.9.9") + XCTAssertNotNil(lastResult?["capabilities"]) + XCTAssertEqual(session.caller.clientName, "codex") + + session.receive(request(2, "initialize", ["protocolVersion": "1999-01-01"])) + XCTAssertEqual(lastResult?["protocolVersion"] as? String, MCPProtocol.legacyVersions[0]) + } + + func testDiscoverAnswersWithTheCurrentRevision() { + let session = session() + session.receive(request("d", "server/discover", modern: true)) + XCTAssertEqual(lastResult?["supportedVersions"] as? [String], [MCPProtocol.currentVersion]) + XCTAssertEqual(lastResult?["resultType"] as? String, "complete") + let meta = lastResult?["_meta"] as? [String: Any] + XCTAssertEqual((meta?[MCPProtocol.metaServerInfo] as? [String: Any])?["name"] as? String, "stack-nudge") + XCTAssertEqual(session.caller.clientName, "claude-code") + } + + func testAnUnknownRevisionIsRefusedWithWhatWeSpeak() { + let session = session() + session.receive(["jsonrpc": "2.0", "id": 3, "method": "tools/list", + "params": ["_meta": [MCPProtocol.metaProtocolVersion: "2030-01-01"]]]) + XCTAssertEqual(lastError?["code"] as? Int, MCPProtocol.unsupportedProtocolVersion) + } + + func testNotificationsAreNeverAnswered() { + let session = session() + session.receive(["jsonrpc": "2.0", "method": "notifications/initialized"]) + XCTAssertTrue(sent.isEmpty) + } + + func testAnUnknownMethodIsMethodNotFound() { + let session = session() + session.receive(request(4, "prompts/list")) + XCTAssertEqual(lastError?["code"] as? Int, MCPProtocol.methodNotFound) + } + + // MARK: Tools + + func testToolsAreListedInAFixedOrder() { + let session = session() + session.receive(request(5, "tools/list")) + let names = (lastResult?["tools"] as? [[String: Any]])?.compactMap { $0["name"] as? String } + XCTAssertEqual(names, ["settings_list", "settings_get", "sessions_list"]) + } + + private func call(_ session: MCPSession, _ name: String, _ arguments: [String: Any] = [:]) -> [String: Any]? { + session.receive(request(6, "tools/call", ["name": name, "arguments": arguments])) + return lastResult + } + + func testSettingsListSaysWhatCanBeChanged() { + let session = session() + let result = call(session, "settings_list") + let settings = (result?["structuredContent"] as? [String: Any])?["settings"] as? [[String: Any]] + XCTAssertEqual(settings?.count, 2) + let banner = settings?.first { $0["key"] as? String == "STACKNUDGE_BANNER" } + XCTAssertEqual(banner?["writable"] as? Bool, false) + XCTAssertNotNil(banner?["readOnlyReason"]) + XCTAssertEqual(result?["isError"] as? Bool, false) + XCTAssertNotNil((result?["content"] as? [[String: Any]])?.first?["text"], "text for clients that only read content") + } + + func testSettingsListNarrowsByCategoryAndRejectsAnUnknownOne() { + let session = session() + let voice = (call(session, "settings_list", ["category": "voice"])?["structuredContent"] as? [String: Any])?["settings"] + XCTAssertEqual((voice as? [[String: Any]])?.count, 1) + XCTAssertEqual(call(session, "settings_list", ["category": "nope"])?["isError"] as? Bool, true) + } + + func testSettingsGetNamesAMissingKey() { + let session = session() + XCTAssertEqual((call(session, "settings_get", ["key": "STACKNUDGE_VOICE"])?["structuredContent"] + as? [String: Any])?["value"] as? Bool, true) + XCTAssertEqual(call(session, "settings_get", ["key": "STACKNUDGE_NOPE"])?["isError"] as? Bool, true) + session.receive(request(7, "tools/call", ["name": "settings_get", "arguments": [:] as [String: Any]])) + XCTAssertEqual(lastError?["code"] as? Int, MCPProtocol.invalidParams) + } + + func testSessionsListIsTheAppsList() { + let session = session() + let sessions = (call(session, "sessions_list")?["structuredContent"] as? [String: Any])?["sessions"] as? [[String: Any]] + XCTAssertEqual(sessions?.first?["waitingOnUser"] as? Bool, true) + } + + // MARK: Resources + + func testResourcesReadAsJSONAndAnUnknownURIIsInvalidParams() throws { + let session = session() + session.receive(request(8, "resources/read", ["uri": "stacknudge://settings/voice"])) + let text = ((lastResult?["contents"] as? [[String: Any]])?.first?["text"] as? String) ?? "" + let body = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) + XCTAssertEqual((body["settings"] as? [[String: Any]])?.count, 1) + + session.receive(request(9, "resources/read", ["uri": "stacknudge://nope"])) + XCTAssertEqual(lastError?["code"] as? Int, MCPProtocol.invalidParams) + } + + func testAnOlderClientHearsOnlyTheURIsItSubscribedTo() { + let session = session() + session.receive(request(10, "resources/subscribe", ["uri": MCPSession.settingsURI])) + sent = [] + session.resourcesUpdated([MCPSession.sessionsURI]) + XCTAssertTrue(sent.isEmpty) + session.resourcesUpdated([MCPSession.settingsURI, MCPSession.sessionsURI]) + XCTAssertEqual(sent.count, 1) + XCTAssertEqual(sent.first?["method"] as? String, "notifications/resources/updated") + XCTAssertEqual((sent.first?["params"] as? [String: Any])?["uri"] as? String, MCPSession.settingsURI) + } + + // 2026-07-28: acknowledged first, every notification tagged with the + // listen request's id, and nothing after it's cancelled. + func testAListenStreamIsAcknowledgedTaggedAndCancellable() { + let session = session() + session.receive(request(11, "subscriptions/listen", + ["notifications": ["resourceSubscriptions": [MCPSession.sessionsURI, "stacknudge://nope"], + "toolsListChanged": true]], + modern: true)) + XCTAssertEqual(sent.first?["method"] as? String, "notifications/subscriptions/acknowledged") + let ack = sent.first?["params"] as? [String: Any] + XCTAssertEqual((ack?["_meta"] as? [String: Any])?[MCPProtocol.metaSubscriptionID] as? Int, 11) + XCTAssertEqual((ack?["notifications"] as? [String: Any])?["resourceSubscriptions"] as? [String], + [MCPSession.sessionsURI], "an unknown URI isn't acknowledged") + XCTAssertNil(sent.first?["id"], "the listen request stays open") + + sent = [] + session.resourcesUpdated([MCPSession.sessionsURI]) + XCTAssertEqual(((sent.first?["params"] as? [String: Any])?["_meta"] as? [String: Any])?[MCPProtocol.metaSubscriptionID] as? Int, 11) + + session.receive(["jsonrpc": "2.0", "method": "notifications/cancelled", "params": ["requestId": 11]]) + sent = [] + session.resourcesUpdated([MCPSession.sessionsURI]) + XCTAssertTrue(sent.isEmpty) + } + + func testANewerClientHearsListChangesOnlyOnAStreamThatAsked() { + let older = session() + older.receive(request(1, "initialize", ["protocolVersion": "2025-11-25"])) + sent = [] + older.toolsListChanged() + XCTAssertEqual(sent.first?["method"] as? String, "notifications/tools/list_changed") + + let newer = session() + newer.receive(request(1, "server/discover", modern: true)) + sent = [] + newer.toolsListChanged() + XCTAssertTrue(sent.isEmpty) + } + + func testTheURIsASettingsChangeTouches() { + let changed = FakeContext().settingsList.filter { $0.category == "voice" } + XCTAssertEqual(MCPSession.settingsURIs(changed: changed), + [MCPSession.settingsURI, "stacknudge://settings/voice"]) + XCTAssertEqual(MCPSession.settingsURIs(changed: []), []) + } + + // MARK: The caller + + func testTheCallerComesFromTheBridgesHello() { + let caller = MCPCaller.fromHello(["type": "hello", "claudeSessionId": "abc", "parentPid": 77, "parentApp": ""]) + XCTAssertEqual(caller.claudeSessionID, "abc") + XCTAssertEqual(caller.parentPID, 77) + XCTAssertNil(caller.parentApp) + XCTAssertEqual(caller.displayName, "Claude Code") + XCTAssertEqual(MCPCaller(clientName: "codex").displayName, "Codex") + XCTAssertEqual(MCPCaller(parentApp: "Claude").displayName, "Claude") + } +} + +final class MCPBridgeTests: XCTestCase { + + func testTheHelloCarriesTheClaudeSessionAndParent() { + let hello = MCPBridge.hello(environment: ["CLAUDE_CODE_SESSION_ID": "s-1"], parentPID: getpid()) + XCTAssertEqual(hello["type"] as? String, "hello") + XCTAssertEqual(hello["claudeSessionId"] as? String, "s-1") + XCTAssertEqual(hello["parentPid"] as? Int, Int(getpid())) + XCTAssertNil(MCPBridge.hello(environment: [:], parentPID: getpid())["claudeSessionId"]) + } + + func testAnAppIsNamedFromItsBundlePath() { + XCTAssertEqual(MCPBridge.appName(fromExecutablePath: "/Applications/Claude.app/Contents/MacOS/Claude"), "Claude") + XCTAssertNil(MCPBridge.appName(fromExecutablePath: "/Users/me/.local/bin/claude")) + } + + // The app isn't running: the client's startup still succeeds, with no + // tools and a reason. + func testWithTheAppDownTheClientStillStarts() { + let initialize = MCPBridge.notRunningReply(to: ["jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": ["protocolVersion": "2025-11-25"]]) + let result = initialize?["result"] as? [String: Any] + XCTAssertEqual(result?["protocolVersion"] as? String, "2025-11-25") + XCTAssertEqual(result?["instructions"] as? String, MCPBridge.notRunning) + let tools = MCPBridge.notRunningReply(to: ["jsonrpc": "2.0", "id": 2, "method": "tools/list"]) + XCTAssertEqual(((tools?["result"] as? [String: Any])?["tools"] as? [Any])?.count, 0) + XCTAssertNil(MCPBridge.notRunningReply(to: ["jsonrpc": "2.0", "method": "notifications/initialized"])) + let call = MCPBridge.notRunningReply(to: ["jsonrpc": "2.0", "id": 3, "method": "tools/call"]) + XCTAssertEqual((call?["error"] as? [String: Any])?["code"] as? Int, MCPProtocol.methodNotFound) + } +} + +@MainActor +final class SettingsRegistryTests: XCTestCase { + + func testEveryKeyIsListedOnceUnderASettingsCategory() { + let keys = SettingsRegistry.specs.map(\.key) + XCTAssertEqual(Set(keys).count, keys.count) + let sidebar = Set(SettingsCategory.allCases.map { $0.label.lowercased() }) + for category in SettingsRegistry.categories { + XCTAssertTrue(sidebar.contains(category), "\(category) isn't a Settings category") + } + } + + // An agent changing these could hide a prompt from you or widen what it + // can do; they stay Settings-only. + func testWhatProtectsPromptsIsNeverWritable() { + for key in ["STACKNUDGE_BANNER", "STACKNUDGE_MUTE_WHEN_FOCUSED", "STACKNUDGE_REMIND_MIN", + "STACKNUDGE_AWAY_LOCK", "STACKNUDGE_PANEL_HOTKEY"] { + XCTAssertNotNil(SettingsRegistry.spec(key)?.readOnlyReason, key) + } + } + + func testNoSecretIsListed() { + for key in ["STACKNUDGE_SLACK_BOT_TOKEN", "STACKNUDGE_SLACK_MEMBER_ID", "STACKNUDGE_GITHUB_CLIENT_ID"] { + XCTAssertNil(SettingsRegistry.spec(key), key) + } + } + + func testTheSnapshotReadsNav() { + let nav = PanelNav() + nav.voiceEnabled = true + nav.quotaAlertThreshold = 90 + let snapshot = SettingsRegistry.snapshot(nav) + XCTAssertEqual(snapshot.count, SettingsRegistry.specs.count) + XCTAssertEqual(snapshot.first { $0.key == "STACKNUDGE_VOICE" }?.value, .bool(true)) + XCTAssertEqual(snapshot.first { $0.key == "STACKNUDGE_QUOTA_THRESHOLD" }?.value, .int(90)) + } +} + +final class MCPSessionsTests: XCTestCase { + + func testASessionIsWaitingWhileItsPromptIsInEvents() { + var session = Session(id: 9, pid: 9, agent: "claude", projectPath: "/r", projectName: "r", + terminalPID: nil, terminalApp: nil, elapsed: nil, customName: nil, status: .active) + session.claudeSessionID = "s-9" + let prompt = NudgeEvent(agent: "claude", kind: .permission, title: "Claude Code", message: "Bash(ls)", + claudeSessionID: "s-9") + let other = NudgeEvent(agent: "claude", kind: .permission, title: "Claude Code", message: "Bash(ls)", + claudeSessionID: "s-1") + XCTAssertTrue(MCPSessions.isWaiting(session, events: [prompt])) + XCTAssertFalse(MCPSessions.isWaiting(session, events: [other])) + let entry = MCPSessions.snapshot([session], events: [prompt], allowTabTitle: false).first + XCTAssertEqual(entry?["waitingOnUser"] as? Bool, true) + XCTAssertEqual(entry?["claudeSessionId"] as? String, "s-9") + } +} + +// One real round trip: the bridge's hello, a request and the push of a change, +// over the socket the app listens on. +final class MCPServerSocketTests: XCTestCase { + + func testARoundTripAndAPushOverTheSocket() throws { + // sun_path is 104 bytes, and NSTemporaryDirectory is long on macOS. + let path = "/tmp/sn-mcp-\(UUID().uuidString.prefix(8)).sock" + let server = MCPServer(socketPath: path, context: MCPSessionTests.FakeContext()) + try server.start() + defer { server.stop() } + + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + var addr = sockaddr_un() + addr.sun_family = sa_family_t(AF_UNIX) + withUnsafeMutableBytes(of: &addr.sun_path) { dst in + path.utf8CString.withUnsafeBytes { src in _ = memcpy(dst.baseAddress, src.baseAddress, src.count) } + } + let connected = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + connect(fd, $0, socklen_t(MemoryLayout.size)) + } + } + XCTAssertEqual(connected, 0) + defer { close(fd) } + + func send(_ object: [String: Any]) { + let data = MCPProtocol.encode(object)! + _ = data.withUnsafeBytes { write(fd, $0.baseAddress!, data.count) } + } + var reader = MCPLineReader(fd: fd) + func next() -> [String: Any]? { reader.next().flatMap(MCPProtocol.parse) } + + send(["type": "hello", "claudeSessionId": "s-1", "parentPid": 1]) + send(["jsonrpc": "2.0", "id": 1, "method": "initialize", "params": ["protocolVersion": "2025-11-25"]]) + XCTAssertEqual((next()?["result"] as? [String: Any])?["protocolVersion"] as? String, "2025-11-25") + + send(["jsonrpc": "2.0", "id": 2, "method": "resources/subscribe", "params": ["uri": MCPSession.settingsURI]]) + XCTAssertEqual(next()?["id"] as? Int, 2) + XCTAssertEqual(server.sessions.first?.caller.claudeSessionID, "s-1") + + server.resourcesUpdated([MCPSession.settingsURI]) + XCTAssertEqual(next()?["method"] as? String, "notifications/resources/updated") + } +} diff --git a/docs/design/local-mcp.md b/docs/design/local-mcp.md index bb0a96c..695c11c 100644 --- a/docs/design/local-mcp.md +++ b/docs/design/local-mcp.md @@ -1,8 +1,10 @@ # A local MCP server -Status: design. Nothing here is built yet. Each phase at the end is its own PR, -and this doc is updated as they land, the way -[service-extensions.md](service-extensions.md) was. +Status: phase 1 (read) is built: the bridge, the server on its own socket, the +settings registry, `settings_list`, `settings_get`, `sessions_list` and the +resources with their update notifications. Later phases 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 @@ -79,14 +81,20 @@ claude mcp add stack-nudge -- ~/Applications/StackNudge.app/Contents/MacOS/stack ``` The bridge does no MCP itself. It connects to the running app over -`~/.stack-nudge/panel.sock`, the socket the hooks already use (user-only, 0600), +`~/.stack-nudge/mcp.sock` (user-only, 0600, beside the hooks' `panel.sock`), sends a hello naming who launched it (below), then copies JSON-RPC lines both ways until either side closes. Everything else lives in the app, once: one settings model, one event store, one place to audit. +The socket is separate from `panel.sock` because that one reads each +connection to its end, one at a time, and a bridge holds its connection open +for as long as its client runs. Each MCP connection gets its own reader and a +writer queue with a cap, so a client that stops reading is dropped rather than +blocking the main thread that sends it change notifications. + - **No port.** Nothing listens on TCP, so there's no DNS rebinding, Origin check - or bearer token to get right. The trust boundary is the one the socket has - today: processes running as you. + or bearer token to get right. The trust boundary is the one the hook socket + has today: processes running as you. - **The app isn't running.** The bridge answers `server/discover` and `initialize` itself with no tools and an `instructions` string saying stack-nudge isn't running, rather than failing the client's startup. It diff --git a/panel/MCPAppContext.swift b/panel/MCPAppContext.swift new file mode 100644 index 0000000..2f296c6 --- /dev/null +++ b/panel/MCPAppContext.swift @@ -0,0 +1,132 @@ +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.snapshot(sessionStore.sessions, events: store?.events ?? [], + allowTabTitle: nav?.tabTitleNames ?? false) + } + } + + private func onMain(_ work: () -> T) -> T { + Thread.isMainThread ? work() : DispatchQueue.main.sync(execute: work) + } +} + +// The sessions as a client sees them. Pure, for tests. +enum MCPSessions { + + static func snapshot(_ sessions: [Session], events: [NudgeEvent], allowTabTitle: Bool) -> [[String: Any]] { + let iso = ISO8601DateFormatter() + return sessions.filter { $0.status == .active }.map { session in + var entry: [String: Any] = [ + "pid": session.pid, + "agent": session.agent, + "name": SessionLabel.displayName(for: session, fallback: session.agent, allowTabTitle: allowTabTitle), + "busy": session.liveStatus == "busy", + "waitingOnUser": isWaiting(session, events: events), + ] + if let project = session.projectName { entry["project"] = project } + if let path = session.projectPath { entry["path"] = path } + if let terminal = session.terminalApp { entry["terminal"] = terminal } + if let id = session.claudeSessionID { entry["claudeSessionId"] = id } + if let at = session.lastActivityAt { entry["lastActivity"] = iso.string(from: at) } + return entry + } + } + + // A permission prompt from this session is still in Events: answered and + // dead prompts leave the queue, so one that's there is waiting. + static func isWaiting(_ session: Session, events: [NudgeEvent]) -> Bool { + events.contains { event in + guard event.kind == .permission, !event.isFeed else { return false } + if let id = session.claudeSessionID, let eventID = event.claudeSessionID { return id == eventID } + if let pid = event.agentPID { return pid == session.pid } + return false + } + } +} + +// 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 = "" + private var cancellables = Set() + + 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 = sessionsSignature() + 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 = sessionsSignature() + 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 sessionsSignature() -> String { + guard let sessionStore else { return "" } + let entries = MCPSessions.snapshot(sessionStore.sessions, events: store?.events ?? [], + allowTabTitle: nav?.tabTitleNames ?? false) + // lastActivity moves on every tick of a busy session; a client + // subscribing to the list wants to hear about sessions coming, + // going, and starting or stopping waiting. + .map { $0.filter { $0.key != "lastActivity" } } + guard let data = try? JSONSerialization.data(withJSONObject: entries, options: [.sortedKeys]) else { return "" } + return String(decoding: data, as: UTF8.self) + } +} diff --git a/panel/MCPBridge.swift b/panel/MCPBridge.swift new file mode 100644 index 0000000..ce5856d --- /dev/null +++ b/panel/MCPBridge.swift @@ -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[.. 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.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.. 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) + } + } +} diff --git a/panel/MCPProtocol.swift b/panel/MCPProtocol.swift new file mode 100644 index 0000000..13c87b0 --- /dev/null +++ b/panel/MCPProtocol.swift @@ -0,0 +1,139 @@ +import Foundation + +// JSON-RPC 2.0 as MCP's stdio transport frames it: one object per line. Kept +// as [String: Any] rather than Codable types: the surface is small, ids are a +// number or a string, and params pass through to tools as free-form JSON. +// See docs/design/local-mcp.md. +enum MCPProtocol { + + // The revision that drops the initialize handshake for server/discover and + // per-request _meta. Older clients still send initialize, and get one of + // `legacyVersions` back. + static let currentVersion = "2026-07-28" + static let legacyVersions = ["2025-11-25", "2025-06-18", "2025-03-26"] + + static let parseError = -32700 + static let invalidRequest = -32600 + static let methodNotFound = -32601 + static let invalidParams = -32602 + static let internalError = -32603 + static let unsupportedProtocolVersion = -32022 + + // _meta keys from 2026-07-28. + static let metaProtocolVersion = "io.modelcontextprotocol/protocolVersion" + static let metaClientInfo = "io.modelcontextprotocol/clientInfo" + static let metaServerInfo = "io.modelcontextprotocol/serverInfo" + static let metaSubscriptionID = "io.modelcontextprotocol/subscriptionId" + + // Lines are capped like the hook socket's payloads: well past any real + // request, and short of letting a client make the app buffer without end. + static let maxLineBytes = 1 << 20 + + static func parse(_ line: Data) -> [String: Any]? { + try? JSONSerialization.jsonObject(with: line) as? [String: Any] + } + + static func encode(_ message: [String: Any]) -> Data? { + guard JSONSerialization.isValidJSONObject(message), + var data = try? JSONSerialization.data(withJSONObject: message, + options: [.sortedKeys, .withoutEscapingSlashes]) + else { return nil } + data.append(0x0A) + return data + } + + static func response(id: Any, result: [String: Any]) -> [String: Any] { + ["jsonrpc": "2.0", "id": id, "result": result] + } + + static func error(id: Any?, code: Int, message: String, data: Any? = nil) -> [String: Any] { + var body: [String: Any] = ["code": code, "message": message] + if let data { body["data"] = data } + return ["jsonrpc": "2.0", "id": id ?? NSNull(), "error": body] + } + + static func notification(_ method: String, params: [String: Any]) -> [String: Any] { + ["jsonrpc": "2.0", "method": method, "params": params] + } + + // A tool's answer: the structured value, and the same as text for clients + // that only read content. + static func toolResult(_ value: Any, isError: Bool = false) -> [String: Any] { + let text: String + if let string = value as? String { + text = string + } else if JSONSerialization.isValidJSONObject(value), + let data = try? JSONSerialization.data(withJSONObject: value, + options: [.sortedKeys, .withoutEscapingSlashes]) { + text = String(decoding: data, as: UTF8.self) + } else { + text = "\(value)" + } + var result: [String: Any] = ["content": [["type": "text", "text": text]], "isError": isError] + if value is [String: Any] { result["structuredContent"] = value } + return result + } + + static func toolError(_ message: String) -> [String: Any] { + toolResult(message, isError: true) + } + + // A JSON-RPC id is a number or a string; anything else is no id. + static func requestID(of message: [String: Any]) -> Any? { + switch message["id"] { + case let number as NSNumber: return number + case let string as String: return string + default: return nil + } + } + + static func sameID(_ lhs: Any?, _ rhs: Any?) -> Bool { + switch (lhs, rhs) { + case let (l as String, r as String): return l == r + case let (l as NSNumber, r as NSNumber): return l == r + default: return false + } + } +} + +// Who is on the other end of a bridge connection, as the bridge saw it from +// its own process, never as a model says it is (docs/design/local-mcp.md, +// "Knowing who's calling"). +struct MCPCaller: Equatable { + // From the client's handshake: initialize's clientInfo, or _meta clientInfo. + var clientName: String? = nil + var clientVersion: String? = nil + // CLAUDE_CODE_SESSION_ID in the bridge's environment: Claude Code sets it + // for every process it starts. + var claudeSessionID: String? = nil + // The process that launched the bridge: the agent CLI, or an app such as + // Claude Desktop. + var parentPID: Int? = nil + var parentApp: String? = nil + + // The bridge's first line on the socket. + static func fromHello(_ hello: [String: Any]) -> MCPCaller { + MCPCaller(clientName: nil, clientVersion: nil, + claudeSessionID: (hello["claudeSessionId"] as? String).flatMap { $0.isEmpty ? nil : $0 }, + parentPID: (hello["parentPid"] as? NSNumber)?.intValue, + parentApp: (hello["parentApp"] as? String).flatMap { $0.isEmpty ? nil : $0 }) + } + + // How a feed row and an audit line name the client. + var displayName: String { + if let name = clientName, !name.isEmpty { return Self.friendlyName(name) } + if let app = parentApp, !app.isEmpty { return app } + return claudeSessionID != nil ? "Claude Code" : "An MCP client" + } + + // Clients name themselves in code form ("claude-code"); a row reads better + // with the product name. + static func friendlyName(_ raw: String) -> String { + switch raw.lowercased() { + case "claude-code", "claude code": return "Claude Code" + case "claude-ai", "claude", "claude-desktop": return "Claude" + case "codex", "codex-mcp-client", "codex_cli_rs": return "Codex" + default: return raw + } + } +} diff --git a/panel/MCPServer.swift b/panel/MCPServer.swift new file mode 100644 index 0000000..10b84ac --- /dev/null +++ b/panel/MCPServer.swift @@ -0,0 +1,235 @@ +import Foundation + +// The MCP server's socket, ~/.stack-nudge/mcp.sock (0600). It sits beside +// panel.sock rather than sharing it: panel.sock reads each connection to EOF +// one at a time, and a bridge holds its connection open for as long as its +// client runs. Each connection gets its own reader thread and a writer queue, +// so a client that stops reading can't block the main thread that sends it +// change notifications. See docs/design/local-mcp.md. +final class MCPServer { + + // A client that stops reading is dropped once this much is queued for it. + static let maxQueuedBytes = 4 << 20 + + private let socketPath: String + private let context: MCPContext + private var serverFD: Int32 = -1 + private var boundInode: ino_t? + private let lock = NSLock() + private var connections: [ObjectIdentifier: MCPConnection] = [:] + + init(socketPath: String, context: MCPContext) { + self.socketPath = socketPath + self.context = context + } + + static var defaultSocketPath: String { + (("~/.stack-nudge" as NSString).expandingTildeInPath as NSString).appendingPathComponent("mcp.sock") + } + + func start() throws { + unlink(socketPath) + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { throw POSIXError(.EIO) } + 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 { + close(fd) + throw POSIXError(.ENAMETOOLONG) + } + withUnsafeMutableBytes(of: &addr.sun_path) { dst in + pathBytes.withUnsafeBytes { src in _ = memcpy(dst.baseAddress, src.baseAddress, pathBytes.count) } + } + let bound = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + bind(fd, $0, socklen_t(MemoryLayout.size)) + } + } + guard bound == 0 else { + let err = errno + close(fd) + throw POSIXError(POSIXErrorCode(rawValue: err) ?? .EIO) + } + chmod(socketPath, 0o600) + var st = stat() + if stat(socketPath, &st) == 0 { boundInode = st.st_ino } + guard listen(fd, 16) == 0 else { + let err = errno + close(fd) + throw POSIXError(POSIXErrorCode(rawValue: err) ?? .EIO) + } + serverFD = fd + let thread = Thread { [weak self] in self?.acceptLoop(fd) } + thread.name = "stack-nudge.mcp.accept" + thread.start() + } + + // As EventListener does: only unlink the socket file when it's still the + // one this process bound, so an app replacing us after an update keeps its + // own. + func stop() { + if serverFD >= 0 { close(serverFD); serverFD = -1 } + lock.lock() + let open = Array(connections.values) + connections.removeAll() + lock.unlock() + open.forEach { $0.close() } + guard let want = boundInode else { return } + var st = stat() + guard stat(socketPath, &st) == 0, st.st_ino == want else { return } + unlink(socketPath) + } + + private func acceptLoop(_ fd: Int32) { + while true { + let client = accept(fd, nil, nil) + if client < 0 { + if errno == EINTR { continue } + return + } + let connection = MCPConnection(fd: client, context: context) { [weak self] closed in + self?.forget(closed) + } + lock.lock() + connections[ObjectIdentifier(connection)] = connection + lock.unlock() + connection.start() + } + } + + private func forget(_ connection: MCPConnection) { + lock.lock() + connections.removeValue(forKey: ObjectIdentifier(connection)) + lock.unlock() + } + + // Every connected client's session, for change notifications. + var sessions: [MCPSession] { + lock.lock() + defer { lock.unlock() } + return connections.values.compactMap(\.session) + } + + func resourcesUpdated(_ uris: Set) { + guard !uris.isEmpty else { return } + sessions.forEach { $0.resourcesUpdated(uris) } + } + + func toolsListChanged() { + sessions.forEach { $0.toolsListChanged() } + } +} + +// One bridge's connection: the hello line, then JSON-RPC lines both ways. +final class MCPConnection { + + private let fd: Int32 + private let context: MCPContext + private let onClose: (MCPConnection) -> Void + private let writer = DispatchQueue(label: "stack-nudge.mcp.writer") + private let lock = NSLock() + private var queuedBytes = 0 + private var closed = false + private(set) var session: MCPSession? + + init(fd: Int32, context: MCPContext, onClose: @escaping (MCPConnection) -> Void) { + self.fd = fd + self.context = context + self.onClose = onClose + } + + func start() { + let thread = Thread { [weak self] in self?.readLoop() } + thread.name = "stack-nudge.mcp.connection" + thread.start() + } + + func close() { + lock.lock() + guard !closed else { lock.unlock(); return } + closed = true + lock.unlock() + Darwin.shutdown(fd, SHUT_RDWR) + writer.async { [fd] in Darwin.close(fd) } + onClose(self) + } + + private func readLoop() { + var reader = MCPLineReader(fd: fd) + 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 + self?.write(message) + } + lock.lock() + self.session = session + lock.unlock() + while let line = reader.next() { + guard let message = MCPProtocol.parse(line) else { + write(MCPProtocol.error(id: nil, code: MCPProtocol.parseError, message: "Parse error")) + continue + } + session.receive(message) + } + } + + private func write(_ message: [String: Any]) { + guard let data = MCPProtocol.encode(message) else { return } + lock.lock() + if closed || queuedBytes + data.count > MCPServer.maxQueuedBytes { + lock.unlock() + close() + return + } + queuedBytes += data.count + lock.unlock() + writer.async { [weak self, fd] in + data.withUnsafeBytes { buffer in + var offset = 0 + while offset < buffer.count { + let n = Darwin.write(fd, buffer.baseAddress! + offset, buffer.count - offset) + if n <= 0 { break } + offset += n + } + } + guard let self else { return } + self.lock.lock() + self.queuedBytes -= data.count + self.lock.unlock() + } + } +} + +// Newline-delimited lines from a file descriptor, capped at +// MCPProtocol.maxLineBytes: a longer line ends the connection. +struct MCPLineReader { + let fd: Int32 + private var buffer = Data() + private var done = false + + init(fd: Int32) { self.fd = fd } + + mutating func next() -> Data? { + while true { + if let newline = buffer.firstIndex(of: 0x0A) { + let line = buffer[buffer.startIndex.. MCPProtocol.maxLineBytes { return nil } + var chunk = [UInt8](repeating: 0, count: 8192) + let n = read(fd, &chunk, chunk.count) + if n <= 0 { + done = true + if buffer.isEmpty { return nil } + let last = buffer + buffer.removeAll() + return last + } + buffer.append(chunk, count: n) + } + } +} diff --git a/panel/MCPSession.swift b/panel/MCPSession.swift new file mode 100644 index 0000000..e0faf43 --- /dev/null +++ b/panel/MCPSession.swift @@ -0,0 +1,354 @@ +import Foundation + +// What the server reads from the app. The real one hops to main and reads nav +// and the stores; tests pass a fake, so the protocol is tested without an app. +protocol MCPContext: AnyObject { + var serverVersion: String { get } + func settings() -> [SettingSnapshot] + func sessions() -> [[String: Any]] +} + +// One client's conversation with the server, from the bridge's hello to the +// connection closing. Speaks both 2026-07-28 (server/discover, per-request +// _meta, subscriptions/listen) and the older initialize handshake with +// resources/subscribe, since the clients we target still send the latter. +// +// Thread-safe: requests arrive on the connection's reader, and change +// notifications from the app's observer. +final class MCPSession { + + static let settingsURI = "stacknudge://settings" + static let sessionsURI = "stacknudge://sessions" + static let settingsCategoryPrefix = "stacknudge://settings/" + + private let context: MCPContext + private let send: ([String: Any]) -> Void + private let lock = NSLock() + private(set) var caller: MCPCaller + + // resources/subscribe from an older client: URIs it wants + // notifications/resources/updated for. + private var legacySubscriptions: Set = [] + // subscriptions/listen streams, by the request's id. + private var listeners: [Listener] = [] + // Whether the client speaks 2026-07-28. Such a client hears a notification + // only on a stream that asked for it; an older one hears list changes + // unasked, as its revision allows. + private var modernClient = false + + private struct Listener { + let id: Any + let resourceURIs: Set + let toolsListChanged: Bool + let resourcesListChanged: Bool + } + + init(context: MCPContext, caller: MCPCaller, send: @escaping ([String: Any]) -> Void) { + self.context = context + self.caller = caller + self.send = send + } + + // MARK: - Incoming + + func receive(_ message: [String: Any]) { + guard let method = message["method"] as? String else { return } // a response to nothing we sent + let id = MCPProtocol.requestID(of: message) + let params = message["params"] as? [String: Any] ?? [:] + noteClient(params: params) + + // A notification: never answered. + guard let id else { + if method == "notifications/cancelled" { cancel(params["requestId"]) } + return + } + if let version = (params["_meta"] as? [String: Any])?[MCPProtocol.metaProtocolVersion] as? String, + version != MCPProtocol.currentVersion { + send(MCPProtocol.error(id: id, code: MCPProtocol.unsupportedProtocolVersion, + message: "Unsupported protocol version \(version)", + data: ["supported": [MCPProtocol.currentVersion] + MCPProtocol.legacyVersions])) + return + } + let modern = (params["_meta"] as? [String: Any])?[MCPProtocol.metaProtocolVersion] != nil + || method == "server/discover" + if modern { + lock.lock() + modernClient = true + lock.unlock() + } + do { + switch method { + case "initialize": respond(id, initialize(params), modern: false) + case "server/discover": respond(id, discover(), modern: true) + case "ping": respond(id, [:], modern: modern) + case "tools/list": respond(id, cacheable(["tools": tools()]), modern: modern) + case "tools/call": respond(id, try callTool(params), modern: modern) + case "resources/list": respond(id, cacheable(["resources": resources()]), modern: modern) + case "resources/templates/list": respond(id, cacheable(["resourceTemplates": resourceTemplates()]), modern: modern) + case "resources/read": respond(id, cacheable(try readResource(params)), modern: modern) + 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) + default: + send(MCPProtocol.error(id: id, code: MCPProtocol.methodNotFound, message: "Method not found: \(method)")) + } + } catch let failure as MCPFailure { + send(MCPProtocol.error(id: id, code: failure.code, message: failure.message)) + } catch { + send(MCPProtocol.error(id: id, code: MCPProtocol.internalError, message: "\(error)")) + } + } + + // The client names itself in initialize's clientInfo or every request's + // _meta. Only the name and version are kept, for display. + private func noteClient(params: [String: Any]) { + let info = params["clientInfo"] as? [String: Any] + ?? (params["_meta"] as? [String: Any])?[MCPProtocol.metaClientInfo] as? [String: Any] + guard let info, let name = info["name"] as? String else { return } + lock.lock() + caller.clientName = name + caller.clientVersion = info["version"] as? String + lock.unlock() + } + + private func respond(_ id: Any, _ result: [String: Any], modern: Bool) { + var result = result + result["resultType"] = "complete" + if modern { + var meta = result["_meta"] as? [String: Any] ?? [:] + meta[MCPProtocol.metaServerInfo] = serverInfo + result["_meta"] = meta + } + send(MCPProtocol.response(id: id, result: result)) + } + + // List and read results say how long they stay fresh (2026-07-28). Short: + // settings change under the client whenever someone opens Settings. + private func cacheable(_ result: [String: Any]) -> [String: Any] { + var result = result + result["ttlMs"] = 0 + result["cacheScope"] = "private" + return result + } + + // MARK: - Handshakes + + private var serverInfo: [String: Any] { + ["name": "stack-nudge", "version": context.serverVersion] + } + + static let instructions = """ + stack-nudge is the menu-bar app that tells this person when their coding agents finish or wait \ + on them. Use settings_list and settings_get to read its settings and sessions_list to see which \ + agent sessions are running and which are waiting on the user. + """ + + private var capabilities: [String: Any] { + ["tools": ["listChanged": true], + "resources": ["subscribe": true, "listChanged": true]] + } + + private func initialize(_ params: [String: Any]) -> [String: Any] { + let asked = params["protocolVersion"] as? String ?? "" + let version = MCPProtocol.legacyVersions.contains(asked) ? asked : MCPProtocol.legacyVersions[0] + return ["protocolVersion": version, "capabilities": capabilities, + "serverInfo": serverInfo, "instructions": Self.instructions] + } + + private func discover() -> [String: Any] { + ["supportedVersions": [MCPProtocol.currentVersion], "capabilities": capabilities, + "instructions": Self.instructions] + } + + // MARK: - Tools + + struct MCPFailure: Error { + let code: Int + let message: String + static func invalidParams(_ message: String) -> MCPFailure { + MCPFailure(code: MCPProtocol.invalidParams, message: message) + } + } + + // In a fixed order: clients cache the list, and the spec asks for it. + func tools() -> [[String: Any]] { + [ + ["name": "settings_list", + "title": "List stack-nudge settings", + "description": "Every stack-nudge setting with its current value, the values it takes and whether " + + "it can be changed from here. Pass a category to narrow it.", + "inputSchema": ["type": "object", + "properties": ["category": ["type": "string", "enum": SettingsRegistry.categories]], + "additionalProperties": false], + "annotations": ["readOnlyHint": true]], + ["name": "settings_get", + "title": "Read one stack-nudge setting", + "description": "One setting's current value, by its STACKNUDGE_ key.", + "inputSchema": ["type": "object", + "properties": ["key": ["type": "string"]], + "required": ["key"], "additionalProperties": false], + "annotations": ["readOnlyHint": true]], + ["name": "sessions_list", + "title": "List agent sessions", + "description": "The coding-agent sessions stack-nudge can see: agent, project, whether it's busy, " + + "and whether it's waiting on the user for a permission prompt.", + "inputSchema": ["type": "object", "properties": [:] as [String: Any], "additionalProperties": false], + "annotations": ["readOnlyHint": true]], + ] + } + + private func callTool(_ params: [String: Any]) throws -> [String: Any] { + guard let name = params["name"] as? String else { throw MCPFailure.invalidParams("Missing tool name") } + let arguments = params["arguments"] as? [String: Any] ?? [:] + switch name { + case "settings_list": + let category = arguments["category"] as? String + if let category, !SettingsRegistry.categories.contains(category) { + return MCPProtocol.toolError("No settings category \(category). Categories: " + + SettingsRegistry.categories.joined(separator: ", ")) + } + let settings = context.settings().filter { category == nil || $0.category == category } + return MCPProtocol.toolResult(["settings": settings.map(\.json)]) + case "settings_get": + guard let key = arguments["key"] as? String else { throw MCPFailure.invalidParams("settings_get needs a key") } + guard let setting = context.settings().first(where: { $0.key == key }) else { + return MCPProtocol.toolError("No setting \(key). settings_list names them all.") + } + return MCPProtocol.toolResult(setting.json) + case "sessions_list": + return MCPProtocol.toolResult(["sessions": context.sessions()]) + default: + throw MCPFailure.invalidParams("Unknown tool: \(name)") + } + } + + // MARK: - Resources + + func resources() -> [[String: Any]] { + [ + ["uri": Self.settingsURI, "name": "settings", "title": "stack-nudge settings", + "description": "Every setting and its current value, as settings_list returns them.", + "mimeType": "application/json"], + ["uri": Self.sessionsURI, "name": "sessions", "title": "Agent sessions", + "description": "The agent sessions stack-nudge sees, as sessions_list returns them.", + "mimeType": "application/json"], + ] + } + + func resourceTemplates() -> [[String: Any]] { + [["uriTemplate": Self.settingsCategoryPrefix + "{category}", "name": "settings-category", + "title": "One category of stack-nudge settings", "mimeType": "application/json"]] + } + + static func isKnownURI(_ uri: String) -> Bool { + if uri == settingsURI || uri == sessionsURI { return true } + guard uri.hasPrefix(settingsCategoryPrefix) else { return false } + return SettingsRegistry.categories.contains(String(uri.dropFirst(settingsCategoryPrefix.count))) + } + + private func readResource(_ params: [String: Any]) throws -> [String: Any] { + guard let uri = params["uri"] as? String else { throw MCPFailure.invalidParams("Missing uri") } + let body: Any + if uri == Self.settingsURI { + body = ["settings": context.settings().map(\.json)] + } else if uri == Self.sessionsURI { + body = ["sessions": context.sessions()] + } else if uri.hasPrefix(Self.settingsCategoryPrefix), Self.isKnownURI(uri) { + let category = String(uri.dropFirst(Self.settingsCategoryPrefix.count)) + body = ["settings": context.settings().filter { $0.category == category }.map(\.json)] + } else { + throw MCPFailure.invalidParams("Resource not found: \(uri)") + } + let data = try JSONSerialization.data(withJSONObject: body, options: [.sortedKeys, .withoutEscapingSlashes]) + return ["contents": [["uri": uri, "mimeType": "application/json", "text": String(decoding: data, as: UTF8.self)]]] + } + + private func subscribe(_ params: [String: Any]) throws -> [String: Any] { + guard let uri = params["uri"] as? String, Self.isKnownURI(uri) else { + throw MCPFailure.invalidParams("Resource not found: \(params["uri"] ?? "")") + } + lock.lock() + legacySubscriptions.insert(uri) + lock.unlock() + return [:] + } + + private func unsubscribe(_ params: [String: Any]) -> [String: Any] { + if let uri = params["uri"] as? String { + lock.lock() + legacySubscriptions.remove(uri) + lock.unlock() + } + return [:] + } + + // 2026-07-28: one long-lived request per stream. Acknowledged with what we + // honour, then left open; its response is the stream's end. + private func listen(id: Any, params: [String: Any]) { + 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, + toolsListChanged: filter["toolsListChanged"] as? Bool ?? false, + resourcesListChanged: filter["resourcesListChanged"] as? Bool ?? false) + var acknowledged: [String: Any] = [:] + if listener.toolsListChanged { acknowledged["toolsListChanged"] = true } + if listener.resourcesListChanged { acknowledged["resourcesListChanged"] = true } + if !uris.isEmpty { acknowledged["resourceSubscriptions"] = asked.filter(Self.isKnownURI) } + lock.lock() + listeners.append(listener) + lock.unlock() + send(MCPProtocol.notification("notifications/subscriptions/acknowledged", + params: ["_meta": [MCPProtocol.metaSubscriptionID: id], + "notifications": acknowledged])) + } + + private func cancel(_ requestID: Any?) { + lock.lock() + listeners.removeAll { MCPProtocol.sameID($0.id, requestID) } + lock.unlock() + } + + // MARK: - Change notifications + + // Called by the app when what a resource says has changed. Each stream or + // older subscription that asked for one of `uris` hears about it, once. + func resourcesUpdated(_ uris: Set) { + lock.lock() + let legacy = legacySubscriptions.intersection(uris) + let streams = listeners.map { ($0.id, $0.resourceURIs.intersection(uris)) }.filter { !$0.1.isEmpty } + lock.unlock() + for uri in legacy.sorted() { + send(MCPProtocol.notification("notifications/resources/updated", params: ["uri": uri])) + } + for (id, matched) in streams { + for uri in matched.sorted() { + send(MCPProtocol.notification("notifications/resources/updated", + params: ["uri": uri, "_meta": [MCPProtocol.metaSubscriptionID: id]])) + } + } + } + + // The tool list changed (an extension's tools came or went). See + // `modernClient` for who hears it. + func toolsListChanged() { + lock.lock() + let streams = listeners.filter(\.toolsListChanged).map(\.id) + let modern = modernClient + lock.unlock() + if !modern { + send(MCPProtocol.notification("notifications/tools/list_changed", params: [:])) + } + for id in streams { + send(MCPProtocol.notification("notifications/tools/list_changed", + params: ["_meta": [MCPProtocol.metaSubscriptionID: id]])) + } + } + + // The URIs a change to these settings touches: the whole list, and each + // changed setting's category. + static func settingsURIs(changed: [SettingSnapshot]) -> Set { + guard !changed.isEmpty else { return [] } + return Set([settingsURI] + changed.map { settingsCategoryPrefix + $0.category }) + } +} diff --git a/panel/Panel.swift b/panel/Panel.swift index 0476c76..c226b51 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1348,6 +1348,10 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, self?.nav.extensionGlances = glances }, signals: SignalRegistry(path: SignalRegistry.defaultPath)) private var listener: EventListener? + // The local MCP server on ~/.stack-nudge/mcp.sock, and what keeps its + // clients told about changes (docs/design/local-mcp.md). + private var mcpServer: MCPServer? + private var mcpChanges: MCPChangeWatcher? private var menuBar: MenuBarController? private var companion: CompanionController? private var githubFeed: GitHubFeedPoller? @@ -1656,6 +1660,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, _ = registerSpeakHotkey(spec: config.speakSelectionHotkeySpec) startListener() + startMCPServer() menuBar = MenuBarController(panelController: self) companion = CompanionController( store: store, sessions: sessions, nav: nav, @@ -4529,6 +4534,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, func applicationWillTerminate(_ notification: Notification) { listener?.stop() + mcpServer?.stop() quotaTimer?.invalidate() quotaTimer = nil // Stop any in-flight afplay/stackvox children so Quit silences @@ -6441,6 +6447,20 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, return NSScreen.main ?? NSScreen.screens.first ?? panel.screen ?? NSScreen() } + // 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)) + do { + try server.start() + mcpServer = server + mcpChanges = MCPChangeWatcher(server: server, nav: nav, store: store, sessions: sessions) + } catch { + FileHandle.standardError.write(Data("stack-nudge: MCP server failed to start: \(error)\n".utf8)) + } + } + private func startListener() { let installDir = ("~/.stack-nudge" as NSString).expandingTildeInPath try? FileManager.default.createDirectory( diff --git a/panel/SettingsRegistry.swift b/panel/SettingsRegistry.swift new file mode 100644 index 0000000..85953d7 --- /dev/null +++ b/panel/SettingsRegistry.swift @@ -0,0 +1,205 @@ +import Foundation + +// One entry per STACKNUDGE_* setting an MCP client may see: its key, how +// Settings labels and groups it, the values it takes, and how to read it from +// nav. The panel's rows keep their own drawing; this is the machine-readable +// view of the same values (docs/design/local-mcp.md, "Writes"). +// +// Secrets never appear: the Slack and GitHub tokens live in the Keychain and +// aren't settings, and the Slack member ID is reported as set or not only. +struct SettingSpec { + + enum Kind { + case toggle + case choice([String]) + case integer([Int]) + case number(min: Double, max: Double, step: Double) + case text + } + + let key: String + let label: String + // SettingsCategory's sidebar name, lowercased. + let category: String + let kind: Kind + let read: (PanelNav) -> SettingValue + // Why an MCP client may never change it. nil means it may. + var readOnlyReason: String? = nil +} + +enum SettingValue: Equatable { + case bool(Bool) + case int(Int) + case double(Double) + case string(String) + + var json: Any { + switch self { + case .bool(let value): return value + case .int(let value): return value + case .double(let value): return value + case .string(let value): return value + } + } +} + +// A setting as listed to a client: the spec's description and its value now. +struct SettingSnapshot: Equatable { + let key: String + let label: String + let category: String + let value: SettingValue + let kindJSON: [String: AnyHashable] + let readOnlyReason: String? + + var json: [String: Any] { + var entry: [String: Any] = ["key": key, "label": label, "category": category, + "value": value.json, "writable": readOnlyReason == nil] + for (name, value) in kindJSON { entry[name] = value } + if let readOnlyReason { entry["readOnlyReason"] = readOnlyReason } + return entry + } +} + +enum SettingsRegistry { + + // Settings an agent must never be able to change: each stops a permission + // prompt reaching you, or would let a client widen its own reach. + static let protectsPrompts = "Protects how permission prompts reach you. Change it in Settings." + static let panelOnly = "Recorded by pressing the shortcut in Settings." + static let protectsLock = "Part of locking the screen when you're away. Change it in Settings." + + static func snapshot(_ nav: PanelNav) -> [SettingSnapshot] { + specs.map { spec in + SettingSnapshot(key: spec.key, label: spec.label, category: spec.category, + value: spec.read(nav), kindJSON: kindJSON(spec.kind), + readOnlyReason: spec.readOnlyReason) + } + } + + static func spec(_ key: String) -> SettingSpec? { + specs.first { $0.key == key } + } + + static var categories: [String] { + var seen = Set() + return specs.map(\.category).filter { seen.insert($0).inserted } + } + + static func kindJSON(_ kind: SettingSpec.Kind) -> [String: AnyHashable] { + switch kind { + case .toggle: + return ["type": "boolean"] + case .choice(let options): + return ["type": "string", "options": options] + case .integer(let options): + return ["type": "integer", "options": options] + case .number(let min, let max, let step): + return ["type": "number", "minimum": min, "maximum": max, "step": step] + case .text: + return ["type": "string"] + } + } + + // In Settings' order: by category, then as each page lists them. + static let specs: [SettingSpec] = [ + // Notifications + SettingSpec(key: "STACKNUDGE_BANNER", label: "Banner notifications", category: "notifications", + kind: .toggle, read: { .bool($0.bannerEnabled) }, readOnlyReason: protectsPrompts), + SettingSpec(key: "STACKNUDGE_MUTE_WHEN_FOCUSED", label: "Mute when focused", category: "notifications", + kind: .toggle, read: { .bool($0.muteWhenFocused) }, readOnlyReason: protectsPrompts), + SettingSpec(key: "STACKNUDGE_MUTE_DURATION_MIN", label: "Mute duration (minutes)", category: "notifications", + kind: .integer(PanelNav.muteDurationOptions), read: { .int($0.muteDurationMinutes) }), + SettingSpec(key: "STACKNUDGE_REMIND_MIN", label: "Remind unanswered (minutes)", category: "notifications", + kind: .integer(AttentionPolicy.reminderMinuteOptions), read: { .int($0.remindMinutes) }, + readOnlyReason: protectsPrompts), + SettingSpec(key: "STACKNUDGE_STALLED_MIN", label: "Flag stalled after (minutes, 0 is off)", category: "notifications", + kind: .integer(AttentionPolicy.stalledMinuteOptions), read: { .int($0.stalledMinutes) }), + SettingSpec(key: "STACKNUDGE_SOUND", label: "Sound enabled", category: "notifications", + kind: .toggle, read: { .bool($0.soundEnabled) }), + SettingSpec(key: "STACKNUDGE_SOUND_STOP", label: "Agent done sound", category: "notifications", + kind: .choice(PanelNav.macSounds), read: { .string($0.soundStop) }), + SettingSpec(key: "STACKNUDGE_SOUND_PERMISSION", label: "Permission sound", category: "notifications", + kind: .choice(PanelNav.macSounds), read: { .string($0.soundPermission) }), + // Voice + SettingSpec(key: "STACKNUDGE_VOICE", label: "Voice notifications", category: "voice", + kind: .toggle, read: { .bool($0.voiceEnabled) }), + SettingSpec(key: "STACKNUDGE_VOICE_NAME", label: "Voice", category: "voice", + kind: .text, read: { .string($0.voice) }), + SettingSpec(key: "STACKNUDGE_VOICE_SPEED", label: "Speed", category: "voice", + kind: .number(min: PanelNav.speedMin, max: PanelNav.speedMax, step: PanelNav.speedStep), + read: { .double($0.voiceSpeed) }), + SettingSpec(key: "STACKNUDGE_SPEAK_HOTKEY", label: "Speak shortcut", category: "voice", + kind: .text, read: { .string($0.speakHotkeyDisplay) }, readOnlyReason: panelOnly), + // Appearance + SettingSpec(key: "STACKNUDGE_FLOATING_WIDGET", label: "Floating widget", category: "appearance", + kind: .choice(FloatingWidget.allCases.map(\.rawValue)), read: { .string($0.floatingWidget.rawValue) }), + SettingSpec(key: "STACKNUDGE_COMPACT_SNAP", label: "Snap to corners", category: "appearance", + kind: .toggle, read: { .bool($0.compactSnap) }), + SettingSpec(key: "STACKNUDGE_COMPACT_CORNER", label: "Widget corner", category: "appearance", + kind: .choice(CompactCorner.allCases.map(\.rawValue)), read: { .string($0.compactCorner.rawValue) }), + SettingSpec(key: "STACKNUDGE_COMPACT_ALPHA", label: "Widget opacity", category: "appearance", + kind: .number(min: 0.4, max: 1.0, step: 0.2), read: { .double($0.compactAlpha) }), + SettingSpec(key: "STACKNUDGE_COMPACT_CONTENT", label: "Widget type", category: "appearance", + kind: .choice(CompactContent.allCases.map(\.rawValue)), read: { .string($0.compactContent.rawValue) }), + SettingSpec(key: "STACKNUDGE_MASCOT", label: "Mascot", category: "appearance", + kind: .choice(MascotKind.allCases.map(\.rawValue)), read: { .string($0.mascot.rawValue) }), + SettingSpec(key: "STACKNUDGE_THEME", label: "Accent color", category: "appearance", + kind: .choice(AccentTheme.allCases.map(\.rawValue)), read: { .string($0.theme.rawValue) }), + // Companion + SettingSpec(key: "STACKNUDGE_COMPANION_SIZE", label: "Size", category: "companion", + kind: .choice(CompanionSize.allCases.map(\.rawValue)), read: { .string($0.companionSize.rawValue) }), + SettingSpec(key: "STACKNUDGE_COMPANION_BADGE", label: "Count badge", category: "companion", + kind: .toggle, read: { .bool($0.companionBadge) }), + // Usage + SettingSpec(key: "STACKNUDGE_QUOTA_TRACKING", label: "Quota tracking", category: "usage", + kind: .toggle, read: { .bool($0.quotaTrackingEnabled) }), + SettingSpec(key: "STACKNUDGE_QUOTA_ALERTS", label: "Quota alerts", category: "usage", + kind: .toggle, read: { .bool($0.quotaAlertsEnabled) }), + SettingSpec(key: "STACKNUDGE_QUOTA_THRESHOLD", label: "Alert threshold (%)", category: "usage", + kind: .integer(PanelNav.quotaThresholds), read: { .int($0.quotaAlertThreshold) }), + SettingSpec(key: "STACKNUDGE_USAGE_POLL_MIN", label: "Poll frequency (minutes)", category: "usage", + kind: .integer(PanelNav.quotaPollMinuteOptions), read: { .int($0.quotaPollMinutes) }), + SettingSpec(key: "STACKNUDGE_CONTEXT_ALERT_THRESHOLD", label: "Context alert at (thousand tokens, 0 is off)", + category: "usage", kind: .integer(PanelNav.contextAlertThresholdOptions), + read: { .int($0.contextAlertThresholdK) }), + SettingSpec(key: "STACKNUDGE_QUOTA_SHOW_REMAINING", label: "Show remaining", category: "usage", + kind: .toggle, read: { .bool($0.quotaShowRemaining) }), + // Integrations + SettingSpec(key: "STACKNUDGE_SLACK", label: "Slack notifications", category: "integrations", + kind: .toggle, read: { .bool($0.slackEnabled) }), + SettingSpec(key: "STACKNUDGE_SLACK_IDLE_MIN", label: "Slack: notify when idle (minutes, 0 is always)", + category: "integrations", kind: .integer(SlackDelivery.idleMinuteOptions), + read: { .int($0.slackIdleMinutes) }), + SettingSpec(key: "STACKNUDGE_SLACK_DETAIL", label: "Slack: include message text", category: "integrations", + kind: .toggle, read: { .bool($0.slackIncludeDetail) }), + SettingSpec(key: "STACKNUDGE_SLACK_STOP", label: "Slack: also notify on finished turns", category: "integrations", + kind: .toggle, read: { .bool($0.slackNotifyOnStop) }), + SettingSpec(key: "STACKNUDGE_GITHUB", label: "GitHub PR links", category: "integrations", + kind: .toggle, read: { .bool($0.githubLinkingEnabled) }), + SettingSpec(key: "STACKNUDGE_GITHUB_ACTIVITY", label: "GitHub activity", category: "integrations", + kind: .toggle, read: { .bool($0.githubActivityEnabled) }), + SettingSpec(key: "STACKNUDGE_HIDE_SHIPPED", label: "Hide shipped", category: "integrations", + kind: .toggle, read: { .bool($0.hideShippedTickets) }), + // Panel + SettingSpec(key: "STACKNUDGE_PANEL_HOTKEY", label: "Panel shortcut", category: "panel", + kind: .text, read: { .string($0.hotkeyDisplay) }, readOnlyReason: panelOnly), + SettingSpec(key: "STACKNUDGE_PANEL_PIN", label: "Pin panel", category: "panel", + kind: .toggle, read: { .bool($0.panelPinned) }), + SettingSpec(key: "STACKNUDGE_KEEP_OPEN_WHEN_EMPTY", label: "Keep open when empty", category: "panel", + kind: .toggle, read: { .bool($0.keepOpenWhenEmpty) }), + SettingSpec(key: "STACKNUDGE_TAB_TITLE_NAMES", label: "Name from tab titles", category: "panel", + kind: .toggle, read: { .bool($0.tabTitleNames) }), + // Events + SettingSpec(key: "STACKNUDGE_EVENTS_PER_SESSION", label: "History per session", category: "events", + kind: .integer(PanelNav.eventsPerSessionOptions), read: { .int($0.eventsPerSession) }), + SettingSpec(key: "STACKNUDGE_EVENT_HISTORY", label: "Event history", category: "events", + kind: .toggle, read: { .bool($0.eventHistoryEnabled) }), + // Extensions + SettingSpec(key: "STACKNUDGE_AWAY_LOCK", label: "Lock screen when away", category: "extensions", + kind: .toggle, read: { .bool($0.awayLock) }, readOnlyReason: protectsLock), + // Actions + SettingSpec(key: UpdateChannel.configKey, label: "Update channel", category: "actions", + kind: .choice(UpdateChannel.allCases.map(\.rawValue)), read: { .string($0.updateChannel.rawValue) }), + ] +} diff --git a/panel/main.swift b/panel/main.swift index 55efa66..ff5ee4e 100644 --- a/panel/main.swift +++ b/panel/main.swift @@ -1,5 +1,9 @@ import AppKit +// An MCP client launched this binary as its server: relay to the running app +// and exit, before anything AppKit starts. See MCPBridge. +MCPBridge.runIfAsked() + let app = NSApplication.shared // Dev-only: renders fixture screenshots and exits. See ScreenshotRenderer. ScreenshotRenderer.runIfAsked() From eabb0557064a1f2463128caf097256f9026e292b Mon Sep 17 00:00:00 2001 From: StuBehan Date: Tue, 24 Nov 2026 22:41:26 +0000 Subject: [PATCH 3/4] fix(mcp): start the server once the config has loaded Started before nav read the config, the watcher's first snapshot held the defaults, so every launch told clients that each non-default setting had just changed. A refusal for a per-request revision now names only the one that carries _meta. --- Tests/StackNudgePanelCoreTests/MCPServerTests.swift | 8 ++++++++ panel/MCPSession.swift | 4 +++- panel/Panel.swift | 5 ++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Tests/StackNudgePanelCoreTests/MCPServerTests.swift b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift index 2a8625c..29d84c4 100644 --- a/Tests/StackNudgePanelCoreTests/MCPServerTests.swift +++ b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift @@ -71,6 +71,14 @@ final class MCPSessionTests: XCTestCase { XCTAssertEqual(lastError?["code"] as? Int, MCPProtocol.unsupportedProtocolVersion) } + func testAnOlderRevisionNamedPerRequestIsRefusedWithOnlyTheCurrentOne() { + let session = session() + session.receive(["jsonrpc": "2.0", "id": 3, "method": "tools/list", + "params": ["_meta": [MCPProtocol.metaProtocolVersion: MCPProtocol.legacyVersions[0]]]]) + XCTAssertEqual(lastError?["code"] as? Int, MCPProtocol.unsupportedProtocolVersion) + XCTAssertEqual((lastError?["data"] as? [String: Any])?["supported"] as? [String], [MCPProtocol.currentVersion]) + } + func testNotificationsAreNeverAnswered() { let session = session() session.receive(["jsonrpc": "2.0", "method": "notifications/initialized"]) diff --git a/panel/MCPSession.swift b/panel/MCPSession.swift index e0faf43..e0435f9 100644 --- a/panel/MCPSession.swift +++ b/panel/MCPSession.swift @@ -64,9 +64,11 @@ final class MCPSession { } if let version = (params["_meta"] as? [String: Any])?[MCPProtocol.metaProtocolVersion] as? String, version != MCPProtocol.currentVersion { + // Only the revisions that carry _meta: the older ones are reached + // through initialize, never named per request. send(MCPProtocol.error(id: id, code: MCPProtocol.unsupportedProtocolVersion, message: "Unsupported protocol version \(version)", - data: ["supported": [MCPProtocol.currentVersion] + MCPProtocol.legacyVersions])) + data: ["supported": [MCPProtocol.currentVersion]])) return } let modern = (params["_meta"] as? [String: Any])?[MCPProtocol.metaProtocolVersion] != nil diff --git a/panel/Panel.swift b/panel/Panel.swift index c226b51..e1dcf64 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1660,7 +1660,6 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, _ = registerSpeakHotkey(spec: config.speakSelectionHotkeySpec) startListener() - startMCPServer() menuBar = MenuBarController(panelController: self) companion = CompanionController( store: store, sessions: sessions, nav: nav, @@ -1771,6 +1770,10 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, MainActor.assumeIsolated { self?.companion?.noteArrival(event) } } nav.loadFromConfig() // populate panelPinned + other live values up-front + // After the config, so the server's first view of the settings is the + // user's: started earlier, the load reads to its clients as every + // non-default setting changing at once. + startMCPServer() // Scan agent configs for missing wires (post-update / post-install // reconciliation). Surfaces a "Set up X" banner in Settings when // any detected agent lacks our notify.sh hook. From e18431f1d1e486eb65c6bc4430acc7f15cc661d8 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Wed, 25 Nov 2026 00:08:43 +0000 Subject: [PATCH 4/4] refactor(mcp): sessions_list reads SessionSnapshot The same shape event:session sends, so the two agree on what waiting means, and leave out paths and terminal names the same way. Ended sessions are left out, and the watcher compares snapshots rather than a JSON signature. --- .../MCPServerTests.swift | 30 +++++---- docs/design/service-extensions.md | 4 +- panel/MCPAppContext.swift | 62 ++++++------------- panel/MCPSession.swift | 4 +- panel/SessionSnapshot.swift | 6 +- 5 files changed, 46 insertions(+), 60 deletions(-) diff --git a/Tests/StackNudgePanelCoreTests/MCPServerTests.swift b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift index 29d84c4..9e29143 100644 --- a/Tests/StackNudgePanelCoreTests/MCPServerTests.swift +++ b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift @@ -294,19 +294,27 @@ final class SettingsRegistryTests: XCTestCase { final class MCPSessionsTests: XCTestCase { - func testASessionIsWaitingWhileItsPromptIsInEvents() { - var session = Session(id: 9, pid: 9, agent: "claude", projectPath: "/r", projectName: "r", - terminalPID: nil, terminalApp: nil, elapsed: nil, customName: nil, status: .active) - session.claudeSessionID = "s-9" + private func session(_ pid: Int, claude: String, status: SessionStatus = .active) -> Session { + var session = Session(id: pid, pid: pid, agent: "claude", projectPath: "/r", projectName: "r", + terminalPID: nil, terminalApp: nil, elapsed: nil, customName: nil, status: status) + session.claudeSessionID = claude + return session + } + + func testASessionIsWaitingWhileItsPromptIsStillBlocking() { let prompt = NudgeEvent(agent: "claude", kind: .permission, title: "Claude Code", message: "Bash(ls)", claudeSessionID: "s-9") - let other = NudgeEvent(agent: "claude", kind: .permission, title: "Claude Code", message: "Bash(ls)", - claudeSessionID: "s-1") - XCTAssertTrue(MCPSessions.isWaiting(session, events: [prompt])) - XCTAssertFalse(MCPSessions.isWaiting(session, events: [other])) - let entry = MCPSessions.snapshot([session], events: [prompt], allowTabTitle: false).first - XCTAssertEqual(entry?["waitingOnUser"] as? Bool, true) - XCTAssertEqual(entry?["claudeSessionId"] as? String, "s-9") + let entries = MCPSessions.list([session(9, claude: "s-9"), session(1, claude: "s-1")], events: [prompt], + isBlocking: { _ in true }).map(MCPSessions.json) + XCTAssertEqual(entries.map { $0["state"] as? String }, ["waiting", "active"]) + XCTAssertEqual(entries.first?["claudeSessionId"] as? String, "s-9") + XCTAssertEqual(entries.first?["repo"] as? String, "r") + XCTAssertNil(entries.first?["path"], "no paths, as event:session") + } + + func testAnEndedSessionIsLeftOut() { + let entries = MCPSessions.list([session(9, claude: "s-9", status: .finished(at: Date()))], events: []) + XCTAssertTrue(entries.isEmpty) } } diff --git a/docs/design/service-extensions.md b/docs/design/service-extensions.md index c976337..5506bd8 100644 --- a/docs/design/service-extensions.md +++ b/docs/design/service-extensions.md @@ -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. diff --git a/panel/MCPAppContext.swift b/panel/MCPAppContext.swift index 2f296c6..87cf384 100644 --- a/panel/MCPAppContext.swift +++ b/panel/MCPAppContext.swift @@ -27,8 +27,7 @@ final class MCPAppContext: MCPContext { func sessions() -> [[String: Any]] { onMain { guard let sessionStore else { return [] } - return MCPSessions.snapshot(sessionStore.sessions, events: store?.events ?? [], - allowTabTitle: nav?.tabTitleNames ?? false) + return MCPSessions.list(sessionStore.sessions, events: store?.events ?? []).map(MCPSessions.json) } } @@ -37,37 +36,23 @@ final class MCPAppContext: MCPContext { } } -// The sessions as a client sees them. Pure, for tests. +// 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 snapshot(_ sessions: [Session], events: [NudgeEvent], allowTabTitle: Bool) -> [[String: Any]] { - let iso = ISO8601DateFormatter() - return sessions.filter { $0.status == .active }.map { session in - var entry: [String: Any] = [ - "pid": session.pid, - "agent": session.agent, - "name": SessionLabel.displayName(for: session, fallback: session.agent, allowTabTitle: allowTabTitle), - "busy": session.liveStatus == "busy", - "waitingOnUser": isWaiting(session, events: events), - ] - if let project = session.projectName { entry["project"] = project } - if let path = session.projectPath { entry["path"] = path } - if let terminal = session.terminalApp { entry["terminal"] = terminal } - if let id = session.claudeSessionID { entry["claudeSessionId"] = id } - if let at = session.lastActivityAt { entry["lastActivity"] = iso.string(from: at) } - return entry - } + 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 } } - // A permission prompt from this session is still in Events: answered and - // dead prompts leave the queue, so one that's there is waiting. - static func isWaiting(_ session: Session, events: [NudgeEvent]) -> Bool { - events.contains { event in - guard event.kind == .permission, !event.isFeed else { return false } - if let id = session.claudeSessionID, let eventID = event.claudeSessionID { return id == eventID } - if let pid = event.agentPID { return pid == session.pid } - return false - } + 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 } } @@ -82,7 +67,7 @@ final class MCPChangeWatcher { private weak var store: EventStore? private weak var sessionStore: SessionStore? private var lastSettings: [String: SettingValue] = [:] - private var lastSessions = "" + private var lastSessions: [SessionSnapshot] = [] private var cancellables = Set() init(server: MCPServer, nav: PanelNav, store: EventStore, sessions: SessionStore) { @@ -91,7 +76,7 @@ final class MCPChangeWatcher { self.store = store self.sessionStore = sessions lastSettings = Self.values(SettingsRegistry.snapshot(nav)) - lastSessions = sessionsSignature() + lastSessions = currentSessions() Publishers.Merge3(nav.objectWillChange.map { _ in () }, store.objectWillChange.map { _ in () }, sessions.objectWillChange.map { _ in () }) @@ -106,7 +91,7 @@ final class MCPChangeWatcher { let changed = snapshot.filter { lastSettings[$0.key] != $0.value } lastSettings = Self.values(snapshot) var uris = MCPSession.settingsURIs(changed: changed) - let sessions = sessionsSignature() + let sessions = currentSessions() if sessions != lastSessions { lastSessions = sessions uris.insert(MCPSession.sessionsURI) @@ -118,15 +103,8 @@ final class MCPChangeWatcher { Dictionary(snapshot.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first }) } - private func sessionsSignature() -> String { - guard let sessionStore else { return "" } - let entries = MCPSessions.snapshot(sessionStore.sessions, events: store?.events ?? [], - allowTabTitle: nav?.tabTitleNames ?? false) - // lastActivity moves on every tick of a busy session; a client - // subscribing to the list wants to hear about sessions coming, - // going, and starting or stopping waiting. - .map { $0.filter { $0.key != "lastActivity" } } - guard let data = try? JSONSerialization.data(withJSONObject: entries, options: [.sortedKeys]) else { return "" } - return String(decoding: data, as: UTF8.self) + private func currentSessions() -> [SessionSnapshot] { + guard let sessionStore else { return [] } + return MCPSessions.list(sessionStore.sessions, events: store?.events ?? []) } } diff --git a/panel/MCPSession.swift b/panel/MCPSession.swift index e0435f9..c52ea13 100644 --- a/panel/MCPSession.swift +++ b/panel/MCPSession.swift @@ -192,8 +192,8 @@ final class MCPSession { "annotations": ["readOnlyHint": true]], ["name": "sessions_list", "title": "List agent sessions", - "description": "The coding-agent sessions stack-nudge can see: agent, project, whether it's busy, " - + "and whether it's waiting on the user for a permission prompt.", + "description": "The coding-agent sessions stack-nudge can see: agent, repo, and state: busy, idle, " + + "waiting on the user for a permission prompt, or active when the agent doesn't say.", "inputSchema": ["type": "object", "properties": [:] as [String: Any], "additionalProperties": false], "annotations": ["readOnlyHint": true]], ] diff --git a/panel/SessionSnapshot.swift b/panel/SessionSnapshot.swift index ed48bb8..9432fae 100644 --- a/panel/SessionSnapshot.swift +++ b/panel/SessionSnapshot.swift @@ -1,9 +1,9 @@ import Foundation // One agent session as stack-nudge describes it to anything outside the panel: -// service extensions behind `event:session`, and the MCP server once it reads -// this too. Built from SessionStore's poll and the prompts waiting in Events, -// so both get the same shape and agree on what "waiting" means. +// service extensions behind `event:session`, and the MCP server's +// `sessions_list`. Built from SessionStore's poll and the prompts waiting in +// Events, so both get the same shape and agree on what "waiting" means. // // What it leaves out is deliberate: no paths, no prompt or tool text, no // terminal or tab identifiers. The repo's name and the name a person chose for