Start built-in web and reconnect enabled MCP profiles

This commit is contained in:
Mark Gregory
2026-11-16 17:43:02 +00:00
parent a2ccafa613
commit dd06e337fc
4 changed files with 111 additions and 25 deletions
+10 -13
View File
@@ -2,25 +2,22 @@
## Built-in web toolset ## Built-in web toolset
In **Toolbox → MCP Servers**, choose **Connect** on **Built-In Web**. This loads AI Studio registers **Built-In Web** at launch. Its `retrieve_page` and
`retrieve_page` and `web_search` inside AI Studio without launching an MCP `web_search` tools make requests on demand, without an MCP subprocess. Choose a tool, review its JSON input and confirm the call.
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 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 search URL in **Toolbox → Web** to override the default. You can attach returned sources
to the next chat message. to the next chat message.
## Connect an existing server ## Connect an existing server
Open **Toolbox** beside the composer. Choose **Use LM Studio Config** to read Open **Toolbox → MCP Servers**. Choose **Use LM Studio Config** to read
`~/.lmstudio/mcp.json`, or **Import mcp.json** to choose another file. Select `~/.lmstudio/mcp.json`, or **Import mcp.json** to choose another file. Turn on
**Connect** on the row for the server you want. For stdio, choose **Start & the switch beside each server you want to use. It connects immediately and
Connect** to launch the executable and discover tools in one step. Each row reconnects the next time AI Studio opens. Turn the switch off to disconnect it.
shows its own connection status. Multiple servers may stay connected, and
tool calls on different servers can run concurrently. Use **Tools** on a Each server row shows its own status and offers **Retry** after a failed
connected row to open its tool inspector. The composer shows the total connection. Multiple servers can stay connected. Use **Tools** on a connected
number of connected toolsets. The composer shows the connected toolset and its tool row to open its tool inspector. The manual connection form is session-only.
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.
A local profile accepts `command`, an `args` array, `env`, and an optional A local profile accepts `command`, an `args` array, `env`, and an optional
absolute `cwd`. Each argument stays a separate string. No shell interprets the absolute `cwd`. Each argument stays a separate string. No shell interprets the
+26 -8
View File
@@ -243,9 +243,10 @@ struct MCPSettings: View {
HSplitView { HSplitView {
Form { Form {
Section("Built-In Tools") { Section("Built-In Tools") {
connectionRow(.web, title: BuiltInWebTools.name, subtitle: "Retrieve pages and search via SearXNG", icon: "globe") { LabeledContent {
let search = webSearchEndpoint Text("Runs on demand").foregroundStyle(.secondary)
studio.connectMCP(.web, name: BuiltInWebTools.name) { BuiltInWebTools(searchEndpoint: search) } } label: {
Label(BuiltInWebTools.name, systemImage: "globe")
} }
} }
Section("Custom MCP Servers") { Section("Custom MCP Servers") {
@@ -261,11 +262,27 @@ struct MCPSettings: View {
}.buttonStyle(.bordered) }.buttonStyle(.bordered)
ForEach(profiles.keys.sorted(), id: \.self) { name in ForEach(profiles.keys.sorted(), id: \.self) { name in
if let profile = profiles[name] { if let profile = profiles[name] {
connectionRow(.profile(name), title: name, let id = MCPConnectionID.profile(name)
subtitle: profile.command == nil ? "Streamable HTTP" : "Local stdio", let state = studio.mcpConnections[id]
icon: profile.command == nil ? "network" : "terminal", VStack(alignment: .leading, spacing: 5) {
local: profile.command != nil) { Toggle(name, isOn: Binding(
studio.connectMCP(.profile(name), name: name) { try profile.makeClient() } 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 profiles = file.mcpServers
configPath = url.path configPath = url.path
if invalidateProfiles { studio.restoreToolsets() }
configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)." configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)."
} catch { } catch {
configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)" configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)"
+41 -4
View File
@@ -34,6 +34,7 @@ final class StudioModel: ObservableObject {
@Published private(set) var knowledgeStacks: [Conversation] = [] @Published private(set) var knowledgeStacks: [Conversation] = []
@Published private(set) var snippets: [WorkspaceSnippet] = [] @Published private(set) var snippets: [WorkspaceSnippet] = []
@Published private(set) var mcpConnections: [MCPConnectionID: MCPConnectionState] = [:] @Published private(set) var mcpConnections: [MCPConnectionID: MCPConnectionState] = [:]
private static let enabledProfilesKey = "enabledMCPProfiles"
private var mcpOperations: [MCPConnectionID: (id: UUID, task: Task<Void, Never>)] = [:] private var mcpOperations: [MCPConnectionID: (id: UUID, task: Task<Void, Never>)] = [:]
var activeToolsets: [(id: MCPConnectionID, toolset: ActiveToolset)] { var activeToolsets: [(id: MCPConnectionID, toolset: ActiveToolset)] {
@@ -61,6 +62,7 @@ final class StudioModel: ObservableObject {
defer { launching = false } defer { launching = false }
reloadRuntimeSettings() reloadRuntimeSettings()
guard store == nil else { return } guard store == nil else { return }
if databaseURL == nil { restoreToolsets() }
if let history = UserDefaults.standard.data(forKey: GenerationMeasurement.key), if let history = UserDefaults.standard.data(forKey: GenerationMeasurement.key),
let saved = try? JSONDecoder().decode([GenerationMeasurement].self, from: history) { let saved = try? JSONDecoder().decode([GenerationMeasurement].self, from: history) {
measurements = Array(saved.prefix(50)) measurements = Array(saved.prefix(50))
@@ -238,10 +240,10 @@ final class StudioModel: ObservableObject {
if wantsRepositories { if wantsRepositories {
webStatus = "Listing Gitea repositories…" webStatus = "Listing Gitea repositories…"
do { do {
let client: any MCPToolClient guard let repositoryClient else {
if let repositoryClient { client = repositoryClient } throw StudioError("Enable the Gitea server in Toolbox → MCP Servers and check its connection.")
else { client = try await GiteaRepositoryLookup.configuredClient() } }
let repositories = try await GiteaRepositoryLookup.references(client: client) let repositories = try await GiteaRepositoryLookup.references(client: repositoryClient)
try Task.checkCancellation() try Task.checkCancellation()
systemParts.append(repositories) systemParts.append(repositories)
webStatus = "Gitea repositories checked." webStatus = "Gitea repositories checked."
@@ -578,6 +580,41 @@ final class StudioModel: ObservableObject {
} }
extension StudioModel { 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) { func connectMCP(_ id: MCPConnectionID, name: String, makeClient: @escaping @MainActor () throws -> any MCPToolClient) {
guard mcpConnections[id]?.toolset == nil else { return } guard mcpConnections[id]?.toolset == nil else { return }
runMCP(id, progress: "Connecting…") { runMCP(id, progress: "Connecting…") {
+34
View File
@@ -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 @MainActor
func testSeparateConnectionsRunCallsAndRetainResultsIndependently() async throws { func testSeparateConnectionsRunCallsAndRetainResultsIndependently() async throws {
let studio = StudioModel() let studio = StudioModel()