Branchwell

Textley / app · textley.ai / Sources / Textley / TextleyMCPStdioBridge.swift

1import Foundation
2import Logging
3import MCP
4
5/// The agent launches the existing app executable in this mode. It does not
6/// instantiate SwiftUI, open Core Data or enable access. Only the running app
7/// accesses the library and enforces permission/revision checks.
8enum TextleyMCPStdioBridge {
9 static func run() async {
10 do {
11 let connection = try configuration()
12 try await forward(endpoint: connection.endpoint, token: connection.token)
13 } catch {
14 // Never include requests, note content or credentials in diagnostics.
15 FileHandle.standardError.write(Data("Open Textley, enable MCP access in Settings → Integrations → MCP, and restart this server in your agent. If macOS asks, approve Textley’s existing Keychain access.\n".utf8))
16 exit(1)
17 }
18 }
19
20 private static func configuration() throws -> (endpoint: URL, token: String) {
21 #if DEBUG
22 // Integration harness only; these overrides are absent from Release.
23 if let address = ProcessInfo.processInfo.environment["TEXTLEY_MCP_TEST_ENDPOINT"],
24 let token = ProcessInfo.processInfo.environment["TEXTLEY_MCP_TEST_TOKEN"],
25 let endpoint = URL(string: address), endpoint.scheme == "http", endpoint.host == "127.0.0.1",
26 endpoint.path == "/mcp", token.count == 64 {
27 return (endpoint, token)
28 }
29 #endif
30 guard let token = try TextleyMCPToken.loadExisting() else {
31 throw MCPAccessError.message("Enable MCP in Textley first.")
32 }
33 return (URL(string: "http://127.0.0.1:\(TextleyMCPService.defaultPort)/mcp")!, token)
34 }
35
36 static func forward(endpoint: URL, token: String) async throws {
37 let client = Client(name: "Textley desktop bridge", version: "1.0.3")
38 let configuration = URLSessionConfiguration.ephemeral
39 configuration.timeoutIntervalForRequest = 600
40 configuration.timeoutIntervalForResource = 660
41 let transport = HTTPClientTransport(endpoint: endpoint, configuration: configuration, streaming: false, requestModifier: { request in
42 var request = request
43 request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
44 return request
45 })
46 do {
47 let upstream = try await client.connect(transport: transport)
48 let server = Server(name: "Textley", version: "1.0.3", instructions: upstream.instructions, capabilities: .init(tools: .init()))
49 await server.withMethodHandler(ListTools.self) { parameters in
50 let context = try await client.send(ListTools.request(parameters))
51 return try await context.value
52 }
53 await server.withMethodHandler(CallTool.self) { parameters in
54 let context = try await client.send(CallTool.request(parameters))
55 return try await context.value
56 }
57 try await server.start(transport: TextleyStdioTransport())
58 await server.waitUntilCompleted()
59 await server.stop()
60 await client.disconnect()
61 } catch {
62 await client.disconnect()
63 throw error
64 }
65 }
66}
67
68private actor TextleyStdioTransport: Transport {
69 private let stdio = StdioTransport()
70 nonisolated var logger: Logger { stdio.logger }
71
72 func connect() async throws { try await stdio.connect() }
73 func disconnect() async { await stdio.disconnect() }
74 func send(_ data: Data) async throws { try await stdio.send(data) }
75
76 func receive() -> AsyncThrowingStream<Data, Error> {
77 AsyncThrowingStream { continuation in
78 let reader = Task {
79 do {
80 for try await message in await stdio.receive() {
81 continuation.yield(TextleyMCPInitialization.normalized(message))
82 }
83 continuation.finish()
84 } catch {
85 continuation.finish(throwing: error)
86 }
87 }
88 continuation.onTermination = { _ in reader.cancel() }
89 }
90 }
91}
92
93enum TextleyMCPInitialization {
94 static func normalized(_ message: Data) -> Data {
95 guard var request = (try? JSONSerialization.jsonObject(with: message)) as? [String: Any],
96 request["method"] as? String == "initialize",
97 var params = request["params"] as? [String: Any],
98 var capabilities = params["capabilities"] as? [String: Any],
99 let experimental = capabilities["experimental"] as? [String: Any],
100 experimental.values.contains(where: { !($0 is String) }) else { return message }
101
102 // The Swift SDK expects strings here. MCP clients can send objects, and Textley doesn't use experimental capabilities.
103 capabilities.removeValue(forKey: "experimental")
104 params["capabilities"] = capabilities
105 request["params"] = params
106 return (try? JSONSerialization.data(withJSONObject: request)) ?? message
107 }
108}