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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ final class ExtensionSettingsPageTests: XCTestCase {
XCTAssertEqual(nav.label(for: .extensionPage("away")), "Away")
XCTAssertEqual(nav.selectedRow, .extensionSetting("away", "STACKNUDGE_EXT_A"), "lands on the first row")
nav.selectNextCategory()
XCTAssertEqual(nav.settingsCategory, .panel)
XCTAssertEqual(nav.settingsCategory, .mcp)
}

// Settings, then the app's lock row, then Update when there is one, then
Expand Down
109 changes: 109 additions & 0 deletions Tests/StackNudgePanelCoreTests/MCPClientsTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import XCTest

@testable import StackNudgePanelCore

// Settings → MCP → Set up for…: what each client's setup copies, and whether
// its config already has stack-nudge.
final class MCPClientsTests: XCTestCase {

private let binary = "/Users/me/Applications/StackNudge.app/Contents/MacOS/stack-nudge"

func testEachSetupPointsAtTheAppsOwnBinary() {
XCTAssertEqual(MCPClient.claudeCode.setup(binary: binary),
"claude mcp add --scope user stack-nudge -- \(binary) --mcp")
XCTAssertEqual(MCPClient.codex.setup(binary: binary), "codex mcp add stack-nudge -- \(binary) --mcp")
XCTAssertEqual(MCPClient.claudeDesktop.setup(binary: binary),
#""stack-nudge": {"command": "\#(binary)", "args": ["--mcp"]}"#)
}

// What Desktop gets pasted into its JSON has to stay JSON.
func testDesktopsEntryParsesInsideMCPServers() throws {
let entry = MCPClient.claudeDesktop.setup(binary: "/Users/a \"b\"/stack-nudge")
let config = "{\"mcpServers\": {\(entry)}}"
XCTAssertTrue(MCPClient.claudeDesktop.hasBridge(in: config))
}

func testAPathWithASpaceIsQuotedForTheShell() {
XCTAssertEqual(MCPClient.codex.setup(binary: "/Apps/Stack Nudge/stack-nudge"),
"codex mcp add stack-nudge -- '/Apps/Stack Nudge/stack-nudge' --mcp")
}

func testClaudeCodeIsFoundAtUserOrProjectScope() {
let user = #"{"mcpServers": {"nudge": {"type": "stdio", "command": "\#(binary)", "args": ["--mcp"]}}}"#
let project = #"{"projects": {"/r": {"mcpServers": {"stack-nudge": {"command": "\#(binary)", "args": ["--mcp"]}}}}}"#
XCTAssertTrue(MCPClient.claudeCode.hasBridge(in: user), "found whatever it was named")
XCTAssertTrue(MCPClient.claudeCode.hasBridge(in: project))
}

func testOtherServersAndTheAppWithoutTheFlagDontCount() {
let other = #"{"mcpServers": {"x": {"command": "npx", "args": ["stack-nudge", "--mcp"]}}}"#
let noFlag = #"{"mcpServers": {"x": {"command": "\#(binary)", "args": []}}}"#
XCTAssertFalse(MCPClient.claudeDesktop.hasBridge(in: other))
XCTAssertFalse(MCPClient.claudeDesktop.hasBridge(in: noFlag))
XCTAssertFalse(MCPClient.claudeDesktop.hasBridge(in: "not json"))
}

func testCodexsTableIsFound() {
let config = """
model = "gpt-5"

[mcp_servers.other]
command = "npx"
args = ["-y", "thing"]

[mcp_servers.stack-nudge]
command = "\(binary)"
args = [
"--mcp",
]
"""
XCTAssertTrue(MCPClient.codex.hasBridge(in: config))
XCTAssertFalse(MCPClient.codex.hasBridge(in: "[mcp_servers.other]\ncommand = \"npx\"\nargs = [\"--mcp\"]"))
XCTAssertFalse(MCPClient.codex.hasBridge(in: "[profiles.x]\ncommand = \"\(binary)\"\nargs = [\"--mcp\"]"))
}

// Extra Claude config dirs and Codex homes count as much as the defaults.
func testAClientIsTickedFromAnyOfItsConfigs() {
let codexEntry = "[mcp_servers.n]\ncommand = \"\(binary)\"\nargs = [\"--mcp\"]"
let files = ["/work/.claude/.claude.json": #"{"mcpServers": {"n": {"command": "\#(binary)", "args": ["--mcp"]}}}"#,
"/h/.codex/config.toml": codexEntry]
let configured = MCPClient.configured(home: "/h", claudeDirs: ["/work/.claude"], codexHomes: [],
read: { files[$0] })
XCTAssertEqual(configured, [.claudeCode, .codex])
}
}

// The MCP category and the page below it, reached and left as an integration
// page is.
@MainActor
final class MCPSettingsTests: XCTestCase {

func testTheCategoryHoldsTheDoorAndTheWritesSwitch() {
let nav = PanelNav()
XCTAssertEqual(nav.rows(in: .mcp), [.mcpSetupClients, .mcpWrites])
XCTAssertEqual(nav.rows(in: .mcpSetupPage), MCPClient.allCases.map { .mcpClient($0) })
XCTAssertFalse(nav.rows(in: .actions).contains(.mcpWrites))
XCTAssertEqual(SettingsCategory.allCases.firstIndex(of: .mcp),
SettingsCategory.allCases.firstIndex(of: .extensions).map { $0 + 1 })
}

func testThePageOpensFromItsRowAndGoesBackToIt() {
let nav = PanelNav()
nav.settingsCategory = .mcp
nav.settingsDetailFocused = true
nav.selectFirstCategoryRow()
XCTAssertEqual(nav.selectedRow, .mcpSetupClients)
XCTAssertTrue(nav.selectedRowOpensOnRight)
nav.openMCPSetupPage()
XCTAssertEqual(nav.settingsCategory, .mcpSetupPage)
XCTAssertEqual(nav.sidebarCategory, .mcp, "MCP stays lit while its page is open")
XCTAssertEqual(nav.settingsBackLabel, "MCP")
nav.settingsBack()
XCTAssertEqual(nav.settingsCategory, .mcp)
XCTAssertEqual(nav.selectedRow, .mcpSetupClients)
}

func testTheWritesSwitchIsListedUnderMCP() {
XCTAssertEqual(SettingsRegistry.spec("STACKNUDGE_MCP_WRITES")?.category, "mcp")
}
}
4 changes: 2 additions & 2 deletions Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ final class SettingsCategoryTests: XCTestCase {
func testEveryCategoryRowIsReachableAndUnique() {
let nav = PanelNav()
var seen: [SettingsRow] = []
for category in SettingsCategory.allCases + Integration.allCases.map({ .integrationPage($0) }) {
for category in SettingsCategory.allCases + Integration.allCases.map({ .integrationPage($0) }) + [.mcpSetupPage] {
seen += nav.rows(in: category)
}
XCTAssertEqual(Set(seen).count, seen.count, "a row appears in two categories")
Expand Down Expand Up @@ -60,7 +60,7 @@ final class SettingsCategoryTests: XCTestCase {
// GitHub page swaps Connect for Disconnect on signing in; every branch
// is reachable, so every one counts as a home.
let pages: [SettingsCategory] = Integration.allCases.map { .integrationPage($0) }
+ [.extensionPage(SettingsRow.representativeExtensionID)]
+ [.extensionPage(SettingsRow.representativeExtensionID), .mcpSetupPage]
for cached in [true, false] {
for signedIn in [true, false] {
nav.voiceModelCached = cached
Expand Down
8 changes: 5 additions & 3 deletions docs/design/local-mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,10 +183,12 @@ anything else (Settings, the config file) is credited to `stack-nudge`.
## Writes

Settings writes are the main use, so v1 has them. One switch governs them,
Settings → Actions → **MCP clients can change settings** (`STACKNUDGE_MCP_WRITES`),
Settings → MCP → **MCP clients can change settings** (`STACKNUDGE_MCP_WRITES`),
on by default. It is a client-side opt-in already: nothing reaches stack-nudge
until you add the server, and **Copy MCP setup for Claude Code** on the same
page copies the line that does it, pointing at the installed app.
until you add the server, and **Set up for…** on the same page lists Claude
Code, Claude Desktop and Codex, copies what adds it to each, pointing at the
installed app, and ticks the ones whose config already has it. stack-nudge
reads those configs and never writes them.

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
Expand Down
5 changes: 4 additions & 1 deletion docs/panel.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,14 @@ Reachable from the tab strip, `Cmd+,`, or the last `Cmd`-number. A sidebar of ca
| **Usage** | Quota tracking, Quota alerts, Alert threshold, Poll frequency, Context alert, Show remaining, and the two pi budgets |
| **Integrations** | A card each for Slack and GitHub, with where it stands on the right; `→` or `⏎` opens its page. Slack's: paste setup, detected user, test message, on/off, idle threshold, message text, finished turns. GitHub's: PR links, GitHub activity, Hide shipped, Connect GitHub (or Disconnect once signed in). Each page's first line says what it's doing or what's wrong |
| **Extensions** | What's installed, then **Browse extensions** (see [Extensions](#extensions)) |
| **MCP** | **Set up for…**, whose page has a card each for Claude Code, Claude Desktop and Codex: `⏎` copies what adds stack-nudge to it, and a tick shows once its config has it. Then MCP clients can change settings. See [the local MCP server](design/local-mcp.md) |
| **Panel** | Hotkey, Pin panel, Keep open when empty, Launch at login, Name from tab titles |
| **Events** | History per session, Event history, Clear event history |
| **Actions** | Edit phrases, Check permissions, Open config file, View release notes, Update channel (Stable or Nightly, see [Nightly builds](setup.md#nightly-builds)), Check for updates, Copy MCP setup for Claude Code and MCP clients can change settings (see [the local MCP server](design/local-mcp.md)), Uninstall, Quit |
| **Actions** | Edit phrases, Check permissions, Open config file, View release notes, Update channel (Stable or Nightly, see [Nightly builds](setup.md#nightly-builds)), Check for updates, Uninstall, Quit |
| **About** | The version and hook-script status, and a link to this repo |

The version, nightly build number included, is on the left of the footer on every Settings page.

An extension that asks for a Settings page gets one under Extensions. A pending update, an extension update, a missing permission, or an agent whose hooks aren't wired yet shows as a row above every category. An app or extension update also puts a dot on the Settings tab.

| Key | Action |
Expand Down
11 changes: 11 additions & 0 deletions panel/Components.swift
Original file line number Diff line number Diff line change
Expand Up @@ -270,13 +270,24 @@ extension EnvironmentValues {
// and "Hide" otherwise.
struct PageFooter<Hints: View>: View {

// A quiet line on the left, such as Settings' version. Hints keep the
// right.
var leading: String? = nil
@ViewBuilder var hints: () -> Hints
@Environment(\.escapeCancels) private var escapeCancels

static func escapeLabel(cancels: Bool) -> String { cancels ? "Cancel" : "Hide" }

var body: some View {
HStack(spacing: 0) {
if let leading {
Text(leading)
.font(.caption2.monospacedDigit())
.foregroundStyle(.tertiary)
.lineLimit(1)
.fixedSize()
.padding(.trailing, 12)
}
ShedToFitLayout {
hints()
}
Expand Down
133 changes: 133 additions & 0 deletions panel/MCPClients.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import Foundation

// The MCP clients Settings → MCP → Set up for… can add stack-nudge to, and
// whether each already has it. A client's config is read, never written:
// setting one up copies what to run or paste, so stack-nudge never edits a
// file another app owns. Pure, for tests.
enum MCPClient: CaseIterable, Hashable {
case claudeCode, claudeDesktop, codex

var name: String {
switch self {
case .claudeCode: return "Claude Code"
case .claudeDesktop: return "Claude Desktop"
case .codex: return "Codex"
}
}

// The card's second line: what ⏎ copies.
var summary: String {
switch self {
case .claudeCode: return "Copies the claude mcp add command, for every project"
case .claudeDesktop: return "Copies the entry for mcpServers in its config file"
case .codex: return "Copies the codex mcp add command"
}
}

var symbol: String {
switch self {
case .claudeCode: return "terminal.fill"
case .claudeDesktop: return "macwindow"
case .codex: return "chevron.left.forwardslash.chevron.right"
}
}

// What to run or paste, pointing at `binary`, this app's own, so it's
// right wherever the app is installed. Claude Desktop doesn't expand ~, so
// its path is always written out in full.
func setup(binary: String) -> String {
let quoted = binary.contains(" ") ? "'\(binary)'" : binary
switch self {
case .claudeCode:
return "claude mcp add --scope user stack-nudge -- \(quoted) \(MCPBridge.flag)"
case .codex:
return "codex mcp add stack-nudge -- \(quoted) \(MCPBridge.flag)"
case .claudeDesktop:
return "\"stack-nudge\": {\"command\": \(Self.jsonString(binary)), \"args\": [\"\(MCPBridge.flag)\"]}"
}
}

// The files a client keeps its servers in. Claude Code and Codex can each
// run from more than one config dir; the extra ones are the logins the
// Usage tab already found (ClaudeConfigDirs, CodexHomes).
func configFiles(home: String, claudeDirs: [String], codexHomes: [String]) -> [String] {
switch self {
case .claudeCode:
return ["\(home)/.claude.json"] + claudeDirs.map { "\($0)/.claude.json" }
case .claudeDesktop:
return ["\(home)/Library/Application Support/Claude/claude_desktop_config.json"]
case .codex:
return ["\(home)/.codex/config.toml"] + codexHomes.map { "\($0)/config.toml" }
}
}

// The clients with stack-nudge in any of their config files.
static func configured(home: String = NSHomeDirectory(), claudeDirs: [String] = [], codexHomes: [String] = [],
read: (String) -> String? = { try? String(contentsOfFile: $0, encoding: .utf8) })
-> Set<MCPClient> {
Set(allCases.filter { client in
client.configFiles(home: home, claudeDirs: claudeDirs, codexHomes: codexHomes)
.contains { path in read(path).map(client.hasBridge) ?? false }
})
}

// Whether one config file's text has a server running stack-nudge's
// bridge, whatever it was named.
func hasBridge(in text: String) -> Bool {
switch self {
case .claudeCode, .claudeDesktop: return Self.jsonHasBridge(text)
case .codex: return Self.tomlHasBridge(text)
}
}

// A server is stack-nudge's when it runs the app's binary with --mcp.
static func isBridge(command: String?, args: [String]) -> Bool {
guard let command else { return false }
return (command as NSString).lastPathComponent == "stack-nudge" && args.contains(MCPBridge.flag)
}

// mcpServers at the top, as Desktop and Claude Code's user scope keep
// them, and under each project, as Claude Code's local scope does.
private static func jsonHasBridge(_ text: String) -> Bool {
guard let data = text.data(using: .utf8),
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
else { return false }
let projects = (root["projects"] as? [String: Any] ?? [:]).values.compactMap { $0 as? [String: Any] }
let servers = ([root] + projects).flatMap { ($0["mcpServers"] as? [String: Any] ?? [:]).values }
return servers.contains { server in
guard let server = server as? [String: Any] else { return false }
return isBridge(command: server["command"] as? String, args: server["args"] as? [String] ?? [])
}
}

// Codex's servers are `[mcp_servers.<name>]` tables. Read line by line
// rather than as TOML: only the table's command and args matter here.
private static func tomlHasBridge(_ text: String) -> Bool {
let tables = text.components(separatedBy: "\n").reduce(into: [[String]]()) { tables, raw in
let line = raw.trimmingCharacters(in: .whitespaces)
if line.hasPrefix("[") {
tables.append(line.hasPrefix("[mcp_servers.") ? [] : ["skip"])
} else if !tables.isEmpty {
tables[tables.count - 1].append(line)
}
}
return tables.filter { $0.first != "skip" }.contains { lines in
let command = lines.first { $0.hasPrefix("command") }.flatMap(quoted)
let args = lines.drop { !$0.hasPrefix("args") }.joined(separator: " ")
return isBridge(command: command, args: args.contains("\"\(MCPBridge.flag)\"") ? [MCPBridge.flag] : [])
}
}

// The first double-quoted string on a line.
private static func quoted(_ line: String) -> String? {
let parts = line.components(separatedBy: "\"")
return parts.count >= 3 ? parts[1] : nil
}

private static func jsonString(_ value: String) -> String {
guard let data = try? JSONSerialization.data(withJSONObject: [value], options: [.withoutEscapingSlashes]),
let array = String(data: data, encoding: .utf8)
else { return "\"\(value)\"" }
return String(array.dropFirst().dropLast())
}
}
2 changes: 2 additions & 0 deletions panel/Panel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1570,6 +1570,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate,
.removeDuplicates()
.sink { [weak self] category in
if case .extensionPage(let id) = category { self?.extensions.tabAppeared(id) }
// Counted on the MCP row, so read as the category opens.
if category == .mcp { self?.nav.refreshMCPClients() }
}
.store(in: &cancellables)
}
Expand Down
Loading
Loading