diff --git a/Tests/StackNudgePanelCoreTests/ExtensionMCPTests.swift b/Tests/StackNudgePanelCoreTests/ExtensionMCPTests.swift new file mode 100644 index 0000000..065cc7f --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/ExtensionMCPTests.swift @@ -0,0 +1,198 @@ +import XCTest + +@testable import StackNudgePanelCore + +// Extensions offering tools and event types to MCP clients: the manifest's +// mcp block, the line protocol, and the host routing calls and events. +final class ExtensionMCPManifestTests: XCTestCase { + + private func parse(_ mcp: String) -> Result { + ExtensionManifest.parse(Data(""" + {"id":"pylon","name":"Pylon","version":"1","schema":2,"mode":"service","capabilities":["mcp"],"mcp":\(mcp)} + """.utf8)) + } + + func testAValidBlockIsRead() throws { + let manifest = try parse(""" + {"tools":[{"name":"open_issues","description":"Issues waiting on a reply.", + "inputSchema":{"type":"object","properties":{"limit":{"type":"integer"}}}}], + "events":[{"name":"sla_breach","description":"An issue is about to breach its SLA.", + "filters":{"team":"Only this team."}, + "payloadSchema":{"type":"object","properties":{"issue":{"type":"string"}}}}]} + """).get() + XCTAssertEqual(manifest.mcp.tools.map(\.name), ["open_issues"]) + XCTAssertEqual(manifest.mcp.events.first?.filters, ["team": "Only this team."]) + XCTAssertTrue(manifest.capabilities.contains(.mcp)) + let tool = manifest.mcp.toolsJSON(owner: "pylon", name: "Pylon").first + XCTAssertEqual(tool?["name"] as? String, "pylon.open_issues") + XCTAssertEqual(manifest.mcp.eventTypes(owner: "pylon").first?.name, "pylon.sla_breach") + } + + func testNoBlockIsEmpty() throws { + let manifest = try ExtensionManifest.parse(Data(""" + {"id":"pylon","name":"Pylon","version":"1","schema":1} + """.utf8)).get() + XCTAssertTrue(manifest.mcp.isEmpty) + } + + func testABadBlockIsRefusedWithWhy() { + let cases = [ + #"[]"#, + #"{"tools":[{"name":"Open","description":"d"}]}"#, + #"{"tools":[{"name":"open","description":""}]}"#, + #"{"tools":[{"name":"open","description":"d","inputSchema":{"type":"string"}}]}"#, + #"{"tools":[{"name":"open","description":"d"},{"name":"open","description":"d"}]}"#, + #"{"events":[{"name":"x","description":"d","filters":{"team":3}}]}"#, + ] + for mcp in cases { + guard case .failure(.invalidMCP) = parse(mcp) else { return XCTFail("accepted \(mcp)") } + } + let many = (0...ExtensionMCP.maxEach).map { #"{"name":"t\#($0)","description":"d"}"# }.joined(separator: ",") + guard case .failure(.invalidMCP) = parse(#"{"tools":[\#(many)]}"#) else { return XCTFail("too many") } + } + + func testOfferingToMCPIsForServicesAndAbove() { + XCTAssertFalse(ExtensionTier.view.allows(.mcp)) + XCTAssertTrue(ExtensionTier.service.allows(.mcp)) + XCTAssertTrue(ExtensionTier.service.allows(.eventSettings)) + XCTAssertEqual(ExtensionCapability.event("settings"), .eventSettings) + } +} + +final class ExtensionMCPProtocolTests: XCTestCase { + + func testACallCarriesTheArgumentsAndTheCaller() throws { + let line = ServiceProtocol.encode(.mcpCall(id: 4, tool: "open_issues", arguments: Data(#"{"limit":5}"#.utf8), + caller: ["client": .string("Claude Code"), "pid": .int(42)])) + let object = try XCTUnwrap(try JSONSerialization.jsonObject(with: line) as? [String: Any]) + XCTAssertEqual(object["type"] as? String, "mcp.call") + XCTAssertEqual((object["arguments"] as? [String: Any])?["limit"] as? Int, 5) + XCTAssertEqual((object["caller"] as? [String: Any])?["pid"] as? Int, 42) + XCTAssertEqual(line.last, 0x0A) + } + + func testResultsAndEventsAreDecodedAndCheckedForShape() { + XCTAssertEqual(ServiceProtocol.decode(Data(#"{"type":"mcp.result","id":4,"result":"3 open"}"#.utf8)), + .message(.mcpResult(id: 4, result: Data(#""3 open""#.utf8), isError: false))) + if case .message(.mcpResult(_, _, let isError)) = ServiceProtocol.decode( + Data(#"{"type":"mcp.result","id":4,"result":{"n":3},"isError":true}"#.utf8)) { + XCTAssertTrue(isError) + } else { XCTFail("an object result") } + if case .invalid = ServiceProtocol.decode(Data(#"{"type":"mcp.result","id":4,"result":3}"#.utf8)) {} else { + XCTFail("a bare number isn't a result") + } + if case .message(.mcpEvent(let name, _, let eventID)) = ServiceProtocol.decode( + Data(#"{"type":"mcp.event","name":"sla_breach","data":{"issue":"P-1"},"eventId":"e-1"}"#.utf8)) { + XCTAssertEqual(name, "sla_breach") + XCTAssertEqual(eventID, "e-1") + } else { XCTFail("an event") } + if case .invalid = ServiceProtocol.decode(Data(#"{"type":"mcp.event","name":"Bad Name","data":{}}"#.utf8)) {} else { + XCTFail("a bad name") + } + if case .invalid = ServiceProtocol.decode(Data(#"{"type":"mcp.event","name":"x","data":"no"}"#.utf8)) {} else { + XCTFail("data must be an object") + } + } +} + +@MainActor +final class ExtensionHostMCPTests: XCTestCase { + + private var spawner = FakeSpawner() + private var clock = FakeScheduler() + private var tiers: [String: ExtensionTier] = ["pylon": .service] + + private func manifest(capabilities: [String] = ["mcp"]) -> ExtensionManifest { + let list = capabilities.map { "\"\($0)\"" }.joined(separator: ",") + guard case .success(let m) = ExtensionManifest.parse(Data(""" + {"id":"pylon","name":"Pylon","version":"1","schema":2,"mode":"service","capabilities":[\(list)], + "mcp":{"tools":[{"name":"open_issues","description":"Open issues."}], + "events":[{"name":"sla_breach","description":"SLA about to breach."}]}} + """.utf8)) else { fatalError("fixture manifest didn't parse") } + return m + } + + private func host() -> ExtensionHost { + ExtensionHost(background: { $0() }, toMain: { $0() }, + runner: { _, _, _ in .transient("stub") }, + tiers: { [unowned self] in self.tiers }, + makeSupervisor: { [unowned self] manifest, granted, onEvent in + ServiceSupervisor.fake(id: manifest.id, granted: granted, + spawner: self.spawner, scheduler: self.clock, onEvent: onEvent) + }, + writeLog: { _ in }) + } + + func testToolsAreOfferedOnlyWhileTheServiceRuns() { + let host = host() + var changes = 0 + host.onMCPChanged = { changes += 1 } + host.load(.init(installed: [manifest()])) + XCTAssertTrue(host.mcpContributions.isEmpty, "not running yet") + spawner.last.ready() + XCTAssertEqual(host.mcpContributions.map(\.id), ["pylon"]) + XCTAssertGreaterThan(changes, 0) + } + + func testWithoutTheCapabilityNothingIsOffered() { + let host = host() + host.load(.init(installed: [manifest(capabilities: [])])) + spawner.last.ready() + XCTAssertTrue(host.mcpContributions.isEmpty) + } + + // The call reaches the extension with the caller as stack-nudge saw it, + // and its answer comes back as the tool result. + func testACallIsRoutedAndAnswered() { + let host = host() + host.load(.init(installed: [manifest()])) + spawner.last.ready() + var result: [String: Any]? + host.callMCPTool("pylon.open_issues", arguments: ["limit": 5], + caller: ["client": .string("Claude Code")]) { result = $0 } + let call = spawner.last.messages.last { $0["type"] as? String == "mcp.call" } + XCTAssertEqual(call?["tool"] as? String, "open_issues") + XCTAssertEqual((call?["caller"] as? [String: Any])?["client"] as? String, "Claude Code") + let id = call?["id"] as? Int ?? -1 + spawner.last.say(#"{"type":"mcp.result","id":\#(id),"result":"3 open"}"#) + XCTAssertEqual(((result?["content"] as? [[String: Any]])?.first)?["text"] as? String, "3 open") + XCTAssertEqual(result?["isError"] as? Bool, false) + } + + func testAnUnknownToolIsNoneOfTheHostsBusiness() { + let host = host() + host.load(.init(installed: [manifest()])) + spawner.last.ready() + var answered = false + var result: [String: Any]? = ["unset": true] + host.callMCPTool("pylon.nope", arguments: [:], caller: [:]) { result = $0; answered = true } + XCTAssertTrue(answered) + XCTAssertNil(result) + } + + func testOnlyDeclaredEventsArePassedOn() { + let host = host() + var emitted: [String] = [] + host.onMCPEvent = { name, _, _ in emitted.append(name) } + host.load(.init(installed: [manifest()])) + spawner.last.ready() + spawner.last.say(#"{"type":"mcp.event","name":"sla_breach","data":{"issue":"P-1"}}"#) + spawner.last.say(#"{"type":"mcp.event","name":"undeclared","data":{}}"#) + XCTAssertEqual(emitted, ["pylon.sla_breach"]) + } + + // Settings changes reach only the extensions granted event:settings. + func testASettingsChangeReachesOnlyThoseGrantedIt() { + let host = host() + host.load(.init(installed: [manifest(capabilities: ["mcp", "event:settings"])])) + spawner.last.ready() + host.broadcast(event: "settings", fields: ["key": .string("STACKNUDGE_VOICE"), "value": .string("Off")]) + XCTAssertEqual(spawner.last.messages.last?["name"] as? String, "settings") + + let other = self.host() + other.load(.init(installed: [manifest()])) + spawner.last.ready() + other.broadcast(event: "settings", fields: ["key": .string("STACKNUDGE_VOICE")]) + XCTAssertNotEqual(spawner.last.messages.last?["name"] as? String, "settings") + } +} diff --git a/Tests/StackNudgePanelCoreTests/ExtensionManifestTests.swift b/Tests/StackNudgePanelCoreTests/ExtensionManifestTests.swift index 1da1afe..ccbe37a 100644 --- a/Tests/StackNudgePanelCoreTests/ExtensionManifestTests.swift +++ b/Tests/StackNudgePanelCoreTests/ExtensionManifestTests.swift @@ -397,7 +397,7 @@ final class ExtensionManifestTests: XCTestCase { // Every capability the host knows, by the name a manifest uses for it. func testEveryKnownCapabilityIsAccepted() { let names = ["bluetooth", "signal:presence", "event:idle", "event:panel", - "event:session", "event:nudge", "feed"] + "event:session", "event:nudge", "feed", "mcp", "event:settings"] let list = names.map { "\"\($0)\"" }.joined(separator: ",") guard case .success(let m) = service(#","mode":"service","capabilities":["# + list + "]") else { return XCTFail("known capabilities refused") } diff --git a/Tests/StackNudgePanelCoreTests/ExtensionTierTests.swift b/Tests/StackNudgePanelCoreTests/ExtensionTierTests.swift index 77e09af..bfab97a 100644 --- a/Tests/StackNudgePanelCoreTests/ExtensionTierTests.swift +++ b/Tests/StackNudgePanelCoreTests/ExtensionTierTests.swift @@ -29,7 +29,7 @@ final class ExtensionTierTests: XCTestCase { let manifest = service(everything) XCTAssertEqual(ExtensionTier.grants(for: manifest, tier: .view), []) XCTAssertEqual(ExtensionTier.grants(for: manifest, tier: .service), - [.eventIdle, .eventPanel, .feed]) + [.eventIdle, .eventPanel, .feed, .mcp, .eventSettings]) XCTAssertEqual(ExtensionTier.grants(for: manifest, tier: .trusted), ExtensionCapability.allCases) } diff --git a/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift b/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift index 4f4ce1b..b99aa29 100644 --- a/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift +++ b/Tests/StackNudgePanelCoreTests/MCPEventsTests.swift @@ -72,10 +72,10 @@ final class MCPEventHubTests: XCTestCase { func testAnExtensionsTypesComeAndGo() { let hub = hub() let type = MCPEventHub.EventType(name: "pylon.sla", description: "d", filters: [:], payloadSchema: [:]) - XCTAssertTrue(hub.setExtensionTypes([type], for: "pylon")) - XCTAssertFalse(hub.setExtensionTypes([type], for: "pylon"), "the same list again is no change") + XCTAssertTrue(hub.replaceExtensionTypes(["pylon": [type]])) + XCTAssertFalse(hub.replaceExtensionTypes(["pylon": [type]]), "the same list again is no change") XCTAssertEqual(hub.type(named: "pylon.sla")?.owner, "pylon") - XCTAssertTrue(hub.setExtensionTypes([], for: "pylon")) + XCTAssertTrue(hub.replaceExtensionTypes([:]), "an extension that stops offering any drops out") XCTAssertNil(hub.type(named: "pylon.sla")) } } diff --git a/Tests/StackNudgePanelCoreTests/MCPServerTests.swift b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift index da2ecd5..6acb24a 100644 --- a/Tests/StackNudgePanelCoreTests/MCPServerTests.swift +++ b/Tests/StackNudgePanelCoreTests/MCPServerTests.swift @@ -29,6 +29,16 @@ final class MCPSessionTests: XCTestCase { } func raiseNudge(_ request: MCPNudge.Request, caller: MCPCaller) { nudges.append((request, caller)) } func mute(minutes: Int, caller: MCPCaller) -> String { mutes.append(minutes); return "ok" } + var extensionToolList: [[String: Any]] = [] + func extensionTools() -> [[String: Any]] { extensionToolList } + // Answered at once unless held, when the test answers it. + var holdExtensionCalls = false + var heldCalls: [([String: Any]?) -> Void] = [] + func callExtensionTool(_ name: String, arguments: [String: Any], caller: MCPCaller, + complete: @escaping ([String: Any]?) -> Void) { + guard !holdExtensionCalls else { return heldCalls.append(complete) } + complete(name == "pylon.open_issues" ? MCPProtocol.toolResult("3 open") : nil) + } } private var sent: [[String: Any]] = [] @@ -173,6 +183,38 @@ final class MCPSessionTests: XCTestCase { XCTAssertEqual(context.nudges.count, 1) } + func testAnExtensionsToolIsListedAfterTheAppsAndCalled() { + let session = session() + context.extensionToolList = [["name": "pylon.open_issues"]] + session.receive(request(5, "tools/list")) + let names = (lastResult?["tools"] as? [[String: Any]])?.compactMap { $0["name"] as? String } + XCTAssertEqual(names?.last, "pylon.open_issues") + XCTAssertEqual((call(session, "pylon.open_issues")?["content"] as? [[String: Any]])?.first?["text"] as? String, + "3 open") + session.receive(request(6, "tools/call", ["name": "pylon.nope"])) + XCTAssertEqual(lastError?["code"] as? Int, MCPProtocol.invalidParams) + } + + func testAWaitingExtensionCallHoldsUpNothingElse() { + let session = session() + context.holdExtensionCalls = true + session.receive(request(7, "tools/call", ["name": "pylon.open_issues"])) + session.receive(request(8, "ping")) + XCTAssertTrue(MCPProtocol.sameID(sent.last?["id"], 8)) + context.heldCalls.removeFirst()(MCPProtocol.toolResult("3 open")) + XCTAssertTrue(MCPProtocol.sameID(sent.last?["id"], 7)) + } + + func testACancelledExtensionCallIsNeverAnswered() { + let session = session() + context.holdExtensionCalls = true + session.receive(request(7, "tools/call", ["name": "pylon.open_issues"])) + session.receive(["jsonrpc": "2.0", "method": "notifications/cancelled", "params": ["requestId": 7]]) + let before = sent.count + context.heldCalls.removeFirst()(MCPProtocol.toolResult("3 open")) + XCTAssertEqual(sent.count, before) + } + func testMuteIsBoundedToADay() { let session = session() XCTAssertEqual(call(session, "mute", ["minutes": 30])?["isError"] as? Bool, false) diff --git a/docs/design/local-mcp.md b/docs/design/local-mcp.md index afdb586..038f7c7 100644 --- a/docs/design/local-mcp.md +++ b/docs/design/local-mcp.md @@ -1,10 +1,10 @@ # A local MCP server -Status: phases 1 to 3 are built: the bridge, the server on its own socket, the +Status: phases 1 to 4 are built: the bridge, the server on its own socket, the settings registry, every tool below, the resources with their update -notifications, the write switch, the audit lines, and the app's events over -push and poll. Extension contributions (phase 4) are marked *not yet -delivered*. Each phase is its own PR, and this doc is updated as they land, the +notifications, the write switch, the audit lines, the app's events over push +and poll, and extensions' tools and events (docs/extensions.md, "Tools and +events for AI agents"). The relay (phase 5) is not. Each phase is its own PR, and this doc is updated as they land, the way [service-extensions.md](service-extensions.md) was. ## Why @@ -220,12 +220,18 @@ the registry, so the panel and MCP can't drift apart. 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 +block declaring the tools and event types it offers, each named under its ID +(`pylon.sla_breach`), and checked at install like the rest of the manifest. The +NDJSON protocol gains `mcp.call` and `mcp.result` for tool calls and `mcp.event` +to emit an occurrence. The host passes on only an event type the extension +declared, with an object for its data, and only a result for a call it made; +a call unanswered in 30 seconds fails. A call waits without holding up the +client's other requests, and one the client cancels is never answered. It +doesn't validate arguments or +payloads against the declared JSON Schemas: clients see the schemas and are +expected to keep to them, and extensions to their own. Resources from +extensions aren't offered (yet). The tools and event types come and go with +the service, and each change 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. diff --git a/docs/design/service-extensions.md b/docs/design/service-extensions.md index 5506bd8..f3bd257 100644 --- a/docs/design/service-extensions.md +++ b/docs/design/service-extensions.md @@ -216,6 +216,7 @@ doesn't send them yet (*not yet delivered*). | `panel` | `open` | refresh what's on screen when it matters | | `session` | one session's whole state whenever it starts, changes or ends (below) | token counting, insights, the direct exchange's roster | | `nudge` | an agent nudge as delivered, without FIFO paths or PIDs | voice, Slack-style relays | +| `settings` | a setting changed: key, value, and who changed it (an MCP client, or `stack-nudge`) | extensions that follow the user's settings. Delivered | `session` is sent for each session that's new or changed, and once as `ended` when it goes. A service that has just started gets every current session first, diff --git a/docs/extensions.md b/docs/extensions.md index 0e673db..f0c2a50 100644 --- a/docs/extensions.md +++ b/docs/extensions.md @@ -604,6 +604,58 @@ Any tier may use it, since it grants nothing. It's a manifest field, so older hosts ignore it and show a tab, which still works. An unknown surface, or an empty list, is refused. +## Tools and events for AI agents + +A service extension can offer tools and event types to MCP clients (Claude +Code, Codex, Claude Desktop) through stack-nudge's own MCP server +([design](design/local-mcp.md)). It asks for the `mcp` capability, which needs +the `service` tier, and declares what it offers in the manifest: + +```json +"capabilities": ["mcp"], +"mcp": { + "tools": [{"name": "open_issues", "description": "Issues waiting on a reply.", + "inputSchema": {"type": "object", "properties": {"limit": {"type": "integer"}}}}], + "events": [{"name": "sla_breach", "description": "An issue is about to breach its SLA.", + "filters": {"team": "Only issues for this team."}, + "payloadSchema": {"type": "object", "properties": {"issue": {"type": "string"}}}}] +} +``` + +Names are lowercase letters, digits and `_`, at most 16 of each, and clients +see them under the extension's id: `pylon.open_issues`, `pylon.sla_breach`. +They're offered only while the service is running, and clients are told when +they come and go. + +A call arrives on stdin, with the caller as stack-nudge saw it. `sessionId` and +`pid` are present only when they name a session stack-nudge can see running, +never because a model said so: + +```json +{"type": "mcp.call", "id": 7, "tool": "open_issues", "arguments": {"limit": 5}, + "caller": {"client": "Claude Code", "sessionId": "...", "pid": 4242}} +``` + +Answer with the same `id` within 30 seconds, with a string or an object, and +`isError` when it failed: + +```json +{"type": "mcp.result", "id": 7, "result": {"open": 3}} +``` + +An occurrence of a declared event type is one line; `eventId` is optional and +should be the upstream's own id when there is one. Its `data` is shown to a +model as it is, so keep it to what identifies the thing: an id, a title, a +link. + +```json +{"type": "mcp.event", "name": "sla_breach", "data": {"issue": "P-123"}, "eventId": "pylon-p123-sla"} +``` + +`event:settings` (also `service` tier) delivers +`{"type": "event", "name": "settings", "key": "...", "value": "...", "by": "..."}` +whenever a setting changes, from Settings or an MCP client. + ## Away, the reference service extension `extensions/away` in StackOneHQ/stack-nudge-extensions-marketplace notices when you walk away from the Mac with your phone, and diff --git a/panel/ExtensionHost.swift b/panel/ExtensionHost.swift index 08f846e..8294b9b 100644 --- a/panel/ExtensionHost.swift +++ b/panel/ExtensionHost.swift @@ -150,6 +150,13 @@ final class ExtensionHost: ObservableObject { // started since its last document still shows the dead process's, which // its keys must not be resolved against. private var freshDocument: Set = [] + // MCP tool calls handed to an extension and not yet answered, by call id. + private var mcpCalls: [Int: (id: String, complete: ([String: Any]) -> Void)] = [:] + private var nextMCPCall = 0 + // Told when an extension's MCP tools or event types come or go, and when + // one emits an event (the app passes both to the MCP server). + var onMCPChanged: (() -> Void)? + var onMCPEvent: ((String, [String: Any], String?) -> Void)? private var extensionLog = ExtensionLog() private let writeLog: (String) -> Void private let now: () -> TimeInterval @@ -639,6 +646,10 @@ final class ExtensionHost: ObservableObject { private func stopService(_ id: String) { guard let service = running.removeValue(forKey: id) else { return } onFeedActionsLapsed(id) + if !service.manifest.mcp.isEmpty { + failMCPCalls(for: id, "the extension stopped") + onMCPChanged?() + } // Released now rather than when the process is finally gone: the // extension is no longer one the app listens to, so whatever it last // said must not keep acting. @@ -710,6 +721,16 @@ final class ExtensionHost: ObservableObject { onFeed(id, manifest.name, post) case .retract(let key): onRetract(id, key) + case .mcpResult(let callID, let result, let isError): + completeMCPCall(callID, from: id, result: result, isError: isError) + case .mcpEvent(let name, let data, let eventID): + // Only a type it declared: the server lists those, and a client + // subscribed to the list's contract. + guard running[id]?.manifest.mcp.events.contains(where: { $0.name == name }) == true else { + return log(id, "sent mcp.event \(name), which it didn't declare") + } + guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return } + onMCPEvent?(ExtensionMCP.toolName(id, name), object, eventID) case .degraded(let why): log(id, "degraded \u{2014} \(why)") case .problem(let why): @@ -718,6 +739,11 @@ final class ExtensionHost: ObservableObject { } private func serviceStateChanged(_ id: String, _ state: ServiceSupervisor.State) { + // Its tools and events are offered only while it runs. + if running[id]?.manifest.mcp.isEmpty == false { + if state != .running { failMCPCalls(for: id, "the extension stopped") } + onMCPChanged?() + } var pane = self.pane(id) switch state { case .starting: @@ -758,9 +784,7 @@ final class ExtensionHost: ObservableObject { let changes = SessionSnapshot.changes(from: sessionSnapshots, to: snapshots) sessionSnapshots = snapshots guard !changes.isEmpty else { return } - for service in running.values { - for change in changes { service.supervisor.send(event: "session", fields: change.fields) } - } + for change in changes { broadcast(event: "session", fields: change.fields) } } // Whether ⏎ on one of this extension's feed events can reach it now. When @@ -777,6 +801,73 @@ final class ExtensionHost: ObservableObject { return true } + // MARK: - MCP + + // The extensions offering MCP tools and events right now: running, and + // granted mcp. In id order, so the server's tool list is stable. + var mcpContributions: [(id: String, name: String, mcp: ExtensionMCP)] { + running.values + .filter { $0.granted.contains(.mcp) && !$0.manifest.mcp.isEmpty && services[$0.manifest.id] == .running } + .map { ($0.manifest.id, $0.manifest.name, $0.manifest.mcp) } + .sorted { $0.0 < $1.0 } + } + + static let mcpCallTimeout: TimeInterval = 30 + + // Routes an MCP client's call to `.` to that extension. Main + // thread. Completes with the tool result, or nil when no running extension + // offers that tool. + func callMCPTool(_ name: String, arguments: [String: Any], caller: [String: ServiceProtocol.Value], + timeout: TimeInterval = ExtensionHost.mcpCallTimeout, + complete: @escaping ([String: Any]?) -> Void) { + let parts = name.split(separator: ".", maxSplits: 1).map(String.init) + guard parts.count == 2, + let contribution = mcpContributions.first(where: { $0.id == parts[0] }), + contribution.mcp.tools.contains(where: { $0.name == parts[1] }), + let service = running[parts[0]], + let data = try? JSONSerialization.data(withJSONObject: arguments) + else { return complete(nil) } + nextMCPCall += 1 + let callID = nextMCPCall + mcpCalls[callID] = (parts[0], { complete($0) }) + service.supervisor.callMCP(id: callID, tool: parts[1], arguments: data, caller: caller) { [weak self] accepted in + guard !accepted else { return } + self?.toMain { self?.finishMCPCall(callID, MCPProtocol.toolError("\(contribution.name) isn't running.")) } + } + toMain { [weak self] in + DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { + self?.finishMCPCall(callID, MCPProtocol.toolError("\(contribution.name) didn't answer in time.")) + } + } + } + + // The extension's answer, as a tool result. Its text and data are its + // own: the client is told which extension they came from by the tool's + // name and description. + private func completeMCPCall(_ callID: Int, from id: String, result: Data, isError: Bool) { + guard mcpCalls[callID]?.id == id else { + return log(id, "answered an mcp.call it wasn't asked (\(callID))") + } + let value = (try? JSONSerialization.jsonObject(with: result, options: .fragmentsAllowed)) ?? "" + finishMCPCall(callID, MCPProtocol.toolResult(value, isError: isError)) + } + + private func finishMCPCall(_ callID: Int, _ result: [String: Any]) { + guard let call = mcpCalls.removeValue(forKey: callID) else { return } + call.complete(result) + } + + private func failMCPCalls(for id: String, _ why: String) { + for (callID, call) in mcpCalls where call.id == id { + finishMCPCall(callID, MCPProtocol.toolError("The call failed: \(why).")) + } + } + + // An app event to every running service granted it. + func broadcast(event name: String, fields: [String: ServiceProtocol.Value]) { + running.values.forEach { $0.supervisor.send(event: name, fields: fields) } + } + // What a service was given, for its page's "Allowed" line. Empty for a // view extension, which nothing passes through. func granted(_ id: String) -> [ExtensionCapability] { running[id]?.granted ?? [] } diff --git a/panel/ExtensionMCP.swift b/panel/ExtensionMCP.swift new file mode 100644 index 0000000..7900148 --- /dev/null +++ b/panel/ExtensionMCP.swift @@ -0,0 +1,126 @@ +import Foundation + +// What a service extension offers MCP clients through stack-nudge's server: +// tools a client can call, routed to the extension as `mcp.call`, and event +// types it emits as `mcp.event`. Declared in the manifest's `mcp` block, +// checked at install like the rest of the manifest, and offered only while the +// extension holds the `mcp` capability. Names are namespaced by the +// extension's id, so `pylon` declaring `sla_breach` offers `pylon.sla_breach` +// (docs/design/local-mcp.md, "Extensions"). +struct ExtensionMCP: Equatable { + + struct Tool: Equatable { + let name: String + let description: String + // A JSON Schema object, kept as its JSON so the manifest stays + // Equatable. + let inputSchema: Data + } + + struct Event: Equatable { + let name: String + let description: String + // Subscription arguments: each narrows to occurrences whose data has + // that string field equal to the argument. + let filters: [String: String] + let payloadSchema: Data + } + + var tools: [Tool] = [] + var events: [Event] = [] + + var isEmpty: Bool { tools.isEmpty && events.isEmpty } + + static let maxEach = 16 + static let maxDescription = 500 + + // A name inside the extension's namespace: lowercase, a letter first. + static func isValidName(_ name: String) -> Bool { + guard let first = name.first, first.isASCII, first.isLowercase, name.count <= 40 else { return false } + return name.allSatisfy { $0.isASCII && ($0.isLowercase || $0.isNumber || $0 == "_") } + } + + // The manifest's `mcp` value, or why it isn't one. Absent is empty. + static func parse(_ raw: Any?) -> Result { + guard let raw else { return .success(ExtensionMCP()) } + guard let object = raw as? [String: Any] else { return .failure(.invalidMCP("mcp must be an object")) } + var parsed = ExtensionMCP() + let tools = object["tools"] as? [[String: Any]] ?? [] + let events = object["events"] as? [[String: Any]] ?? [] + guard tools.count <= maxEach, events.count <= maxEach else { + return .failure(.invalidMCP("at most \(maxEach) tools and \(maxEach) events")) + } + for entry in tools { + guard let name = entry["name"] as? String, isValidName(name) else { + return .failure(.invalidMCP("a tool name must be lowercase letters, digits and _, starting with a letter")) + } + guard let description = describe(entry["description"]) else { + return .failure(.invalidMCP("tool \(name) needs a description of up to \(maxDescription) characters")) + } + guard let schema = objectSchema(entry["inputSchema"] ?? ["type": "object"]) else { + return .failure(.invalidMCP("tool \(name)'s inputSchema must be an object schema")) + } + guard !parsed.tools.contains(where: { $0.name == name }) else { + return .failure(.invalidMCP("tool \(name) is declared twice")) + } + parsed.tools.append(Tool(name: name, description: description, inputSchema: schema)) + } + for entry in events { + guard let name = entry["name"] as? String, isValidName(name) else { + return .failure(.invalidMCP("an event name must be lowercase letters, digits and _, starting with a letter")) + } + guard let description = describe(entry["description"]) else { + return .failure(.invalidMCP("event \(name) needs a description of up to \(maxDescription) characters")) + } + guard let schema = objectSchema(entry["payloadSchema"] ?? ["type": "object"]) else { + return .failure(.invalidMCP("event \(name)'s payloadSchema must be an object schema")) + } + let filters = entry["filters"] as? [String: String] ?? [:] + guard (entry["filters"] == nil || entry["filters"] is [String: String]), + filters.keys.allSatisfy(isValidName) + else { return .failure(.invalidMCP("event \(name)'s filters map argument names to descriptions")) } + guard !parsed.events.contains(where: { $0.name == name }) else { + return .failure(.invalidMCP("event \(name) is declared twice")) + } + parsed.events.append(Event(name: name, description: description, filters: filters, payloadSchema: schema)) + } + return .success(parsed) + } + + private static func describe(_ raw: Any?) -> String? { + guard let text = (raw as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), + !text.isEmpty, text.count <= maxDescription else { return nil } + return text + } + + private static func objectSchema(_ raw: Any) -> Data? { + guard let schema = raw as? [String: Any], (schema["type"] as? String) == "object", + JSONSerialization.isValidJSONObject(schema) + else { return nil } + return try? JSONSerialization.data(withJSONObject: schema, options: [.sortedKeys]) + } + + // MARK: - As the server offers them + + static func toolName(_ id: String, _ tool: String) -> String { "\(id).\(tool)" } + + func toolsJSON(owner id: String, name: String) -> [[String: Any]] { + tools.map { tool in + ["name": Self.toolName(id, tool.name), + "title": "\(name): \(tool.name)", + "description": "From the \(name) extension. \(tool.description)", + "inputSchema": (try? JSONSerialization.jsonObject(with: tool.inputSchema)) ?? ["type": "object"], + "_meta": ["stack-nudge/extension": id]] + } + } + + func eventTypes(owner id: String) -> [MCPEventHub.EventType] { + events.map { event in + MCPEventHub.EventType(name: Self.toolName(id, event.name), + description: event.description, filters: event.filters, + payloadSchema: ((try? JSONSerialization.jsonObject(with: event.payloadSchema)) + as? [String: Any]) ?? ["type": "object"], + owner: id) + } + } +} diff --git a/panel/ExtensionManifest.swift b/panel/ExtensionManifest.swift index 1a8aad2..ce11c7a 100644 --- a/panel/ExtensionManifest.swift +++ b/panel/ExtensionManifest.swift @@ -101,6 +101,9 @@ struct ExtensionManifest: Equatable { // install starts with a crash. Asked for in the manifest, so the rest // keep the short one that catches a hang quickly. var handshakeSeconds: TimeInterval = ExtensionManifest.defaultHandshakeSeconds + // Tools and event types offered to MCP clients; empty without an `mcp` + // block. Last and defaulted, like the rest. + var mcp = ExtensionMCP() var tabEntry: ExtensionTab { ExtensionTab(id: id, label: tab.label) } var hasTab: Bool { surfaces.contains(.tab) } @@ -222,6 +225,7 @@ struct ExtensionManifest: Equatable { case invalidConfigType(key: String, why: String) case unknownSurface(String) case noSurfaces + case invalidMCP(String) var message: String { switch self { @@ -241,6 +245,8 @@ struct ExtensionManifest: Equatable { return "config key \"\(key)\" \(why)" case .unknownSurface(let name): return "unknown surface \"\(name)\"" + case .invalidMCP(let why): + return "mcp: \(why)" case .noSurfaces: return "surfaces is empty; it needs \"tab\", \"settings\" or both" } @@ -310,6 +316,14 @@ struct ExtensionManifest: Equatable { } if !capabilities.contains(capability) { capabilities.append(capability) } } + // The `mcp` block holds JSON Schemas, which Codable can't carry, so it + // is read from the same bytes as plain JSON. + let rawMCP = (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["mcp"] + let mcp: ExtensionMCP + switch ExtensionMCP.parse(rawMCP) { + case .success(let parsed): mcp = parsed + case .failure(let failure): return .failure(failure) + } return .success(ExtensionManifest( id: decoded.id, @@ -334,7 +348,8 @@ struct ExtensionManifest: Equatable { // Clamped rather than refused, like the poll interval: never // shorter than the default, never long enough to hide a hang. handshakeSeconds: min(max(decoded.handshakeSeconds ?? defaultHandshakeSeconds, - defaultHandshakeSeconds), maximumHandshakeSeconds))) + defaultHandshakeSeconds), maximumHandshakeSeconds), + mcp: mcp)) } // The decoder's own description names the field, which is the one thing a @@ -589,6 +604,11 @@ enum ExtensionCapability: String, CaseIterable, Equatable { case eventSession = "event:session" case eventNudge = "event:nudge" case feed + // Offer tools and event types to MCP clients through stack-nudge's server, + // as the manifest's `mcp` block declares (ExtensionMCP). + case mcp + // Hear when a setting changes, from Settings or an MCP client. + case eventSettings = "event:settings" // The capability that gates an `event` or `signal` message by its name, so // the supervisor can check one without a table of its own. diff --git a/panel/ExtensionTier.swift b/panel/ExtensionTier.swift index 92d9809..c5aa640 100644 --- a/panel/ExtensionTier.swift +++ b/panel/ExtensionTier.swift @@ -24,7 +24,7 @@ enum ExtensionTier: String, Comparable, CaseIterable { // until somebody decides which tier it belongs to. func allows(_ capability: ExtensionCapability) -> Bool { switch capability { - case .eventIdle, .eventPanel, .feed: + case .eventIdle, .eventPanel, .feed, .mcp, .eventSettings: return self >= .service case .signalPresence, .eventSession, .eventNudge, .bluetooth: return self >= .trusted diff --git a/panel/MCPAppContext.swift b/panel/MCPAppContext.swift index 385b4fe..65582a6 100644 --- a/panel/MCPAppContext.swift +++ b/panel/MCPAppContext.swift @@ -14,6 +14,8 @@ final class MCPAppContext: MCPContext { private let resume: () -> Void // Set once the server exists: writes credit their client through it. weak var server: MCPServer? + // The extension host, for the tools running extensions offer. + weak var extensions: ExtensionHost? init(nav: PanelNav, store: EventStore, sessions: SessionStore, muteFor: @escaping (Int, Bool) -> Void, resume: @escaping () -> Void) { @@ -74,6 +76,37 @@ final class MCPAppContext: MCPContext { } } + func extensionTools() -> [[String: Any]] { + onMain { + (extensions?.mcpContributions ?? []).flatMap { $0.mcp.toolsJSON(owner: $0.id, name: $0.name) } + } + } + + // Answers on main, whenever the extension does: the host times a call out + // itself, so `complete` always runs. + func callExtensionTool(_ name: String, arguments: [String: Any], caller: MCPCaller, + complete: @escaping ([String: Any]?) -> Void) { + guard name.contains(".") else { return complete(nil) } + DispatchQueue.main.async { [weak self] in + guard let self, let host = self.extensions else { return complete(nil) } + let fields = MCPAppContext.callerFields(caller, live: self.sessionStore?.sessions ?? []) + host.callMCPTool(name, arguments: arguments, caller: fields, complete: complete) + } + } + + // The caller as an extension hears it in mcp.call: as the bridge saw it, + // and only as far as stack-nudge can vouch for it. The session id and pid + // are passed only when they name a session it sees running, so an + // extension never acts on a session it can't find. + static func callerFields(_ caller: MCPCaller, live sessions: [Session]) -> [String: ServiceProtocol.Value] { + var fields: [String: ServiceProtocol.Value] = ["client": .string(caller.displayName)] + if let session = MCPNudge.session(for: caller, in: sessions) { + fields["pid"] = .int(session.pid) + if let id = session.claudeSessionID { fields["sessionId"] = .string(id) } + } + return fields + } + private func onMain(_ work: () -> T) -> T { Thread.isMainThread ? work() : DispatchQueue.main.sync(execute: work) } @@ -113,6 +146,9 @@ final class MCPChangeWatcher { private var lastSessions: [SessionSnapshot] = [] private var cancellables = Set() + // A setting changed: also told to extensions granted event:settings. + var onSettingChanged: ((_ key: String, _ value: String, _ by: String) -> Void)? + init(server: MCPServer, nav: PanelNav, store: EventStore, sessions: SessionStore) { self.server = server self.nav = nav @@ -138,6 +174,7 @@ final class MCPChangeWatcher { "by": server.attribution.take(setting.key) ?? "stack-nudge"] if let previous = lastSettings[setting.key] { data["previous"] = SettingsRegistry.describe(previous) } server.emit("settings.changed", data: data) + onSettingChanged?(setting.key, SettingsRegistry.describe(setting.value), data["by"] as? String ?? "stack-nudge") } lastSettings = Self.values(snapshot) var uris = MCPSession.settingsURIs(changed: changed) diff --git a/panel/MCPEvents.swift b/panel/MCPEvents.swift index c7cb836..67473a5 100644 --- a/panel/MCPEvents.swift +++ b/panel/MCPEvents.swift @@ -94,16 +94,18 @@ final class MCPEventHub { types.first { $0.name == name } } - // An extension's event types replace whatever it offered before. Returns - // whether the list changed, so the server can say so. + // Every extension's event types at once, replacing what was there: an + // extension that no longer offers any drops out. Returns whether the list + // changed, so the server can say so. @discardableResult - func setExtensionTypes(_ types: [EventType], for owner: String) -> Bool { + func replaceExtensionTypes(_ byOwner: [String: [EventType]]) -> Bool { lock.lock() defer { lock.unlock() } - let before = extensionTypes.filter { $0.owner == owner }.map(\.name) - extensionTypes.removeAll { $0.owner == owner } - extensionTypes += types.map { var type = $0; type.owner = owner; return type } - return before != types.map(\.name) + let before = extensionTypes.map(\.name) + extensionTypes = byOwner.keys.sorted().flatMap { owner in + (byOwner[owner] ?? []).map { var type = $0; type.owner = owner; return type } + } + return before != extensionTypes.map(\.name) } private static let sessionFilters = ["agent": "Only this agent: claude, codex, gemini, agy or pi.", diff --git a/panel/MCPSession.swift b/panel/MCPSession.swift index aefaf09..19ab577 100644 --- a/panel/MCPSession.swift +++ b/panel/MCPSession.swift @@ -13,6 +13,12 @@ protocol MCPContext: AnyObject { // Mutes for `minutes` (0 resumes), sparing permission prompts. Says what // it did. func mute(minutes: Int, caller: MCPCaller) -> String + // Tools running extensions offer, already namespaced (ExtensionMCP). + func extensionTools() -> [[String: Any]] + // Calls one. `complete` runs once, on any thread, with the extension's + // answer, or a timeout's, or nil when no running extension offers `name`. + func callExtensionTool(_ name: String, arguments: [String: Any], caller: MCPCaller, + complete: @escaping ([String: Any]?) -> Void) } // One client's conversation with the server, from the bridge's hello to the @@ -20,8 +26,8 @@ protocol MCPContext: AnyObject { // _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. +// Thread-safe: requests arrive on the connection's reader, change +// notifications from the app's observer, and extensions' answers from main. final class MCPSession { static let settingsURI = "stacknudge://settings" @@ -55,6 +61,11 @@ final class MCPSession { // events/stream subscriptions, one per request. private var streams: [EventStream] = [] + // Extension tool calls still waiting on their extension, by request id. + // One cancelled, or whose connection closed, is dropped from here and its + // answer goes nowhere. + private var pendingCalls: [Any] = [] + private final class EventStream { let id: Any let name: String @@ -87,6 +98,7 @@ final class MCPSession { let open = streams streams.removeAll() listeners.removeAll() + pendingCalls.removeAll() lock.unlock() open.forEach { $0.timer?.cancel() } } @@ -126,7 +138,7 @@ final class MCPSession { 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 "tools/call": try callTool(id: id, params: 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) @@ -230,7 +242,12 @@ final class MCPSession { } // In a fixed order: clients cache the list, and the spec asks for it. + // The app's own first, then each running extension's. func tools() -> [[String: Any]] { + appTools() + context.extensionTools() + } + + private func appTools() -> [[String: Any]] { [ ["name": "settings_list", "title": "List stack-nudge settings", @@ -290,9 +307,17 @@ final class MCPSession { ] } - private func callTool(_ params: [String: Any]) throws -> [String: Any] { + private func callTool(id: Any, params: [String: Any], modern: Bool) throws { guard let name = params["name"] as? String else { throw MCPFailure.invalidParams("Missing tool name") } let arguments = params["arguments"] as? [String: Any] ?? [:] + if let result = try appTool(name, arguments: arguments) { + return respond(id, result, modern: modern) + } + callExtensionTool(id: id, name: name, arguments: arguments, modern: modern) + } + + // The app's own tools, answered at once. nil for any other name. + private func appTool(_ name: String, arguments: [String: Any]) throws -> [String: Any]? { switch name { case "settings_list": let category = arguments["category"] as? String @@ -332,10 +357,35 @@ final class MCPSession { else { return MCPProtocol.toolError("minutes is from 0 to \(MCPSession.maxMuteMinutes).") } return MCPProtocol.toolResult(context.mute(minutes: minutes, caller: currentCaller)) default: - throw MCPFailure.invalidParams("Unknown tool: \(name)") + return nil + } + } + + // An extension's tool, by its namespaced name. It answers on its own time, + // so the response is sent from the host's completion rather than here: + // this client's other requests, and a cancel for this one, aren't held + // behind it. Its result is its own. + private func callExtensionTool(id: Any, name: String, arguments: [String: Any], modern: Bool) { + lock.lock() + pendingCalls.append(id) + lock.unlock() + context.callExtensionTool(name, arguments: arguments, caller: currentCaller) { [weak self] result in + guard let self, self.takePendingCall(id) else { return } + guard let result else { + return self.send(MCPProtocol.error(id: id, code: MCPProtocol.invalidParams, message: "Unknown tool: \(name)")) + } + self.respond(id, result, modern: modern) } } + private func takePendingCall(_ id: Any) -> Bool { + lock.lock() + defer { lock.unlock() } + guard let index = pendingCalls.firstIndex(where: { MCPProtocol.sameID($0, id) }) else { return false } + pendingCalls.remove(at: index) + return true + } + // MARK: - Resources func resources() -> [[String: Any]] { @@ -422,6 +472,7 @@ final class MCPSession { private func cancel(_ requestID: Any?) { lock.lock() listeners.removeAll { MCPProtocol.sameID($0.id, requestID) } + pendingCalls.removeAll { MCPProtocol.sameID($0, requestID) } let cancelled = streams.filter { MCPProtocol.sameID($0.id, requestID) } streams.removeAll { MCPProtocol.sameID($0.id, requestID) } lock.unlock() diff --git a/panel/Panel.swift b/panel/Panel.swift index 1ebc214..931a5a4 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -6509,10 +6509,36 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, resume: { [weak self] in self?.resumeNotifications() }) let server = MCPServer(socketPath: MCPServer.defaultSocketPath, context: context) context.server = server + context.extensions = extensions do { try server.start() mcpServer = server mcpChanges = MCPChangeWatcher(server: server, nav: nav, store: store, sessions: sessions) + mcpChanges?.onSettingChanged = { [weak self] key, value, by in + self?.extensions.broadcast(event: "settings", fields: ["key": .string(key), "value": .string(value), + "by": .string(by)]) + } + // Extensions' tools and event types come and go with them. A + // service's every state change lands here, so clients are told + // only when what's offered actually differs: a restart would + // otherwise have them fetch the same list several times over. + // The name counts too, since each tool's description carries it. + var offeredTools: ([[String]], [[ExtensionMCP.Tool]]) = ([], []) + extensions.onMCPChanged = { [weak self, weak server] in + guard let self, let server else { return } + let contributions = self.extensions.mcpContributions + let types = Dictionary(uniqueKeysWithValues: contributions.map { + ($0.id, $0.mcp.eventTypes(owner: $0.id)) + }) + if server.events.replaceExtensionTypes(types) { server.eventsListChanged() } + let tools = (contributions.map { [$0.id, $0.name] }, contributions.map(\.mcp.tools)) + guard tools != offeredTools else { return } + offeredTools = tools + server.toolsListChanged() + } + extensions.onMCPEvent = { [weak server] name, data, eventID in + server?.emit(name, data: data, eventID: eventID) + } } catch { FileHandle.standardError.write(Data("stack-nudge: MCP server failed to start: \(error)\n".utf8)) } diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 59cf2bb..db621b0 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -3034,6 +3034,8 @@ extension ExtensionCapability { case .eventSession: return "See agent sessions" case .eventNudge: return "Read nudges, including prompt text" case .feed: return "Post to the event feed" + case .mcp: return "Offer tools and events to AI agents" + case .eventSettings: return "Know when a setting changes" } } @@ -3047,6 +3049,8 @@ extension ExtensionCapability { case .eventSession: return "seeing agent sessions" case .eventNudge: return "reading nudges, including prompt text" case .feed: return "posting to the event feed" + case .mcp: return "offering tools and events to AI agents" + case .eventSettings: return "knowing when a setting changes" } } } diff --git a/panel/ScreenshotRenderer.swift b/panel/ScreenshotRenderer.swift index 1027bb7..54a18f0 100644 --- a/panel/ScreenshotRenderer.swift +++ b/panel/ScreenshotRenderer.swift @@ -3,7 +3,7 @@ import SwiftUI // Dev-only: renders the panel from fixture state into PNGs: the README's // pictures (`readme`), the Extensions pages (`extensions`), the Integrations -// pages (`integrations`) and the MCP server's rows (`mcp`), for reviewers to +// pages (`integrations`) and the MCP server's screens (`mcp`), for reviewers to // see each screen without installing anything. // // StackNudge.app/Contents/MacOS/stack-nudge --render-screenshots [readme|extensions|integrations|mcp] @@ -237,7 +237,7 @@ enum ScreenshotRenderer { let published: [(String, String, String, String?, [String])] = [ ("away", "Away", "Locks the Mac when your phone leaves", "trusted", []), ("derby", "Token Derby", "A horse race where each runner advances on the tokens its owner burns.", nil, ["python3"]), - ("pylon", "Pylon", "Customer issues waiting on a response, and a nudge before the SLA runs out.", nil, ["python3"]), + ("pylon", "Pylon", "Customer issues waiting on a response, and a nudge before the SLA runs out.", "service", ["python3"]), ("system", "System", "CPU, memory and disk usage at a glance.", nil, []), ("radar", "Radar", "Watches your open pull requests for review requests.", "trusted", []), ("standup", "Standup", "Yesterday's merged work, ready to paste into standup.", nil, []), @@ -251,7 +251,7 @@ enum ScreenshotRenderer { ("pomodoro", "Pomodoro", "A 25-minute timer in the widget.", nil, []), ] let capabilities = ["away": ["bluetooth", "signal:presence"], "slack-status": ["event:idle"], - "focus": ["event:panel", "feed"]] + "focus": ["event:panel", "feed"], "pylon": ["mcp", "event:settings"]] let entries = published.map { id, name, description, tier, requires in ExtensionInstaller.IndexEntry(id: id, name: name, version: id == "derby" ? "1.2.0" : "1.1.0", description: description, asset: "extension-\(id)-1.1.0.tar.gz", @@ -302,6 +302,15 @@ enum ScreenshotRenderer { + (f.nav.rows(in: .actions).firstIndex(of: .mcpSetup) ?? 0) }) }, + // An extension that offers tools and events to MCP clients, as its + // install asks. + Scenario(name: "mcp-install-confirm", set: "mcp") { + let (catalog, host) = fixtureCatalog() + return (browser(catalog, host), { + catalog.selection = .row("pylon") + catalog.requestInstall(catalog.entries.first { $0.id == "pylon" }!) + }) + }, Scenario(name: "mcp-events", set: "mcp", height: panelHeight) { let f = PanelFixture(mode: .events) let request = MCPNudge.Request(title: "Migration finished", message: "All 14 tables moved, no errors.", diff --git a/panel/ServiceProtocol.swift b/panel/ServiceProtocol.swift index 95c8bd9..cd704f2 100644 --- a/panel/ServiceProtocol.swift +++ b/panel/ServiceProtocol.swift @@ -52,6 +52,10 @@ enum ServiceProtocol { case feedAction(id: String, key: String) case ping(id: Int) case stop + // An MCP client called one of the extension's tools (ExtensionMCP). + // `arguments` is the client's JSON object, already checked to be one; + // `caller` is the client as the bridge saw it, never as a model claims. + case mcpCall(id: Int, tool: String, arguments: Data, caller: [String: Value]) } // One line, newline included. Keys are sorted so the bytes are stable, @@ -79,6 +83,10 @@ enum ServiceProtocol { object = ["type": "ping", "id": id] case .stop: object = ["type": "stop"] + case .mcpCall(let id, let tool, let arguments, let caller): + object = ["type": "mcp.call", "id": id, "tool": tool, + "arguments": (try? JSONSerialization.jsonObject(with: arguments)) ?? [String: Any](), + "caller": caller.mapValues(\.json)] } // Every value above is a String, Int, Bool or a collection of them, so // serialisation cannot fail; the fallback is for the type checker. @@ -104,6 +112,11 @@ enum ServiceProtocol { // Settings picker. Whether the key is declared, and dynamic, is the // host's to check: this only knows the line. case choices(key: String, options: [ConfigOption]) + // The answer to an mcp.call: a string or an object, kept as JSON + // bytes, and whether it's an error the client should see as one. + case mcpResult(id: Int, result: Data, isError: Bool) + // An occurrence of one of the extension's declared event types. + case mcpEvent(name: String, data: Data, eventID: String?) } // A feed event, as an extension posts one. Text is trimmed to fit, as a @@ -267,6 +280,23 @@ enum ServiceProtocol { } } return .message(.choices(key: key, options: options)) + case "mcp.result": + guard let id = integer(object["id"]) else { return .invalid("mcp.result without an id") } + let result = object["result"] ?? "" + guard result is String || result is [String: Any], + let data = try? JSONSerialization.data(withJSONObject: result, options: [.fragmentsAllowed, .sortedKeys]) + else { return .invalid("mcp.result's result must be a string or an object") } + let isError = (object["isError"] as? NSNumber).map { CFGetTypeID($0) == CFBooleanGetTypeID() && $0.boolValue } ?? false + return .message(.mcpResult(id: id, result: data, isError: isError)) + case "mcp.event": + guard let name = object["name"] as? String, ExtensionMCP.isValidName(name) else { + return .invalid("mcp.event without a valid name") + } + guard let payload = object["data"] as? [String: Any], + let data = try? JSONSerialization.data(withJSONObject: payload, options: .sortedKeys) + else { return .invalid("mcp.event without a data object") } + let eventID = (object["eventId"] as? String).flatMap { $0.isEmpty || $0.count > 200 ? nil : $0 } + return .message(.mcpEvent(name: name, data: data, eventID: eventID)) default: return .ignored(type: type) } diff --git a/panel/ServiceSupervisor.swift b/panel/ServiceSupervisor.swift index 554689d..c16de64 100644 --- a/panel/ServiceSupervisor.swift +++ b/panel/ServiceSupervisor.swift @@ -102,6 +102,8 @@ final class ServiceSupervisor { case feed(ServiceProtocol.FeedPost) case retract(key: String) case choices(key: String, options: [ConfigOption]) + case mcpResult(id: Int, result: Data, isError: Bool) + case mcpEvent(name: String, data: Data, eventID: String?) // Something was dropped: too many messages, a line over its limit. // Sent once per process, since the point is to say it is happening, // not to forward the flood. @@ -313,6 +315,18 @@ final class ServiceSupervisor { } } + // Hands an MCP client's tool call to the extension. False when it can't + // take one: not running, or not granted mcp. The answer comes back as an + // `mcpResult` event. + func callMCP(id: Int, tool: String, arguments: Data, caller: [String: ServiceProtocol.Value], + accepted: @escaping (Bool) -> Void) { + perform { [weak self] in + guard let self, self.state == .running, self.granted.contains(.mcp) else { return accepted(false) } + self.send(.mcpCall(id: id, tool: tool, arguments: arguments, caller: caller)) + accepted(true) + } + } + // MARK: - Spawning private func spawn() { @@ -492,6 +506,12 @@ final class ServiceSupervisor { // Needs no capability: it only fills a picker for one of the // extension's own keys, which the host checks it declared. onEvent(.choices(key: key, options: options)) + case .mcpResult(let id, let result, let isError): + guard granted.contains(.mcp) else { return onEvent(.problem("mcp wasn't granted")) } + onEvent(.mcpResult(id: id, result: result, isError: isError)) + case .mcpEvent(let name, let data, let eventID): + guard granted.contains(.mcp) else { return onEvent(.problem("mcp wasn't granted")) } + onEvent(.mcpEvent(name: name, data: data, eventID: eventID)) case .pong(let id): guard outstandingPing?.id == id else { return } pongTimer?.cancel()