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
+51 -13
View File
@@ -235,12 +235,14 @@ struct ChatView: View {
Button {
showingToolbox = true
} label: {
Label(studio.activeToolset == nil ? "Toolbox" : "1 Active Toolset",
let count = studio.activeToolsets.count
Label(count == 0 ? "Toolbox" : count == 1 ? "1 Active Toolset" : "\(count) Active Toolsets",
systemImage: "wrench.and.screwdriver")
}
.buttonStyle(.bordered)
if let toolset = studio.activeToolset {
Text("\(toolset.name) · \(toolset.tools.count) tools").lineLimit(1).foregroundStyle(.secondary)
if !studio.activeToolsets.isEmpty {
let servers = studio.activeToolsets.map { $0.toolset.name }.joined(separator: ", ")
Text(servers).lineLimit(2).foregroundStyle(.secondary).help(servers)
}
if studio.activeStack != nil || studio.activeSkill != nil ||
studio.activeContext != nil || studio.activeWebClip != nil {
@@ -1221,6 +1223,27 @@ struct ToolboxSheet: View {
struct WorkspaceResourcesView: View {
@Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel
@State private var page: Page? = .stacks
private enum Page: String, CaseIterable, Identifiable {
case stacks = "Knowledge Stacks"
case skills = "Skills"
case contexts = "Contexts"
case prompts = "Prompt Library"
case clips = "Web Clips"
var id: Self { self }
var icon: String {
switch self {
case .stacks: "square.stack.3d.up"
case .skills: "bolt"
case .contexts: "doc.text"
case .prompts: "text.bubble"
case .clips: "link"
}
}
}
var body: some View {
VStack(spacing: 0) {
@@ -1230,18 +1253,29 @@ struct WorkspaceResourcesView: View {
Button("Done") { dismiss() }
}
.padding()
TabView {
KnowledgeStacksView(studio: studio).tabItem { Label("Stacks", systemImage: "square.stack.3d.up") }
WorkspaceSnippetsView(studio: studio, kind: .skill).tabItem { Label("Skills", systemImage: "bolt") }
WorkspaceSnippetsView(studio: studio, kind: .context).tabItem { Label("Contexts", systemImage: "doc.text") }
WorkspaceSnippetsView(studio: studio, kind: .prompt).tabItem { Label("Prompts", systemImage: "text.bubble") }
WorkspaceSnippetsView(studio: studio, kind: .webClip).tabItem { Label("Web Clips", systemImage: "link") }
Divider()
HSplitView {
List(Page.allCases, selection: $page) { entry in
Label(entry.rawValue, systemImage: entry.icon).tag(entry)
}
.listStyle(.sidebar)
.frame(minWidth: 175, idealWidth: 190, maxWidth: 235)
Group {
switch page ?? .stacks {
case .stacks: KnowledgeStacksView(studio: studio)
case .skills: WorkspaceSnippetsView(studio: studio, kind: .skill).id(Page.skills)
case .contexts: WorkspaceSnippetsView(studio: studio, kind: .context).id(Page.contexts)
case .prompts: WorkspaceSnippetsView(studio: studio, kind: .prompt).id(Page.prompts)
case .clips: WorkspaceSnippetsView(studio: studio, kind: .webClip).id(Page.clips)
}
}
.frame(minWidth: 590, maxWidth: .infinity, maxHeight: .infinity)
}
if !studio.workspaceStatus.isEmpty {
Text(studio.workspaceStatus).foregroundStyle(.red).textSelection(.enabled).padding(8)
}
}
.frame(width: 720, height: 560)
.frame(width: 840, height: 570)
}
}
@@ -1259,11 +1293,15 @@ struct KnowledgeStacksView: View {
Form {
Section("Knowledge Stacks") {
HStack {
TextField("New stack name", text: $name)
Button("Create") {
TextField("New stack name", text: $name, prompt: Text("Enter a name for the stack"))
.labelsHidden()
.textFieldStyle(.roundedBorder)
.accessibilityLabel("New stack name")
Button("Create Stack") {
selected = studio.createStack(name.trimmingCharacters(in: .whitespacesAndNewlines))
name = ""
}.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)
}.buttonStyle(.borderedProminent)
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)
}
Picker("Manage stack", selection: $selected) {
Text("Select a stack").tag(UUID?.none)
+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 {
+69 -4
View File
@@ -24,13 +24,21 @@ final class StudioModel: ObservableObject {
@Published var useExternalKnowledge = false
var connectedKnowledge: (any MCPToolClient)? {
guard let activeToolset, activeToolset.tools.contains(where: { $0.name == "search_knowledge" }) else { return nil }
return activeToolset.client
activeToolsets.first(where: { entry in
entry.toolset.tools.contains { $0.name == "search_knowledge" }
})?.toolset.client
}
@Published private(set) var measurements: [GenerationMeasurement] = []
@Published private(set) var knowledgeStacks: [Conversation] = []
@Published private(set) var snippets: [WorkspaceSnippet] = []
@Published var activeToolset: ActiveToolset?
@Published private(set) var mcpConnections: [MCPConnectionID: MCPConnectionState] = [:]
private var mcpOperations: [MCPConnectionID: (id: UUID, task: Task<Void, Never>)] = [:]
var activeToolsets: [(id: MCPConnectionID, toolset: ActiveToolset)] {
mcpConnections.compactMap { id, state in state.toolset.map { (id, $0) } }
.sorted { $0.1.name.localizedStandardCompare($1.1.name) == .orderedAscending }
}
@Published var activeStack: UUID?
@Published var activeSkill: UUID?
@Published var activeContext: UUID?
@@ -171,7 +179,7 @@ final class StudioModel: ObservableObject {
\(toolAttachment.output)
""")
}
let lookup = activeToolset?.client is BuiltInWebTools ? ChatWebLookup(message: text) : nil
let lookup = mcpConnections[.web]?.toolset != nil ? ChatWebLookup(message: text) : nil
let searchEndpoint = UserDefaults.standard.string(forKey: "webSearchEndpoint") ?? ""
try store.save(user, in: chat)
messages.append(user)
@@ -535,3 +543,60 @@ final class StudioModel: ObservableObject {
} catch { status = error.localizedDescription }
}
}
extension StudioModel {
func connectMCP(_ id: MCPConnectionID, name: String, makeClient: @escaping @MainActor () throws -> any MCPToolClient) {
guard mcpConnections[id]?.toolset == nil else { return }
runMCP(id, progress: "Connecting…") {
let client = try makeClient()
let tools = try await client.listTools()
return MCPConnectionState(toolset: ActiveToolset(name: name, client: client, tools: tools),
output: tools.isEmpty ? "The server exposed no tools." : "\(tools.count) tools available.")
}
}
func invokeMCP(_ id: MCPConnectionID, tool: String, arguments: Data, searchEndpoint: String) {
guard let connected = mcpConnections[id]?.toolset, connected.tools.contains(where: { $0.name == tool }) else { return }
runMCP(id, progress: "Running \(tool)…") {
let client: any MCPToolClient = id == .web ? BuiltInWebTools(searchEndpoint: searchEndpoint) : connected.client
let response = try await client.callTool(tool, argumentsJSON: arguments)
return MCPConnectionState(toolset: connected, output: String(decoding: response, as: UTF8.self),
completedTool: tool)
}
}
func disconnectMCP(_ id: MCPConnectionID) {
mcpOperations.removeValue(forKey: id)?.task.cancel()
mcpConnections[id] = nil
if connectedKnowledge == nil { useExternalKnowledge = false }
}
func cancelMCP(_ id: MCPConnectionID) {
mcpOperations[id]?.task.cancel()
}
private func runMCP(
_ id: MCPConnectionID, progress: String,
work: @escaping @MainActor () async throws -> MCPConnectionState
) {
guard mcpOperations[id] == nil else { return }
let before = mcpConnections[id]?.toolset
let operationID = UUID()
mcpConnections[id] = MCPConnectionState(toolset: before, progress: progress)
let task = Task {
let result: MCPConnectionState
do {
let state = try await work()
try Task.checkCancellation()
result = state
} catch {
result = MCPConnectionState(toolset: before, output: Task.isCancelled ? "Cancelled." : error.localizedDescription,
failed: !Task.isCancelled)
}
guard mcpOperations[id]?.id == operationID else { return }
mcpOperations[id] = nil
mcpConnections[id] = result
}
mcpOperations[id] = (operationID, task)
}
}