|
| 1 | +// |
| 2 | +// MCPToolsStore.swift |
| 3 | +// DemoChat |
| 4 | +// |
| 5 | +// Created by Tony Li on 24/6/25. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | +import MCP |
| 10 | +import OpenAI |
| 11 | +import Logging |
| 12 | +import SwiftUI |
| 13 | + |
| 14 | +@MainActor |
| 15 | +public final class MCPToolsStore: ObservableObject { |
| 16 | + @Published public var availableTools: [MCPToolInfo] = [] |
| 17 | + @Published public var enabledTools: Set<String> = [] |
| 18 | + @Published public var isConnecting: Bool = false |
| 19 | + @Published public var connectionError: String? |
| 20 | + @Published public var isConnected: Bool = false |
| 21 | + |
| 22 | + public var githubToken: Binding<String> |
| 23 | + private var mcpClient: MCP.Client? |
| 24 | + private let logger = Logger(label: "mcp.tools.store") |
| 25 | + |
| 26 | + // Persistence keys |
| 27 | + private let enabledToolsKey = "mcpEnabledTools" |
| 28 | + |
| 29 | + public struct MCPToolInfo: Identifiable, Hashable { |
| 30 | + public let id: String |
| 31 | + public let name: String |
| 32 | + public let description: String |
| 33 | + public let inputSchema: MCP.Value? |
| 34 | + |
| 35 | + public init(from tool: MCP.Tool) { |
| 36 | + self.id = tool.name |
| 37 | + self.name = tool.name |
| 38 | + self.description = tool.description |
| 39 | + self.inputSchema = tool.inputSchema |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public init(githubToken: Binding<String>) { |
| 44 | + self.githubToken = githubToken |
| 45 | + loadEnabledTools() |
| 46 | + |
| 47 | + // Auto-connect if token is available |
| 48 | + if !githubToken.wrappedValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { |
| 49 | + Task { |
| 50 | + await connectToGitHubMCP() |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /// Connect to GitHub MCP server and discover available tools |
| 56 | + public func connectToGitHubMCP() async { |
| 57 | + isConnecting = true |
| 58 | + connectionError = nil |
| 59 | + |
| 60 | + // Check if GitHub token is provided |
| 61 | + guard !githubToken.wrappedValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { |
| 62 | + connectionError = "GitHub token is required for authentication" |
| 63 | + isConnecting = false |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + do { |
| 68 | + // Create MCP client |
| 69 | + let client = MCP.Client( |
| 70 | + name: "OpenAI-Demo", |
| 71 | + version: "1.0.0" |
| 72 | + ) |
| 73 | + |
| 74 | + // Create HTTP transport for GitHub MCP server with authentication headers |
| 75 | + let configuration = URLSessionConfiguration.default |
| 76 | + configuration.httpAdditionalHeaders = [ |
| 77 | + "Authorization": "Bearer \(githubToken.wrappedValue.trimmingCharacters(in: .whitespacesAndNewlines))" |
| 78 | + ] |
| 79 | + |
| 80 | + let transport = HTTPClientTransport( |
| 81 | + endpoint: URL(string: "https://api.githubcopilot.com/mcp/")!, |
| 82 | + configuration: configuration, |
| 83 | + streaming: true, |
| 84 | + logger: logger |
| 85 | + ) |
| 86 | + |
| 87 | + // Connect to the server |
| 88 | + let result = try await client.connect(transport: transport) |
| 89 | + |
| 90 | + // Check if server supports tools |
| 91 | + guard result.capabilities.tools != nil else { |
| 92 | + throw MCPError.invalidRequest("GitHub MCP server does not support tools") |
| 93 | + } |
| 94 | + |
| 95 | + // List available tools |
| 96 | + let toolsResponse = try await client.listTools() |
| 97 | + |
| 98 | + // Update UI |
| 99 | + self.mcpClient = client |
| 100 | + self.availableTools = toolsResponse.tools.map { MCPToolInfo(from: $0) } |
| 101 | + self.isConnected = true |
| 102 | + |
| 103 | + // Restore enabled tools that are still available |
| 104 | + let availableToolNames = Set(self.availableTools.map { $0.name }) |
| 105 | + self.enabledTools = self.enabledTools.intersection(availableToolNames) |
| 106 | + |
| 107 | + logger.info("Successfully connected to GitHub MCP server with \(toolsResponse.tools.count) tools") |
| 108 | + |
| 109 | + } catch { |
| 110 | + connectionError = error.localizedDescription |
| 111 | + logger.error("Failed to connect to GitHub MCP server: \(error)") |
| 112 | + } |
| 113 | + |
| 114 | + isConnecting = false |
| 115 | + } |
| 116 | + |
| 117 | + /// Disconnect from MCP server |
| 118 | + public func disconnect() async { |
| 119 | + if let client = mcpClient { |
| 120 | + await client.disconnect() |
| 121 | + mcpClient = nil |
| 122 | + } |
| 123 | + |
| 124 | + isConnected = false |
| 125 | + availableTools = [] |
| 126 | + enabledTools = [] |
| 127 | + connectionError = nil |
| 128 | + |
| 129 | + // Clear the GitHub token from storage |
| 130 | + githubToken.wrappedValue = "" |
| 131 | + |
| 132 | + // Clear saved enabled tools |
| 133 | + UserDefaults.standard.removeObject(forKey: enabledToolsKey) |
| 134 | + } |
| 135 | + |
| 136 | + /// Toggle tool enabled state |
| 137 | + public func toggleTool(_ toolName: String) { |
| 138 | + if enabledTools.contains(toolName) { |
| 139 | + enabledTools.remove(toolName) |
| 140 | + } else { |
| 141 | + enabledTools.insert(toolName) |
| 142 | + } |
| 143 | + saveEnabledTools() |
| 144 | + } |
| 145 | + |
| 146 | + /// Enable all available tools |
| 147 | + public func enableAllTools() { |
| 148 | + enabledTools = Set(availableTools.map { $0.name }) |
| 149 | + saveEnabledTools() |
| 150 | + } |
| 151 | + |
| 152 | + /// Disable all tools |
| 153 | + public func disableAllTools() { |
| 154 | + enabledTools.removeAll() |
| 155 | + saveEnabledTools() |
| 156 | + } |
| 157 | + |
| 158 | + /// Check if all available tools are enabled |
| 159 | + public var areAllToolsEnabled: Bool { |
| 160 | + !availableTools.isEmpty && enabledTools.count == availableTools.count |
| 161 | + } |
| 162 | + |
| 163 | + /// Get list of enabled tool names for OpenAI API |
| 164 | + public var allowedTools: Components.Schemas.MCPTool.AllowedToolsPayload? { |
| 165 | + guard !enabledTools.isEmpty else { return nil } |
| 166 | + return .case1(Array(enabledTools)) |
| 167 | + } |
| 168 | + |
| 169 | + /// Get authentication headers for GitHub MCP server |
| 170 | + public var authHeaders: [String: String]? { |
| 171 | + guard !githubToken.wrappedValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { |
| 172 | + return nil |
| 173 | + } |
| 174 | + return ["Authorization": "Bearer \(githubToken.wrappedValue.trimmingCharacters(in: .whitespacesAndNewlines))"] |
| 175 | + } |
| 176 | + |
| 177 | + // MARK: - Persistence |
| 178 | + |
| 179 | + private func loadEnabledTools() { |
| 180 | + if let savedTools = UserDefaults.standard.array(forKey: enabledToolsKey) as? [String] { |
| 181 | + enabledTools = Set(savedTools) |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + private func saveEnabledTools() { |
| 186 | + UserDefaults.standard.set(Array(enabledTools), forKey: enabledToolsKey) |
| 187 | + } |
| 188 | + |
| 189 | +} |
0 commit comments