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
198 changes: 198 additions & 0 deletions Tests/StackNudgePanelCoreTests/ExtensionMCPTests.swift
Original file line number Diff line number Diff line change
@@ -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, ExtensionManifest.ParseFailure> {
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")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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") }
Expand Down
2 changes: 1 addition & 1 deletion Tests/StackNudgePanelCoreTests/ExtensionTierTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
6 changes: 3 additions & 3 deletions Tests/StackNudgePanelCoreTests/MCPEventsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}
}
Expand Down
42 changes: 42 additions & 0 deletions Tests/StackNudgePanelCoreTests/MCPServerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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]] = []
Expand Down Expand Up @@ -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)
Expand Down
26 changes: 16 additions & 10 deletions docs/design/local-mcp.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.

Expand Down
1 change: 1 addition & 0 deletions docs/design/service-extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading