forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToolsConfigView.swift
More file actions
227 lines (196 loc) · 8.1 KB
/
ToolsConfigView.swift
File metadata and controls
227 lines (196 loc) · 8.1 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
import Client
import Foundation
import Logger
import SharedUIComponents
import SwiftUI
import Toast
import ConversationServiceProvider
import GitHubCopilotService
import ComposableArchitecture
struct MCPConfigView: View {
@State private var mcpConfig: String = ""
@Environment(\.toast) var toast
@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 isMCPFFEnabled = false
@State private var selectedOption = ToolType.MCP
@Environment(\.colorScheme) var colorScheme
private static var lastSyncTimestamp: Date? = nil
enum ToolType: String, CaseIterable, Identifiable {
case MCP, BuiltIn
var id: Self { self }
}
var body: some View {
WithPerceptionTracking {
ScrollView {
Picker("", selection: $selectedOption) {
Text("MCP").tag(ToolType.MCP)
Text("Built-In").tag(ToolType.BuiltIn)
}
.pickerStyle(.segmented)
.frame(width: 400)
Group {
if selectedOption == .MCP {
VStack(alignment: .leading, spacing: 8) {
MCPIntroView(isMCPFFEnabled: $isMCPFFEnabled)
if isMCPFFEnabled {
MCPManualInstallView()
MCPToolsListView()
}
}
.onAppear {
setupConfigFilePath()
Task {
await updateMCPFeatureFlag()
}
}
.onDisappear {
stopMonitoringConfigFile()
}
.onChange(of: isMCPFFEnabled) { newMCPFFEnabled in
if newMCPFFEnabled {
startMonitoringConfigFile()
refreshConfiguration(())
} else {
stopMonitoringConfigFile()
}
}
.onReceive(DistributedNotificationCenter.default()
.publisher(for: .gitHubCopilotFeatureFlagsDidChange)) { _ in
Task {
await updateMCPFeatureFlag()
}
}
} else {
BuiltInToolsListView()
}
}
.padding(20)
}
}
}
private func updateMCPFeatureFlag() async {
do {
let service = try getService()
if let featureFlags = try await service.getCopilotFeatureFlags() {
isMCPFFEnabled = featureFlags.mcp
}
} catch {
Logger.client.error("Failed to get copilot feature flags: \(error)")
}
}
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
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 seconds
let currentDate = getFileModificationDate(url: configFileURL)
if let currentDate = currentDate, currentDate != lastModificationDate {
// File modification date has changed, update our record
lastModificationDate = currentDate
// Read and validate the updated content
if let validJson = readAndValidateJSON(from: configFileURL) {
await MainActor.run {
mcpConfig = validJson
refreshConfiguration(validJson)
toast("MCP configuration file updated", .info)
}
} else {
// If JSON is invalid, show error
await MainActor.run {
toast("Invalid JSON in MCP configuration file", .error)
}
}
}
}
}
}
private func stopMonitoringConfigFile() {
isMonitoring = false
fileMonitorTask?.cancel()
fileMonitorTask = nil
}
func refreshConfiguration(_: Any) {
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)
}
Task {
do {
let service = try getService()
try await service.postNotification(
name: Notification.Name
.gitHubCopilotShouldRefreshEditorInformation.rawValue
)
toast("MCP configuration updated", .info)
} catch {
toast(error.localizedDescription, .error)
}
}
}
}
#Preview {
MCPConfigView()
.frame(width: 800, height: 600)
}