Keep multiple MCP toolsets connected and restore workspace navigation

This commit is contained in:
Mark Gregory
2026-11-16 15:57:58 +00:00
parent 06e3291edb
commit f7b1083f39
8 changed files with 405 additions and 246 deletions
+193 -217
View File
@@ -220,266 +220,229 @@ actor HTTPMCPClient: MCPToolClient {
struct MCPSettings: View {
@ObservedObject var studio: StudioModel
@AppStorage("mcpEndpoint") private var endpoint = ""
@State private var token = ""
@AppStorage("mcpTransport") private var transport = "http"
@AppStorage("mcpExecutable") private var executable = ""
@AppStorage("mcpArguments") private var launchArguments = ""
private var client: (any MCPToolClient)? { studio.activeToolset?.client }
@AppStorage("webSearchEndpoint") private var webSearchEndpoint = ""
@State private var confirmingStartup = false
@AppStorage("mcpConfigPath") private var configPath = ""
@AppStorage("mcpSelectedProfile") private var selectedProfile = ""
@State private var token = ""
@State private var profiles: [String: MCPServerConfiguration] = [:]
@State private var importingConfig = false
@State private var configStatus = ""
@State private var profileErrors: [String: String] = [:]
private var profile: MCPServerConfiguration? { profiles[selectedProfile] }
private var local: Bool { profile.map { $0.command != nil } ?? (transport == "stdio") }
private var target: String { profile?.target ?? (local ? executable : endpoint) }
private var tools: [MCPTool] { studio.activeToolset?.tools ?? [] }
@State private var name = ""
@State private var selected: MCPConnectionID?
@State private var scrollRequest = UUID()
@State private var tool = ""
@State private var arguments = "{}"
@State private var result = ""
@State private var invokedTool: String?
@State private var busy = false
@State private var confirm = false
@State private var operation: Task<Void, Never>?
private var selection: MCPConnectionID? {
if let selected, studio.mcpConnections[selected]?.toolset != nil { return selected }
return studio.activeToolsets.first?.id
}
var body: some View {
Form {
Section("Built-In Tools") {
Button("Activate Web Toolset", action: activateWeb).disabled(busy)
if client is BuiltInWebTools {
LabeledContent("Connection", value: "Active")
Button("Disconnect Web Toolset") { resetConnection() }.disabled(busy)
}
Text("Retrieve pages directly. Search uses the SearXNG endpoint configured in Toolbox → Web.")
.foregroundStyle(.secondary)
}
Section("Custom MCP Servers") {
HStack {
Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") {
let url = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")
loadConfig(url)
}
if !configPath.isEmpty {
Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) }
Button("Edit File") { NSWorkspace.shared.open(URL(fileURLWithPath: configPath)) }
ScrollViewReader { proxy in
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) }
}
}
ForEach(profiles.keys.sorted(), id: \.self) { serverName in
if let entry = profiles[serverName] {
VStack(alignment: .leading, spacing: 6) {
HStack {
Label(serverName, systemImage: entry.command == nil ? "network" : "terminal")
.font(.headline)
Spacer()
if studio.activeToolset?.profileName == serverName {
Text("\(tools.count) tools · Connected").font(.caption).foregroundStyle(.green)
Button("Disconnect") { resetConnection() }.disabled(busy)
} else {
Button(busy && selectedProfile == serverName ? "Connecting…" : "Connect") {
selectedProfile = serverName
if entry.command != nil { confirmingStartup = true; confirm = true }
else { discover() }
}.disabled(busy)
Section("Custom MCP Servers") {
HStack {
Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") {
loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json"))
}
if !configPath.isEmpty {
Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) }
Button("Edit File") { NSWorkspace.shared.open(URL(fileURLWithPath: configPath)) }
}
}.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() }
}
}
}
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
}
Section("Manual Connection") {
DisclosureGroup("Configure a manual connection") {
Picker("Transport", selection: $transport) {
Text("Streamable HTTP").tag("http")
Text("Local stdio").tag("stdio")
}
if transport == "stdio" {
TextField("Executable or command", text: $executable)
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
} else {
TextField("Endpoint", text: $endpoint)
SecureField("Bearer token (optional)", text: $token)
}
connectionRow(.manual, title: "Manual server", subtitle: transport == "stdio" ? executable : endpoint,
icon: "slider.horizontal.3", local: transport == "stdio",
available: transport == "stdio" ? !executable.isEmpty : !endpoint.isEmpty,
connect: connectManual)
}
}
if let selection, let state = studio.mcpConnections[selection], let toolset = state.toolset {
Section("Run a Tool") {
Picker("Connected server", selection: Binding(
get: { self.selection }, set: { selected = $0 }
)) {
ForEach(studio.activeToolsets, id: \.id) { entry in
Text(entry.toolset.name).tag(Optional(entry.id))
}
}
if !toolset.tools.isEmpty {
Picker("Tool", selection: $tool) {
ForEach(toolset.tools, id: \.name) { Text($0.name).tag($0.name) }
}
if let entry = toolset.tools.first(where: { $0.name == tool }) {
if !entry.description.isEmpty { Text(entry.description).foregroundStyle(.secondary) }
DisclosureGroup("Input Schema") {
Text(String(decoding: entry.inputSchemaJSON, as: UTF8.self))
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
}
}
Text(entry.command == nil ? "Streamable HTTP" : "Local stdio")
.font(.caption).foregroundStyle(.secondary)
if let error = profileErrors[serverName] {
Text(error).font(.caption).foregroundStyle(.red).textSelection(.enabled)
TextEditor(text: $arguments).font(.system(.body, design: .monospaced))
.frame(height: 85).accessibilityLabel("JSON arguments")
Button("Review Tool Call…") { confirm = true }
.disabled(tool.isEmpty || state.progress != nil)
}
if !state.output.isEmpty {
ScrollView {
Text(state.output).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: 160)
if let completed = state.completedTool {
Button("Attach Result to Chat") { studio.attachToolResult(name: completed, output: state.output) }
.disabled(studio.running)
}
}
.padding(.vertical, 3)
}
.id("mcp-tool-inspector")
}
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
}
Section("Manual Connection") {
DisclosureGroup("Configure a manual connection") {
Picker("Transport", selection: $transport) {
Text("Streamable HTTP").tag("http")
Text("Local stdio").tag("stdio")
}
if transport == "stdio" {
TextField("Executable path", text: $executable, prompt: Text("/absolute/path/to/server"))
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
.formStyle(.grouped)
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
do { loadConfig(try result.get()) }
catch { configStatus = error.localizedDescription }
}
.onAppear {
if profiles.isEmpty {
if !configPath.isEmpty {
loadConfig(URL(fileURLWithPath: configPath), invalidateProfiles: false)
} else {
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
SecureField("Bearer token (optional)", text: $token)
}
}
HStack {
Button("Connect Manually") {
selectedProfile = ""
if transport == "stdio" { confirmingStartup = true; confirm = true }
else { discover() }
}
.disabled(busy || (transport == "stdio" ? executable.isEmpty : endpoint.isEmpty))
if studio.activeToolset?.profileName == nil && client != nil && !(client is BuiltInWebTools) {
Button("Disconnect") { resetConnection() }.disabled(busy)
}
if busy { Button("Cancel") { operation?.cancel() } }
}
}
if !tools.isEmpty {
Section("Tool invocation") {
Picker("Tool", selection: $name) {
ForEach(tools, id: \.name) { tool in Text(tool.name).tag(tool.name) }
}
if let tool = tools.first(where: { $0.name == name }) {
if !tool.description.isEmpty { Text(tool.description).foregroundStyle(.secondary) }
DisclosureGroup("Input Schema") {
ScrollView {
Text(String(decoding: tool.inputSchemaJSON, as: UTF8.self))
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
}.frame(maxHeight: 100)
let lmStudio = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")
if FileManager.default.fileExists(atPath: lmStudio.path) {
loadConfig(lmStudio, invalidateProfiles: false)
}
}
TextEditor(text: $arguments).font(.system(.body, design: .monospaced))
.frame(height: 80).accessibilityLabel("JSON arguments")
Button("Review Tool Call…") { confirmingStartup = false; confirm = true }.disabled(busy)
}
selectFirstTool()
}
if !result.isEmpty {
Section("Result") {
ScrollView {
Text(result).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: 160)
if let invokedTool {
Button("Attach Result to Active Chat") {
studio.attachToolResult(name: invokedTool, output: result)
self.invokedTool = nil
}
.disabled(studio.selected == nil || studio.running)
.onChange(of: selection) { _, value in
selectFirstTool()
if value != nil { withAnimation { proxy.scrollTo("mcp-tool-inspector", anchor: .bottom) } }
}
.onChange(of: scrollRequest) { _, _ in
withAnimation { proxy.scrollTo("mcp-tool-inspector", anchor: .bottom) }
}
.onChange(of: tool) { _, _ in arguments = "{}" }
.onChange(of: endpoint) { _, _ in studio.disconnectMCP(.manual) }
.onChange(of: transport) { _, _ in studio.disconnectMCP(.manual) }
.onChange(of: executable) { _, _ in studio.disconnectMCP(.manual) }
.onChange(of: launchArguments) { _, _ in studio.disconnectMCP(.manual) }
.onChange(of: token) { _, _ in studio.disconnectMCP(.manual) }
.confirmationDialog("Run \(tool)?", isPresented: $confirm, titleVisibility: .visible) {
Button("Run Tool") {
if let selection {
studio.invokeMCP(selection, tool: tool, arguments: Data(arguments.utf8),
searchEndpoint: webSearchEndpoint)
}
}
}
}
.formStyle(.grouped)
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
do { loadConfig(try result.get()) }
catch { configStatus = error.localizedDescription }
}
.onAppear {
if !configPath.isEmpty { loadConfig(URL(fileURLWithPath: configPath), disconnect: false) }
if !tools.contains(where: { $0.name == name }) { name = tools.first?.name ?? "" }
}
.onChange(of: endpoint) { _, _ in resetConnection() }
.onChange(of: token) { _, _ in resetConnection() }
.onChange(of: name) { _, _ in arguments = "{}" }
.onChange(of: transport) { _, _ in resetConnection() }
.onChange(of: executable) { _, _ in resetConnection() }
.onChange(of: launchArguments) { _, _ in resetConnection() }
.onDisappear { operation?.cancel() }
.confirmationDialog(confirmingStartup ? "Start local MCP server?" : "Run \(name)?",
isPresented: $confirm, titleVisibility: .visible) {
if confirmingStartup { Button("Start and Discover", action: discover) }
else { Button("Run Tool", action: invoke) }
} message: {
if confirmingStartup {
Text("Launch \(target) with its configured arguments using your macOS account.")
} else {
Text("Send these arguments to \(studio.activeToolset?.name ?? target):\n\(arguments.prefix(800))")
} message: {
Text("Send these arguments to \(selection.flatMap { studio.mcpConnections[$0]?.toolset?.name } ?? "the server"):\n\(arguments.prefix(800))")
}
}
}
private func activateWeb() {
run {
let server = BuiltInWebTools(searchEndpoint: webSearchEndpoint)
let discovered = try await server.listTools()
try Task.checkCancellation()
studio.activeToolset = ActiveToolset(name: BuiltInWebTools.name, client: server, tools: discovered)
name = discovered.first?.name ?? ""
result = "\(discovered.count) built-in tools available."
private func connectionRow(
_ id: MCPConnectionID, title: String, subtitle: String, icon: String,
local: Bool = false, available: Bool = true, connect: @escaping () -> Void
) -> some View {
let state = studio.mcpConnections[id]
return VStack(alignment: .leading, spacing: 5) {
HStack {
Label(title, systemImage: icon).font(.headline)
Spacer()
if let progress = state?.progress {
Text(progress).font(.caption).foregroundStyle(.secondary)
Button("Cancel") { studio.cancelMCP(id) }
} else if let toolset = state?.toolset {
Text("\(toolset.tools.count) tools · Connected").font(.caption).foregroundStyle(.green)
Button("Tools") { selected = id; scrollRequest = UUID() }
Button("Disconnect") { studio.disconnectMCP(id) }
} else {
Button(local ? "Start & Connect" : "Connect") {
selected = id
connect()
}.disabled(!available)
}
}.buttonStyle(.bordered)
if !subtitle.isEmpty { Text(subtitle).font(.caption).foregroundStyle(.secondary).lineLimit(1).help(subtitle) }
if state?.toolset == nil, let output = state?.output, !output.isEmpty {
Text(output).font(.caption).foregroundStyle(state?.failed == true ? .red : .secondary)
.textSelection(.enabled)
}
}
.padding(.vertical, 3)
}
private func selectFirstTool() {
tool = selection.flatMap { studio.mcpConnections[$0]?.toolset?.tools.first?.name } ?? ""
arguments = "{}"
}
private func connectManual() {
let command = executable
let args = launchArguments.split(whereSeparator: \.isNewline).map(String.init)
let target = endpoint
let secret = token
let local = transport == "stdio"
studio.connectMCP(.manual, name: "Manual MCP") {
if local { return try StdioMCPClient(path: command, arguments: args) }
return try HTTPMCPClient(endpoint: target, token: secret)
}
}
private func loadConfig(_ url: URL, disconnect: Bool = true) {
private func loadConfig(_ url: URL, invalidateProfiles: Bool = true) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let file = try MCPServerConfiguration.File.read(url)
if disconnect { resetConnection() }
profiles = file.mcpServers
profileErrors = [:]
configPath = url.path
if profiles[selectedProfile] == nil && (disconnect || !selectedProfile.isEmpty) {
let names = profiles.keys.sorted()
selectedProfile = names.first { name in
guard let profile = profiles[name] else { return false }
return (try? profile.makeClient()) != nil
} ?? names.first ?? ""
if invalidateProfiles {
for id in Array(studio.mcpConnections.keys) {
if case .profile(let name) = id,
configPath != url.path || profiles[name] != file.mcpServers[name] {
studio.disconnectMCP(id)
}
}
}
profiles = file.mcpServers
configPath = url.path
configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)."
} catch {
configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)"
}
}
private func discover() {
let profileName = profile == nil ? nil : selectedProfile
if let profileName { profileErrors[profileName] = nil }
run(profileName: profileName) {
let server: any MCPToolClient
if let profile {
server = try profile.makeClient()
} else if local {
let args = launchArguments.split(whereSeparator: \.isNewline).map(String.init)
server = try StdioMCPClient(path: executable, arguments: args)
} else {
server = try HTTPMCPClient(endpoint: endpoint, token: token)
}
let discovered = try await server.listTools()
try Task.checkCancellation()
studio.activeToolset = ActiveToolset(name: profile == nil ? target : selectedProfile,
client: server, tools: discovered, profileName: profileName)
name = discovered.first?.name ?? ""
result = discovered.isEmpty ? "This server has no exposed tools." : "\(discovered.count) tools discovered."
}
}
private func invoke() {
guard let client, !name.isEmpty else { return }
let tool = name
let data = Data(arguments.utf8)
let configuredClient: any MCPToolClient = client is BuiltInWebTools
? BuiltInWebTools(searchEndpoint: webSearchEndpoint) : client
run {
let output = try await configuredClient.callTool(tool, argumentsJSON: data)
try Task.checkCancellation()
result = String(decoding: output, as: UTF8.self)
invokedTool = tool
}
}
private func resetConnection(cancel: Bool = true) {
if cancel { operation?.cancel() }
studio.activeToolset = nil
name = ""
invokedTool = nil
result = ""
}
private func run(profileName: String? = nil, _ work: @escaping @MainActor () async throws -> Void) {
guard !busy else { return }
busy = true
result = ""
invokedTool = nil
operation = Task {
defer { busy = false; operation = nil }
do { try await work() }
catch {
if let profileName, !Task.isCancelled { profileErrors[profileName] = error.localizedDescription }
else { result = Task.isCancelled ? "Cancelled" : error.localizedDescription }
}
}
}
}
actor StdioMCPClient: MCPToolClient {
@@ -694,7 +657,7 @@ private final class StdioTransport: @unchecked Sendable {
}
}
struct MCPServerConfiguration: Decodable {
struct MCPServerConfiguration: Decodable, Equatable {
let command: String?
let args: [String]?
let env: [String: String]?
@@ -804,7 +767,20 @@ struct ActiveToolset {
let name: String
let client: any MCPToolClient
let tools: [MCPTool]
var profileName: String? = nil
}
enum MCPConnectionID: Hashable {
case web
case manual
case profile(String)
}
struct MCPConnectionState {
var toolset: ActiveToolset? = nil
var progress: String? = nil
var output = ""
var completedTool: String? = nil
var failed = false
}
struct BuiltInWebTools: MCPToolClient {