From dd06e337fcaf390629c09c1fb888e65157c0522a Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Mon, 16 Nov 2026 17:43:02 +0000 Subject: [PATCH] Start built-in web and reconnect enabled MCP profiles --- Docs/MCP.md | 23 +++++++++----------- Sources/MCP.swift | 34 ++++++++++++++++++++++------- Sources/StudioModel.swift | 45 +++++++++++++++++++++++++++++++++++---- Tests/StudioTests.swift | 34 +++++++++++++++++++++++++++++ 4 files changed, 111 insertions(+), 25 deletions(-) diff --git a/Docs/MCP.md b/Docs/MCP.md index aa754c5..260318d 100644 --- a/Docs/MCP.md +++ b/Docs/MCP.md @@ -2,25 +2,22 @@ ## Built-in web toolset -In **Toolbox → MCP Servers**, choose **Connect** on **Built-In Web**. This loads -`retrieve_page` and `web_search` inside AI Studio without launching an MCP -subprocess. Choose a tool, review its JSON input and confirm the call. +AI Studio registers **Built-In Web** at launch. Its `retrieve_page` and +`web_search` tools make requests on demand, without an MCP subprocess. Choose a tool, review its JSON input and confirm the call. Page retrieval takes a `url`. Search takes a `query` and defaults to Bing. Configure a SearXNG search URL in **Toolbox → Web** to override the default. You can attach returned sources to the next chat message. ## Connect an existing server -Open **Toolbox** beside the composer. Choose **Use LM Studio Config** to read -`~/.lmstudio/mcp.json`, or **Import mcp.json** to choose another file. Select -**Connect** on the row for the server you want. For stdio, choose **Start & -Connect** to launch the executable and discover tools in one step. Each row -shows its own connection status. Multiple servers may stay connected, and -tool calls on different servers can run concurrently. Use **Tools** on a -connected row to open its tool inspector. The composer shows the total -number of connected toolsets. The composer shows the connected toolset and its tool -count. The connection stays active when you close Toolbox. Use **Disconnect** on a server’s row to end that connection. AI Studio remembers the configuration file and the selected -profile. The source file remains your editable configuration. +Open **Toolbox → MCP Servers**. Choose **Use LM Studio Config** to read +`~/.lmstudio/mcp.json`, or **Import mcp.json** to choose another file. Turn on +the switch beside each server you want to use. It connects immediately and +reconnects the next time AI Studio opens. Turn the switch off to disconnect it. + +Each server row shows its own status and offers **Retry** after a failed +connection. Multiple servers can stay connected. Use **Tools** on a connected +row to open its tool inspector. The manual connection form is session-only. A local profile accepts `command`, an `args` array, `env`, and an optional absolute `cwd`. Each argument stays a separate string. No shell interprets the diff --git a/Sources/MCP.swift b/Sources/MCP.swift index 9651d18..8df5381 100644 --- a/Sources/MCP.swift +++ b/Sources/MCP.swift @@ -243,9 +243,10 @@ struct MCPSettings: View { HSplitView { Form { Section("Built-In Tools") { - connectionRow(.web, title: BuiltInWebTools.name, subtitle: "Retrieve pages and search via SearXNG", icon: "globe") { - let search = webSearchEndpoint - studio.connectMCP(.web, name: BuiltInWebTools.name) { BuiltInWebTools(searchEndpoint: search) } + LabeledContent { + Text("Runs on demand").foregroundStyle(.secondary) + } label: { + Label(BuiltInWebTools.name, systemImage: "globe") } } Section("Custom MCP Servers") { @@ -261,11 +262,27 @@ struct MCPSettings: View { }.buttonStyle(.bordered) ForEach(profiles.keys.sorted(), id: \.self) { name in if let profile = profiles[name] { - connectionRow(.profile(name), title: name, - subtitle: profile.command == nil ? "Streamable HTTP" : "Local stdio", - icon: profile.command == nil ? "network" : "terminal", - local: profile.command != nil) { - studio.connectMCP(.profile(name), name: name) { try profile.makeClient() } + let id = MCPConnectionID.profile(name) + let state = studio.mcpConnections[id] + VStack(alignment: .leading, spacing: 5) { + Toggle(name, isOn: Binding( + get: { studio.enabledMCPProfiles(path: configPath).contains(name) }, + set: { enabled in + if enabled { selected = id } + studio.setMCPProfile(name, enabled: enabled, path: configPath) + } + )) + if let state { + Text(state.progress ?? state.output) + .font(.caption) + .foregroundStyle(state.failed ? Color.red : Color.secondary) + .textSelection(.enabled) + if state.failed { + Button("Retry") { studio.restoreToolsets() } + } else if state.toolset != nil { + Button("Tools") { selected = id } + } + } } } } @@ -439,6 +456,7 @@ struct MCPSettings: View { } profiles = file.mcpServers configPath = url.path + if invalidateProfiles { studio.restoreToolsets() } configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)." } catch { configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)" diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index a91f1d4..7c7f0e9 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -34,6 +34,7 @@ final class StudioModel: ObservableObject { @Published private(set) var knowledgeStacks: [Conversation] = [] @Published private(set) var snippets: [WorkspaceSnippet] = [] @Published private(set) var mcpConnections: [MCPConnectionID: MCPConnectionState] = [:] + private static let enabledProfilesKey = "enabledMCPProfiles" private var mcpOperations: [MCPConnectionID: (id: UUID, task: Task)] = [:] var activeToolsets: [(id: MCPConnectionID, toolset: ActiveToolset)] { @@ -61,6 +62,7 @@ final class StudioModel: ObservableObject { defer { launching = false } reloadRuntimeSettings() guard store == nil else { return } + if databaseURL == nil { restoreToolsets() } if let history = UserDefaults.standard.data(forKey: GenerationMeasurement.key), let saved = try? JSONDecoder().decode([GenerationMeasurement].self, from: history) { measurements = Array(saved.prefix(50)) @@ -238,10 +240,10 @@ final class StudioModel: ObservableObject { if wantsRepositories { webStatus = "Listing Gitea repositories…" do { - let client: any MCPToolClient - if let repositoryClient { client = repositoryClient } - else { client = try await GiteaRepositoryLookup.configuredClient() } - let repositories = try await GiteaRepositoryLookup.references(client: client) + guard let repositoryClient else { + throw StudioError("Enable the Gitea server in Toolbox → MCP Servers and check its connection.") + } + let repositories = try await GiteaRepositoryLookup.references(client: repositoryClient) try Task.checkCancellation() systemParts.append(repositories) webStatus = "Gitea repositories checked." @@ -578,6 +580,41 @@ final class StudioModel: ObservableObject { } extension StudioModel { + func restoreToolsets(defaults: UserDefaults = .standard) { + let endpoint = defaults.string(forKey: "webSearchEndpoint") ?? "" + connectMCP(.web, name: BuiltInWebTools.name) { BuiltInWebTools(searchEndpoint: endpoint) } + guard let path = defaults.string(forKey: "mcpConfigPath"), !path.isEmpty else { return } + let enabled = Set(enabledMCPProfiles(path: path, defaults: defaults)) + for name in enabled { + connectMCP(.profile(name), name: name) { + let file = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path)) + guard let profile = file.mcpServers[name] else { + throw StudioError("This enabled server is missing from the MCP configuration.") + } + return try profile.makeClient() + } + } + } + + func enabledMCPProfiles(path: String, defaults: UserDefaults = .standard) -> [String] { + let saved = defaults.dictionary(forKey: Self.enabledProfilesKey) as? [String: [String]] + return saved?[path] ?? [] + } + + func setMCPProfile(_ name: String, enabled: Bool, path: String, defaults: UserDefaults = .standard) { + var saved = defaults.dictionary(forKey: Self.enabledProfilesKey) as? [String: [String]] ?? [:] + var names = Set(saved[path] ?? []) + if enabled { + names.insert(name) + } else { + names.remove(name) + disconnectMCP(.profile(name)) + } + saved[path] = names.sorted() + defaults.set(saved, forKey: Self.enabledProfilesKey) + if enabled { restoreToolsets(defaults: defaults) } + } + func connectMCP(_ id: MCPConnectionID, name: String, makeClient: @escaping @MainActor () throws -> any MCPToolClient) { guard mcpConnections[id]?.toolset == nil else { return } runMCP(id, progress: "Connecting…") { diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index b54c12c..2e9d738 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -706,6 +706,40 @@ final class MultipleToolsetsTests: XCTestCase { } } + @MainActor + func testStartupRestoresEnabledProfilesAndBuiltInWeb() async throws { + guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_MCP_URLS"]? + .split(separator: ",").first else { throw XCTSkip("Run Scripts/test.sh to start the MCP fixture.") } + let id = UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: id)) + let file = FileManager.default.temporaryDirectory.appending(path: "\(id).json") + defer { + defaults.removePersistentDomain(forName: id) + try? FileManager.default.removeItem(at: file) + } + let profile = ["url": String(endpoint)] + try JSONEncoder().encode(["mcpServers": ["enabled": profile, "unused": profile]]).write(to: file) + defaults.set(file.path, forKey: "mcpConfigPath") + let first = StudioModel() + first.restoreToolsets(defaults: defaults) + try await waitUntil { first.activeToolsets.map(\.id) == [.web] } + first.setMCPProfile("enabled", enabled: true, path: file.path, defaults: defaults) + try await waitUntil { first.mcpConnections[.profile("enabled")]?.toolset != nil } + + let reopened = StudioModel() + reopened.restoreToolsets(defaults: defaults) + try await waitUntil { reopened.activeToolsets.count == 2 } + XCTAssertNotNil(reopened.mcpConnections[.web]?.toolset) + XCTAssertNotNil(reopened.mcpConnections[.profile("enabled")]?.toolset) + XCTAssertNil(reopened.mcpConnections[.profile("unused")]) + + reopened.setMCPProfile("enabled", enabled: false, path: file.path, defaults: defaults) + let afterDisable = StudioModel() + afterDisable.restoreToolsets(defaults: defaults) + try await waitUntil { afterDisable.activeToolsets.map(\.id) == [.web] } + XCTAssertNil(afterDisable.mcpConnections[.profile("enabled")]) + } + @MainActor func testSeparateConnectionsRunCallsAndRetainResultsIndependently() async throws { let studio = StudioModel()