-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathToolsConfigView.swift
More file actions
275 lines (240 loc) · 10.9 KB
/
ToolsConfigView.swift
File metadata and controls
275 lines (240 loc) · 10.9 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
import Client
import ComposableArchitecture
import ConversationServiceProvider
import Foundation
import GitHubCopilotService
import Logger
import Persist
import SharedUIComponents
import SwiftUI
import SystemUtils
import Toast
struct MCPConfigView: View {
@State private var mcpConfig: String = ""
@Environment(\.toast) var toast
@ObservedObject private var featureFlags = FeatureFlagManager.shared
@ObservedObject private var copilotPolicy = CopilotPolicyManager.shared
@State private var configFilePath: String = mcpConfigFilePath
@State private var isMonitoring: Bool = false
@State private var lastModificationDate: Date? = nil
@State private var fileMonitorTask: Task<Void, Error>? = nil
@State private var selectedMode: ConversationMode = .defaultAgent
@Environment(\.colorScheme) var colorScheme
private var isCustomAgentEnabled: Bool {
copilotPolicy.isCustomAgentEnabled
}
private static var lastSyncTimestamp: Date? = nil
@State private var debounceTimer: Timer?
private static let refreshDebounceInterval: TimeInterval = 1.0 // 1.0 second debounce
var body: some View {
WithPerceptionTracking {
ScrollView {
Picker("", selection: Binding(
get: { hostAppStore.state.activeToolsSubTab },
set: { hostAppStore.send(.setActiveToolsSubTab($0)) }
)) {
if #available(macOS 26.0, *) {
Text("MCP".padded(centerTo: 24, with: "\u{2002}")).tag(ToolsSubTab.MCP)
Text("Built-In".padded(centerTo: 24, with: "\u{2002}")).tag(ToolsSubTab.BuiltIn)
Text("Auto-Approve".padded(centerTo: 24, with: "\u{2002}")).tag(ToolsSubTab.AutoApprove)
} else {
Text("MCP").tag(ToolsSubTab.MCP)
Text("Built-In").tag(ToolsSubTab.BuiltIn)
Text("Auto-Approve").tag(ToolsSubTab.AutoApprove)
}
}
.frame(width: 400)
.labelsHidden()
.pickerStyle(.segmented)
.padding(.top, 12)
.padding(.bottom, 4)
Group {
if hostAppStore.activeToolsSubTab == .MCP {
VStack(alignment: .leading, spacing: 8) {
MCPIntroView(isMCPFFEnabled: featureFlags.isMCPEnabled)
if featureFlags.isMCPEnabled {
MCPManualInstallView()
if featureFlags.isEditorPreviewEnabled {
MCPRegistryURLView()
}
MCPXcodeServerInstallView()
MCPToolsListView(
selectedMode: $selectedMode,
isCustomAgentEnabled: isCustomAgentEnabled
)
HStack {
Spacer()
AdaptiveHelpLink(action: { NSWorkspace.shared.open(
URL(string: "https://modelcontextprotocol.io/introduction")!
) })
}
}
}
.onAppear {
setupConfigFilePath()
if featureFlags.isMCPEnabled {
startMonitoringConfigFile()
}
}
.onDisappear {
stopMonitoringConfigFile()
}
.onChange(of: featureFlags.isMCPEnabled) { newMCPFFEnabled in
if newMCPFFEnabled {
startMonitoringConfigFile()
refreshConfiguration()
} else {
stopMonitoringConfigFile()
}
}
.onChange(of: isCustomAgentEnabled) { isEnabled in
if !isEnabled && !selectedMode.isDefaultAgent {
selectedMode = .defaultAgent
}
}
} else if hostAppStore.activeToolsSubTab == .BuiltIn {
BuiltInToolsListView(
selectedMode: $selectedMode,
isCustomAgentEnabled: isCustomAgentEnabled
)
} else {
AutoApproveContainerView()
}
}
.padding(.horizontal, 20)
}
}
}
private func setupConfigFilePath() {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: configDirectory.path) {
try? fileManager.createDirectory(at: configDirectory, withIntermediateDirectories: true)
}
// If the file doesn't exist, create one with a proper structure
let configFileURL = URL(fileURLWithPath: configFilePath)
if !fileManager.fileExists(atPath: configFilePath) {
try? """
{
"servers": {
}
}
""".write(to: configFileURL, atomically: true, encoding: .utf8)
}
// Read the current content from file and ensure it's valid JSON
mcpConfig = readAndValidateJSON(from: configFileURL) ?? "{}"
// Get initial modification date
lastModificationDate = getFileModificationDate(url: configFileURL)
}
/// Reads file content and validates it as JSON, returning only the "servers" object
private func readAndValidateJSON(from url: URL) -> String? {
guard let data = try? Data(contentsOf: url) else {
return nil
}
// Try to parse as JSON to validate
do {
// First verify it's valid JSON
let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any]
// Extract the "servers" object
guard let servers = jsonObject?["servers"] as? [String: Any] else {
Logger.client.info("No 'servers' key found in MCP configuration")
toast("No 'servers' key found in MCP configuration", .error)
// Return empty object if no servers section
return "{}"
}
// Convert the servers object back to JSON data
let serversData = try JSONSerialization.data(
withJSONObject: servers, options: [.prettyPrinted])
// Return as a string
return String(data: serversData, encoding: .utf8)
} catch {
// If parsing fails, return nil
Logger.client.info("Parsing MCP JSON error: \(error)")
toast("Invalid JSON in MCP configuration file", .error)
return nil
}
}
private func getFileModificationDate(url: URL) -> Date? {
let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
return attributes?[.modificationDate] as? Date
}
private func startMonitoringConfigFile() {
stopMonitoringConfigFile() // Stop existing monitoring if any
isMonitoring = true
Logger.client.info("Starting MCP config file monitoring")
fileMonitorTask = Task {
let configFileURL = URL(fileURLWithPath: configFilePath)
// Check for file changes periodically
while isMonitoring {
try? await Task.sleep(nanoseconds: 3_000_000_000) // Check every 3 second for better responsiveness
guard isMonitoring else { break } // Extra check after sleep
let currentDate = getFileModificationDate(url: configFileURL)
if let currentDate = currentDate, currentDate != lastModificationDate {
// File modification date has changed, update our record
Logger.client.info("MCP config file change detected")
lastModificationDate = currentDate
// Read and validate the updated content
if let validJson = readAndValidateJSON(from: configFileURL) {
await MainActor.run {
mcpConfig = validJson
refreshConfiguration()
toast("MCP configuration file updated", .info)
}
} else {
// If JSON is invalid, show error
await MainActor.run {
toast("Invalid JSON in MCP configuration file", .error)
Logger.client.info("Invalid JSON detected during monitoring")
}
}
}
}
Logger.client.info("Stopped MCP config file monitoring")
}
}
private func stopMonitoringConfigFile() {
guard isMonitoring else { return }
Logger.client.info("Stopping MCP config file monitoring")
isMonitoring = false
fileMonitorTask?.cancel()
fileMonitorTask = nil
}
func refreshConfiguration() {
if MCPConfigView.lastSyncTimestamp == lastModificationDate {
return
}
MCPConfigView.lastSyncTimestamp = lastModificationDate
let fileURL = URL(fileURLWithPath: configFilePath)
if let jsonString = readAndValidateJSON(from: fileURL) {
UserDefaults.shared.set(jsonString, for: \.gitHubCopilotMCPConfig)
}
// Debounce the refresh notification to avoid sending too frequently
debounceTimer?.invalidate()
debounceTimer = Timer.scheduledTimer(withTimeInterval: MCPConfigView.refreshDebounceInterval, repeats: false) { _ in
Task {
do {
let service = try getService()
try await service.postNotification(
name: Notification.Name
.gitHubCopilotShouldRefreshEditorInformation.rawValue
)
await MainActor.run {
toast("Fetching MCP tools...", .info)
}
} catch {
await MainActor.run {
toast(error.localizedDescription, .error)
}
}
}
}
}
}
extension String {
func padded(centerTo total: Int, with pad: Character = " ") -> String {
guard count < total else { return self }
let deficit = total - count
let left = deficit / 2
let right = deficit - left
return String(repeating: pad, count: left) + self + String(repeating: pad, count: right)
}
}