-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathMCPServerGalleryViewModel.swift
More file actions
301 lines (243 loc) · 9.93 KB
/
MCPServerGalleryViewModel.swift
File metadata and controls
301 lines (243 loc) · 9.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import Client
import CryptoKit
import Foundation
import GitHubCopilotService
import Logger
import SwiftUI
@MainActor
final class MCPServerGalleryViewModel: ObservableObject {
// Input invariants
private let pageSize: Int
// User / UI state
@Published var isSearchBarVisible: Bool = false
@Published var searchText: String = ""
// Data
@Published private(set) var servers: [MCPRegistryServerDetail]
@Published private(set) var installedServers: Set<String> = []
@Published private(set) var registryMetadata: MCPRegistryServerListMetadata?
// Loading flags
@Published private(set) var isInitialLoading: Bool = false
@Published private(set) var isLoadingMore: Bool = false
@Published private(set) var isRefreshing: Bool = false
// Transient presentation state
@Published var pendingServer: MCPRegistryServerDetail?
@Published var infoSheetServer: MCPRegistryServerDetail?
@Published var mcpRegistryEntry: MCPRegistryEntry?
@Published private(set) var lastError: Error?
@AppStorage(\.mcpRegistryURL) var mcpRegistryURL
// Service integration
private let registryService = MCPRegistryService.shared
init(
initialList: MCPRegistryServerList,
mcpRegistryEntry: MCPRegistryEntry? = nil,
pageSize: Int = 30
) {
self.pageSize = pageSize
servers = initialList.servers
registryMetadata = initialList.metadata
self.mcpRegistryEntry = mcpRegistryEntry
}
// MARK: - Derived Data
var filteredServers: [MCPRegistryServerDetail] {
// First filter for only latest official servers
let latestServers = servers.filter { server in
server.meta?.official?.isLatest == true
}
// Then apply search filter if search text is present
let key = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard !key.isEmpty else { return latestServers }
return latestServers.filter {
$0.name.lowercased().contains(key) ||
$0.description.lowercased().contains(key)
}
}
var shouldShowLoadMoreSentinel: Bool {
// Show load more sentinel if there's more data available
if let next = registryMetadata?.nextCursor, !next.isEmpty {
return true
}
return false
}
func isServerInstalled(serverId: String) -> Bool {
// Find the server by ID and check installation status using the service
if let server = servers.first(where: { $0.stableID == serverId }) {
return registryService.isServerInstalled(server)
}
// Fallback to the existing key-based check for backwards compatibility
let key = createRegistryServerKey(registryURL: mcpRegistryURL, serverId: serverId)
return installedServers.contains(key)
}
func hasNoDeployments(_ server: MCPRegistryServerDetail) -> Bool {
return server.remotes?.isEmpty ?? true && server.packages?.isEmpty ?? true
}
// MARK: - User Intents (Updated with Service Integration)
func requestInstall(_ server: MCPRegistryServerDetail) {
Task {
await installServer(server)
}
}
func requestInstallWithConfiguration(_ server: MCPRegistryServerDetail, configuration: String) {
Task {
await installServer(server, configuration: configuration)
}
}
func installServer(_ server: MCPRegistryServerDetail, configuration: String? = nil) async {
do {
let installationOption: InstallationOption?
if let configName = configuration {
// Find the specific installation option
let options = registryService.getAllInstallationOptions(for: server)
installationOption = options.first { option in
option.displayName.contains(configName) ||
option.description.contains(configName)
}
} else {
installationOption = nil
}
try await registryService.installMCPServer(server, installationOption: installationOption)
// Refresh installed servers list
loadInstalledServers()
Logger.client.info("Successfully installed MCP Server '\(server.name)'")
} catch {
Logger.client.error("Failed to install server '\(server.name)': \(error)")
// TODO: Consider adding error handling UI feedback here
}
}
func uninstallServer(_ server: MCPRegistryServerDetail) async {
do {
try await registryService.uninstallMCPServer(server)
// Refresh installed servers list
loadInstalledServers()
Logger.client.info("Successfully uninstalled MCP Server '\(server.name)'")
} catch {
Logger.client.error("Failed to uninstall server '\(server.name)': \(error)")
// TODO: Consider adding error handling UI feedback here
}
}
func refresh() {
Task {
isRefreshing = true
defer { isRefreshing = false }
// Clear the current server list
servers = []
registryMetadata = nil
searchText = ""
// Load servers from the base URL
_ = await loadServerList(resetToFirstPage: true)
}
}
// Called from Settings view to refresh with optional new registry entry
func refreshFromURL(mcpRegistryEntry: MCPRegistryEntry? = nil) async -> Error? {
isRefreshing = true
defer { isRefreshing = false }
// Clear the current server list immediately
servers = []
registryMetadata = nil
searchText = ""
self.mcpRegistryEntry = mcpRegistryEntry
Logger.client.info("Cleared gallery view model data for refresh")
// Load servers from the base URL
let error = await loadServerList(resetToFirstPage: true)
// Reload installed servers after fetching new data
loadInstalledServers()
return error
}
func updateData(serverList: MCPRegistryServerList, mcpRegistryEntry: MCPRegistryEntry? = nil) {
servers = serverList.servers
registryMetadata = serverList.metadata
self.mcpRegistryEntry = mcpRegistryEntry
searchText = ""
loadInstalledServers()
Logger.client.info("Updated gallery view model with \(serverList.servers.count) servers and registry entry: \(String(describing: mcpRegistryEntry))")
}
func clearData() {
servers = []
registryMetadata = nil
searchText = ""
Logger.client.info("Cleared gallery view model data")
}
func showInfo(_ server: MCPRegistryServerDetail) {
infoSheetServer = server
}
func dismissInfo() {
infoSheetServer = nil
}
// MARK: - Data Loading
func loadMoreIfNeeded() {
guard !isLoadingMore,
!isInitialLoading,
let nextCursor = registryMetadata?.nextCursor,
!nextCursor.isEmpty
else { return }
Task {
await loadServerList(resetToFirstPage: false)
}
}
private func loadServerList(resetToFirstPage: Bool) async -> Error? {
if resetToFirstPage {
isInitialLoading = true
} else {
isLoadingMore = true
}
defer {
isInitialLoading = false
isLoadingMore = false
}
lastError = nil
do {
let service = try getService()
let cursor = resetToFirstPage ? nil : registryMetadata?.nextCursor
let serverList = try await service.listMCPRegistryServers(
.init(
baseUrl: mcpRegistryURL,
cursor: cursor,
limit: pageSize
)
)
if resetToFirstPage {
// Replace all servers when refreshing or resetting
servers = serverList?.servers ?? []
registryMetadata = serverList?.metadata
} else {
// Append when loading more
servers.append(contentsOf: serverList?.servers ?? [])
registryMetadata = serverList?.metadata
}
return nil
} catch {
Logger.client.error("Failed to load MCP servers: \(error)")
lastError = error
return error
}
}
func loadInstalledServers() {
// Clear the set and rebuild it
installedServers.removeAll()
let configFileURL = URL(fileURLWithPath: mcpConfigFilePath)
guard FileManager.default.fileExists(atPath: mcpConfigFilePath),
let data = try? Data(contentsOf: configFileURL),
let currentConfig = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let serversDict = currentConfig["servers"] as? [String: Any] else {
return
}
for (_, serverConfig) in serversDict {
guard
let serverConfigDict = serverConfig as? [String: Any],
let metadata = serverConfigDict["x-metadata"] as? [String: Any],
let registry = metadata["registry"] as? [String: Any],
let registryUrl = registry["url"] as? String,
let serverId = registry["serverId"] as? String
else { continue }
installedServers.insert(
createRegistryServerKey(registryURL: registryUrl, serverId: serverId)
)
}
}
private func createRegistryServerKey(registryURL: String, serverId: String) -> String {
return registryService.createRegistryServerKey(registryURL: registryURL, serverId: serverId)
}
// MARK: - Installation Options Helper
func getInstallationOptions(for server: MCPRegistryServerDetail) -> [InstallationOption] {
return registryService.getAllInstallationOptions(for: server)
}
}