forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMCPServerToolsSection.swift
More file actions
278 lines (240 loc) · 10.5 KB
/
MCPServerToolsSection.swift
File metadata and controls
278 lines (240 loc) · 10.5 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
import SwiftUI
import Persist
import GitHubCopilotService
import Client
import Logger
import Foundation
/// Section for a single server's tools
struct MCPServerToolsSection: View {
let serverTools: MCPServerToolsCollection
@Binding var isServerEnabled: Bool
var forceExpand: Bool = false
@State private var toolEnabledStates: [String: Bool] = [:]
@State private var isExpanded: Bool = true
private var originalServerName: String { serverTools.name }
private var serverToggleLabel: some View {
HStack(spacing: 8) {
Text("MCP Server: \(serverTools.name)")
.fontWeight(.medium)
.foregroundStyle(
serverTools.status == .running ? .primary : .tertiary
)
if serverTools.status == .error || serverTools.status == .blocked {
let message = extractErrorMessage(serverTools.error?.description ?? "")
if serverTools.status == .error {
Badge(
attributedText: createErrorMessage(message),
level: .danger,
icon: "xmark.circle.fill"
)
.environment((\.openURL), OpenURLAction { url in
if url.absoluteString == "mcp://open-config" {
openMCPConfigFile()
return .handled
}
return .systemAction
})
} else if serverTools.status == .blocked {
Badge(text: serverTools.registryInfo ?? "Blocked", level: .warning, icon: "exclamationmark.triangle.fill")
}
} else if let registryInfo = serverTools.registryInfo {
Text(registryInfo)
.foregroundStyle(.secondary)
.font(.system(size: 11))
}
Spacer()
}
}
private func openMCPConfigFile() {
let url = URL(fileURLWithPath: mcpConfigFilePath)
NSWorkspace.shared.open(url)
}
private func createErrorMessage(_ baseMessage: String) -> AttributedString {
if hasServerConfigPlaceholders() {
var attributedString = AttributedString(baseMessage)
attributedString.append(AttributedString(". You may need to update placeholders in "))
var mcpLink = AttributedString("mcp.json")
mcpLink.link = URL(string: "mcp://open-config")
mcpLink.underlineStyle = .single
attributedString.append(mcpLink)
attributedString.append(AttributedString("."))
return attributedString
} else {
return AttributedString(baseMessage)
}
}
private var serverToggle: some View {
Toggle(isOn: Binding(
get: { isServerEnabled },
set: { updateAllToolsStatus(enabled: $0) }
)) {
serverToggleLabel
}
.toggleStyle(.checkbox)
.padding(.leading, 4)
.disabled(serverTools.status == .error || serverTools.status == .blocked)
}
private var divider: some View {
Divider()
.padding(.leading, 36)
.padding(.top, 2)
.padding(.bottom, 4)
}
private var toolsList: some View {
VStack(spacing: 0) {
divider
ForEach(serverTools.tools, id: \.name) { tool in
ToolRow(
toolName: tool.name,
toolDescription: tool.description,
toolStatus: tool._status,
isServerEnabled: isServerEnabled,
isToolEnabled: toolBindingFor(tool),
onToolToggleChanged: { handleToolToggleChange(tool: tool, isEnabled: $0) }
)
.padding(.leading, 36)
}
}
.onChange(of: serverTools) { newValue in
initializeToolStates(server: newValue)
}
}
var body: some View {
VStack(alignment: .leading, spacing: 0) {
// Conditional view rendering based on error state
if serverTools.status == .error || serverTools.status == .blocked {
// No disclosure group for error state
VStack(spacing: 0) {
serverToggle.padding(.leading, 12)
divider.padding(.top, 4)
}
} else {
// Regular DisclosureGroup for non-error state
DisclosureGroup(isExpanded: $isExpanded) {
toolsList
} label: {
serverToggle
}
.onAppear {
initializeToolStates(server: serverTools)
if forceExpand {
isExpanded = true
}
}
.onChange(of: forceExpand) { newForceExpand in
if newForceExpand {
isExpanded = true
}
}
if !isExpanded {
divider
}
}
}
}
private func extractErrorMessage(_ description: String) -> String {
guard let messageRange = description.range(of: "message:"),
let stackRange = description.range(of: "stack:") else {
return description
}
let start = description.index(messageRange.upperBound, offsetBy: 0)
let end = description.index(stackRange.lowerBound, offsetBy: 0)
return description[start..<end].trimmingCharacters(in: .whitespacesAndNewlines)
}
private func hasServerConfigPlaceholders() -> Bool {
let configFileURL = URL(fileURLWithPath: mcpConfigFilePath)
guard FileManager.default.fileExists(atPath: mcpConfigFilePath),
let data = try? Data(contentsOf: configFileURL),
let jsonObject = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let servers = jsonObject["servers"] as? [String: Any],
let serverConfig = servers[serverTools.name] else {
return false
}
// Convert server config to JSON string
guard let serverData = try? JSONSerialization.data(withJSONObject: serverConfig, options: []),
let serverConfigString = String(data: serverData, encoding: .utf8) else {
return false
}
// Check for placeholder patterns ending with }"
// Matches: "{PLACEHOLDER}", "${PLACEHOLDER}", "key={PLACEHOLDER}", "key=${PLACEHOLDER}", "${prefix:PLACEHOLDER}"
let placeholderPattern = "\"([a-zA-Z0-9_]+=)?\\$?\\{[a-zA-Z0-9_:\\-\\.]+\\}\""
guard let regex = try? NSRegularExpression(pattern: placeholderPattern, options: []) else {
return false
}
let range = NSRange(serverConfigString.startIndex..<serverConfigString.endIndex, in: serverConfigString)
return regex.firstMatch(in: serverConfigString, options: [], range: range) != nil
}
private func initializeToolStates(server: MCPServerToolsCollection) {
var disabled = 0
toolEnabledStates = server.tools.reduce(into: [:]) { result, tool in
result[tool.name] = tool._status == .enabled
disabled += result[tool.name]! ? 0 : 1
}
let enabled = toolEnabledStates.count - disabled
Logger.client.info("Server \(server.name) initialized with \(toolEnabledStates.count) tools (\(enabled) enabled, \(disabled) disabled).")
// Check if all tools are disabled to properly set server state
if !toolEnabledStates.isEmpty && toolEnabledStates.values.allSatisfy({ !$0 }) {
DispatchQueue.main.async {
isServerEnabled = false
}
}
}
private func toolBindingFor(_ tool: MCPTool) -> Binding<Bool> {
Binding(
get: { toolEnabledStates[tool.name] ?? (tool._status == .enabled) },
set: { toolEnabledStates[tool.name] = $0 }
)
}
private func handleToolToggleChange(tool: MCPTool, isEnabled: Bool) {
toolEnabledStates[tool.name] = isEnabled
// Update server state based on tool states
updateServerState()
// Update only this specific tool status
updateToolStatus(tool: tool, isEnabled: isEnabled)
}
private func updateServerState() {
// If any tool is enabled, server should be enabled
// If all tools are disabled, server should be disabled
let allToolsDisabled = serverTools.tools.allSatisfy { tool in
!(toolEnabledStates[tool.name] ?? (tool._status == .enabled))
}
isServerEnabled = !allToolsDisabled
}
private func updateToolStatus(tool: MCPTool, isEnabled: Bool) {
let serverUpdate = UpdateMCPToolsStatusServerCollection(
name: serverTools.name,
tools: [UpdatedMCPToolsStatus(name: tool.name, status: isEnabled ? .enabled : .disabled)]
)
updateMCPStatus([serverUpdate])
}
private func updateAllToolsStatus(enabled: Bool) {
isServerEnabled = enabled
// Get all tools for this server from the original collection
let allServerTools = CopilotMCPToolManagerObservable.shared.availableMCPServerTools
.first(where: { $0.name == originalServerName })?.tools ?? serverTools.tools
// Update all tool states - includes both visible and filtered-out tools
for tool in allServerTools {
toolEnabledStates[tool.name] = enabled
}
// Create status update for all tools
let serverUpdate = UpdateMCPToolsStatusServerCollection(
name: serverTools.name,
tools: allServerTools.map {
UpdatedMCPToolsStatus(name: $0.name, status: enabled ? .enabled : .disabled)
}
)
updateMCPStatus([serverUpdate])
}
private func updateMCPStatus(_ serverUpdates: [UpdateMCPToolsStatusServerCollection]) {
// Update status in AppState and CopilotMCPToolManager
AppState.shared.updateMCPToolsStatus(serverUpdates)
Task {
do {
let service = try getService()
try await service.updateMCPServerToolsStatus(serverUpdates)
} catch {
Logger.client.error("Failed to update MCP status: \(error.localizedDescription)")
}
}
}
}