Keep multiple MCP toolsets connected and restore workspace navigation
This commit is contained in:
+8
-6
@@ -2,7 +2,7 @@
|
||||
|
||||
## Built-in web toolset
|
||||
|
||||
In **Toolbox → MCP Servers**, choose **Activate Web Toolset**. This loads
|
||||
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.
|
||||
Page retrieval takes a `url`. Search takes a `query` and uses the SearXNG
|
||||
@@ -13,11 +13,13 @@ to the next chat message.
|
||||
|
||||
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, review and
|
||||
confirm process startup. The row shows the tool count or its own connection
|
||||
error. The composer shows the connected toolset and its tool
|
||||
count. The connection stays active when you close Toolbox. Use **Disconnect**
|
||||
to end it. AI Studio remembers the configuration file and the selected
|
||||
**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.
|
||||
|
||||
A local profile accepts `command`, an `args` array, `env`, and an optional
|
||||
|
||||
@@ -114,3 +114,11 @@ links including the live Laravel homepage and handles explicit SearXNG
|
||||
searches. Verified Ollama model listing, MLX discovery, local vector counts
|
||||
and a Chroma/MCP query fixture. Added eight theme palettes. The Debug build
|
||||
passed, with 44 tests passing and one opt-in download skipped.
|
||||
|
||||
**16 November 2026.** Workspace navigation now uses full sidebar labels.
|
||||
Toolbox keeps each MCP server connected independently with one-step
|
||||
connection and per-server call progress, cancellation and results.
|
||||
Built-In Web, Local Knowledge, and Gitea stayed connected together in a
|
||||
live discovery test. Separate calls overlapped in the concurrency test.
|
||||
The Debug build launched a fresh instance. 44 tests passed and three
|
||||
opt-in inference checks were skipped.
|
||||
|
||||
@@ -17,11 +17,11 @@ Chat history, older-message recall, and document indexes live in `~/Library/Appl
|
||||
|
||||
## 3. Run a tool
|
||||
|
||||
Open **Toolbox**, enter an MCP HTTP endpoint, and choose **Discover Tools**. Select a tool, review the schema, enter its JSON arguments, and confirm the invocation. You can attach up to 8,000 characters of the result to the next message in the active conversation. The composer shows the attachment before it is sent.
|
||||
Open **Toolbox**, enter an MCP HTTP endpoint, and choose **Connect**. Select a tool, review the schema, enter its JSON arguments, and confirm the invocation. You can attach up to 8,000 characters of the result to the next message in the active conversation. The composer shows the attachment before it is sent.
|
||||
|
||||
For a local subprocess, select **Local stdio**, enter the full path of the
|
||||
server executable, and add one argument per line. Choose **Start Server and
|
||||
Discover…** and confirm. Use **Disconnect** to stop the subprocess. Local
|
||||
server executable, and add one argument per line. Choose **Start & Connect** to start the server and discover its tools.
|
||||
Use **Disconnect** on that row to stop the subprocess. Local
|
||||
stdio supports the MCP initialization handshake used by the 2024 and 2025
|
||||
protocol revisions.
|
||||
|
||||
@@ -94,8 +94,9 @@ open a browser search and paste the chosen URL into **Retrieve Page**.
|
||||
Retrieval extracts text from UTF-8 HTML and plain-text pages without
|
||||
running page scripts. It keeps the final source URL. Attach an individual
|
||||
result or a retrieved page to your next message after reviewing it.
|
||||
Choose **Activate Web Toolset** in the **MCP Servers** tab to access the same
|
||||
operations through the Toolbox tool list. With Built-In Web active, chat retrieves
|
||||
Choose **Connect** on **Built-In Web** in the **MCP Servers** tab to access
|
||||
the same operations through Toolbox. Web and custom MCP servers can stay
|
||||
connected at the same time. With Built-In Web active, chat retrieves
|
||||
up to two explicitly typed HTTP(S) URLs and adds their source text to the
|
||||
request. Use `/search your query` or `Search the web for your query` to search
|
||||
from chat using the configured SearXNG endpoint.
|
||||
|
||||
+1
-1
@@ -19,5 +19,5 @@ xcodebuild ARCHS=arm64 CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_T
|
||||
app="$base/Derived/Build/Products/$configuration/AIStudio.app"
|
||||
printf 'App: %s\n' "$app"
|
||||
if [[ "$launch" != "--no-launch" ]]; then
|
||||
open "$app"
|
||||
open -n "$app"
|
||||
fi
|
||||
|
||||
+51
-13
@@ -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)
|
||||
|
||||
+157
-181
@@ -220,80 +220,54 @@ 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 {
|
||||
ScrollViewReader { proxy in
|
||||
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)
|
||||
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) }
|
||||
}
|
||||
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)
|
||||
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() }
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 3)
|
||||
}
|
||||
}
|
||||
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
|
||||
@@ -305,60 +279,56 @@ struct MCPSettings: View {
|
||||
Text("Local stdio").tag("stdio")
|
||||
}
|
||||
if transport == "stdio" {
|
||||
TextField("Executable path", text: $executable, prompt: Text("/absolute/path/to/server"))
|
||||
TextField("Executable or command", text: $executable)
|
||||
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
|
||||
} else {
|
||||
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
|
||||
TextField("Endpoint", text: $endpoint)
|
||||
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() } }
|
||||
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 !tools.isEmpty {
|
||||
Section("Tool invocation") {
|
||||
Picker("Tool", selection: $name) {
|
||||
ForEach(tools, id: \.name) { tool in Text(tool.name).tag(tool.name) }
|
||||
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 let tool = tools.first(where: { $0.name == name }) {
|
||||
if !tool.description.isEmpty { Text(tool.description).foregroundStyle(.secondary) }
|
||||
}
|
||||
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") {
|
||||
ScrollView {
|
||||
Text(String(decoding: tool.inputSchemaJSON, as: UTF8.self))
|
||||
Text(String(decoding: entry.inputSchemaJSON, as: UTF8.self))
|
||||
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||
}.frame(maxHeight: 100)
|
||||
}
|
||||
}
|
||||
TextEditor(text: $arguments).font(.system(.body, design: .monospaced))
|
||||
.frame(height: 80).accessibilityLabel("JSON arguments")
|
||||
Button("Review Tool Call…") { confirmingStartup = false; confirm = true }.disabled(busy)
|
||||
.frame(height: 85).accessibilityLabel("JSON arguments")
|
||||
Button("Review Tool Call…") { confirm = true }
|
||||
.disabled(tool.isEmpty || state.progress != nil)
|
||||
}
|
||||
}
|
||||
if !result.isEmpty {
|
||||
Section("Result") {
|
||||
if !state.output.isEmpty {
|
||||
ScrollView {
|
||||
Text(result).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||
Text(state.output).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)
|
||||
if let completed = state.completedTool {
|
||||
Button("Attach Result to Chat") { studio.attachToolResult(name: completed, output: state.output) }
|
||||
.disabled(studio.running)
|
||||
}
|
||||
}
|
||||
}
|
||||
.id("mcp-tool-inspector")
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
|
||||
@@ -366,120 +336,113 @@ struct MCPSettings: View {
|
||||
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.")
|
||||
if profiles.isEmpty {
|
||||
if !configPath.isEmpty {
|
||||
loadConfig(URL(fileURLWithPath: configPath), invalidateProfiles: false)
|
||||
} else {
|
||||
Text("Send these arguments to \(studio.activeToolset?.name ?? target):\n\(arguments.prefix(800))")
|
||||
let lmStudio = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")
|
||||
if FileManager.default.fileExists(atPath: lmStudio.path) {
|
||||
loadConfig(lmStudio, invalidateProfiles: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
selectFirstTool()
|
||||
}
|
||||
.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)
|
||||
}
|
||||
}
|
||||
} 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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -672,3 +672,72 @@ final class ToolboxRepairTests: XCTestCase {
|
||||
XCTAssertTrue(context.contains("source: notes.md"))
|
||||
}
|
||||
}
|
||||
|
||||
final class MultipleToolsetsTests: XCTestCase {
|
||||
private struct MockClient: MCPToolClient {
|
||||
let identifier: String
|
||||
|
||||
func listTools() async throws -> [MCPTool] {
|
||||
[MCPTool(name: "echo", description: "", inputSchemaJSON: Data("{}".utf8))]
|
||||
}
|
||||
|
||||
func callTool(_ name: String, argumentsJSON: Data) async throws -> Data {
|
||||
try await Task.sleep(for: .milliseconds(150))
|
||||
return Data(identifier.utf8)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testSeparateConnectionsRunCallsAndRetainResultsIndependently() async throws {
|
||||
let studio = StudioModel()
|
||||
let first = MCPConnectionID.profile("First")
|
||||
let second = MCPConnectionID.profile("Second")
|
||||
studio.connectMCP(first, name: "First") { MockClient(identifier: "first result") }
|
||||
studio.connectMCP(second, name: "Second") { MockClient(identifier: "second result") }
|
||||
try await waitUntil { studio.activeToolsets.count == 2 }
|
||||
studio.invokeMCP(first, tool: "echo", arguments: Data("{}".utf8), searchEndpoint: "")
|
||||
studio.invokeMCP(second, tool: "echo", arguments: Data("{}".utf8), searchEndpoint: "")
|
||||
XCTAssertNotNil(studio.mcpConnections[first]?.progress)
|
||||
XCTAssertNotNil(studio.mcpConnections[second]?.progress)
|
||||
try await waitUntil {
|
||||
studio.mcpConnections[first]?.completedTool == "echo" &&
|
||||
studio.mcpConnections[second]?.completedTool == "echo"
|
||||
}
|
||||
XCTAssertEqual(studio.mcpConnections[first]?.output, "first result")
|
||||
XCTAssertEqual(studio.mcpConnections[second]?.output, "second result")
|
||||
studio.disconnectMCP(first)
|
||||
XCTAssertNil(studio.mcpConnections[first])
|
||||
XCTAssertEqual(studio.activeToolsets.map(\.id), [second])
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testInstalledServersAndBuiltInWebCanStayConnectedTogether() async throws {
|
||||
let env = ProcessInfo.processInfo.environment
|
||||
guard let path = env["AISTUDIO_TEST_REAL_MCP_CONFIG"], env["AISTUDIO_TEST_REAL_GITEA"] == "1" else {
|
||||
throw XCTSkip("Enable the installed MCP profiles smoke test explicitly.")
|
||||
}
|
||||
let config = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path))
|
||||
let studio = StudioModel()
|
||||
for name in ["absdev-gitea", "local-knowledge"] {
|
||||
let profile = try XCTUnwrap(config.mcpServers[name])
|
||||
studio.connectMCP(.profile(name), name: name) { try profile.makeClient() }
|
||||
}
|
||||
studio.connectMCP(.web, name: BuiltInWebTools.name) { BuiltInWebTools(searchEndpoint: "") }
|
||||
try await waitUntil { studio.activeToolsets.count == 3 }
|
||||
XCTAssertNotNil(studio.connectedKnowledge)
|
||||
studio.disconnectMCP(.profile("absdev-gitea"))
|
||||
XCTAssertNotNil(studio.mcpConnections[.web]?.toolset)
|
||||
XCTAssertNotNil(studio.connectedKnowledge)
|
||||
studio.disconnectMCP(.profile("local-knowledge"))
|
||||
studio.disconnectMCP(.web)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func waitUntil(_ condition: @escaping () -> Bool) async throws {
|
||||
let deadline = ContinuousClock.now + .seconds(5)
|
||||
while !condition(), ContinuousClock.now < deadline {
|
||||
try await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
XCTAssertTrue(condition())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user