Build AI Studio 1.1 for macOS #1

Open
admin wants to merge 38 commits from admin/ai-studio-v1.1 AGit into main
8 changed files with 405 additions and 246 deletions
Showing only changes of commit f7b1083f39 - Show all commits
+8 -6
View File
@@ -2,7 +2,7 @@
## Built-in web toolset ## 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 `retrieve_page` and `web_search` inside AI Studio without launching 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 uses the SearXNG 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 Open **Toolbox** beside the composer. 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. Select
**Connect** on the row for the server you want. For stdio, review and **Connect** on the row for the server you want. For stdio, choose **Start &
confirm process startup. The row shows the tool count or its own connection Connect** to launch the executable and discover tools in one step. Each row
error. The composer shows the connected toolset and its tool shows its own connection status. Multiple servers may stay connected, and
count. The connection stays active when you close Toolbox. Use **Disconnect** tool calls on different servers can run concurrently. Use **Tools** on a
to end it. AI Studio remembers the configuration file and the selected 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. 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
+8
View File
@@ -114,3 +114,11 @@ links including the live Laravel homepage and handles explicit SearXNG
searches. Verified Ollama model listing, MLX discovery, local vector counts searches. Verified Ollama model listing, MLX discovery, local vector counts
and a Chroma/MCP query fixture. Added eight theme palettes. The Debug build and a Chroma/MCP query fixture. Added eight theme palettes. The Debug build
passed, with 44 tests passing and one opt-in download skipped. 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.
+6 -5
View File
@@ -17,11 +17,11 @@ Chat history, older-message recall, and document indexes live in `~/Library/Appl
## 3. Run a tool ## 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 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 server executable, and add one argument per line. Choose **Start & Connect** to start the server and discover its tools.
Discover…** and confirm. Use **Disconnect** to stop the subprocess. Local Use **Disconnect** on that row to stop the subprocess. Local
stdio supports the MCP initialization handshake used by the 2024 and 2025 stdio supports the MCP initialization handshake used by the 2024 and 2025
protocol revisions. 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 Retrieval extracts text from UTF-8 HTML and plain-text pages without
running page scripts. It keeps the final source URL. Attach an individual running page scripts. It keeps the final source URL. Attach an individual
result or a retrieved page to your next message after reviewing it. 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 Choose **Connect** on **Built-In Web** in the **MCP Servers** tab to access
operations through the Toolbox tool list. With Built-In Web active, chat retrieves 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 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 request. Use `/search your query` or `Search the web for your query` to search
from chat using the configured SearXNG endpoint. from chat using the configured SearXNG endpoint.
+1 -1
View File
@@ -19,5 +19,5 @@ xcodebuild ARCHS=arm64 CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_T
app="$base/Derived/Build/Products/$configuration/AIStudio.app" app="$base/Derived/Build/Products/$configuration/AIStudio.app"
printf 'App: %s\n' "$app" printf 'App: %s\n' "$app"
if [[ "$launch" != "--no-launch" ]]; then if [[ "$launch" != "--no-launch" ]]; then
open "$app" open -n "$app"
fi fi
+51 -13
View File
@@ -235,12 +235,14 @@ struct ChatView: View {
Button { Button {
showingToolbox = true showingToolbox = true
} label: { } 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") systemImage: "wrench.and.screwdriver")
} }
.buttonStyle(.bordered) .buttonStyle(.bordered)
if let toolset = studio.activeToolset { if !studio.activeToolsets.isEmpty {
Text("\(toolset.name) · \(toolset.tools.count) tools").lineLimit(1).foregroundStyle(.secondary) 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 || if studio.activeStack != nil || studio.activeSkill != nil ||
studio.activeContext != nil || studio.activeWebClip != nil { studio.activeContext != nil || studio.activeWebClip != nil {
@@ -1221,6 +1223,27 @@ struct ToolboxSheet: View {
struct WorkspaceResourcesView: View { struct WorkspaceResourcesView: View {
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
@ObservedObject var studio: StudioModel @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 { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
@@ -1230,18 +1253,29 @@ struct WorkspaceResourcesView: View {
Button("Done") { dismiss() } Button("Done") { dismiss() }
} }
.padding() .padding()
TabView { Divider()
KnowledgeStacksView(studio: studio).tabItem { Label("Stacks", systemImage: "square.stack.3d.up") } HSplitView {
WorkspaceSnippetsView(studio: studio, kind: .skill).tabItem { Label("Skills", systemImage: "bolt") } List(Page.allCases, selection: $page) { entry in
WorkspaceSnippetsView(studio: studio, kind: .context).tabItem { Label("Contexts", systemImage: "doc.text") } Label(entry.rawValue, systemImage: entry.icon).tag(entry)
WorkspaceSnippetsView(studio: studio, kind: .prompt).tabItem { Label("Prompts", systemImage: "text.bubble") } }
WorkspaceSnippetsView(studio: studio, kind: .webClip).tabItem { Label("Web Clips", systemImage: "link") } .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 { if !studio.workspaceStatus.isEmpty {
Text(studio.workspaceStatus).foregroundStyle(.red).textSelection(.enabled).padding(8) 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 { Form {
Section("Knowledge Stacks") { Section("Knowledge Stacks") {
HStack { HStack {
TextField("New stack name", text: $name) TextField("New stack name", text: $name, prompt: Text("Enter a name for the stack"))
Button("Create") { .labelsHidden()
.textFieldStyle(.roundedBorder)
.accessibilityLabel("New stack name")
Button("Create Stack") {
selected = studio.createStack(name.trimmingCharacters(in: .whitespacesAndNewlines)) selected = studio.createStack(name.trimmingCharacters(in: .whitespacesAndNewlines))
name = "" name = ""
}.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy) }.buttonStyle(.borderedProminent)
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)
} }
Picker("Manage stack", selection: $selected) { Picker("Manage stack", selection: $selected) {
Text("Select a stack").tag(UUID?.none) Text("Select a stack").tag(UUID?.none)
+157 -181
View File
@@ -220,80 +220,54 @@ actor HTTPMCPClient: MCPToolClient {
struct MCPSettings: View { struct MCPSettings: View {
@ObservedObject var studio: StudioModel @ObservedObject var studio: StudioModel
@AppStorage("mcpEndpoint") private var endpoint = "" @AppStorage("mcpEndpoint") private var endpoint = ""
@State private var token = ""
@AppStorage("mcpTransport") private var transport = "http" @AppStorage("mcpTransport") private var transport = "http"
@AppStorage("mcpExecutable") private var executable = "" @AppStorage("mcpExecutable") private var executable = ""
@AppStorage("mcpArguments") private var launchArguments = "" @AppStorage("mcpArguments") private var launchArguments = ""
private var client: (any MCPToolClient)? { studio.activeToolset?.client }
@AppStorage("webSearchEndpoint") private var webSearchEndpoint = "" @AppStorage("webSearchEndpoint") private var webSearchEndpoint = ""
@State private var confirmingStartup = false
@AppStorage("mcpConfigPath") private var configPath = "" @AppStorage("mcpConfigPath") private var configPath = ""
@AppStorage("mcpSelectedProfile") private var selectedProfile = "" @State private var token = ""
@State private var profiles: [String: MCPServerConfiguration] = [:] @State private var profiles: [String: MCPServerConfiguration] = [:]
@State private var importingConfig = false @State private var importingConfig = false
@State private var configStatus = "" @State private var configStatus = ""
@State private var profileErrors: [String: String] = [:] @State private var selected: MCPConnectionID?
@State private var scrollRequest = UUID()
private var profile: MCPServerConfiguration? { profiles[selectedProfile] } @State private var tool = ""
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 arguments = "{}" @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 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 { var body: some View {
ScrollViewReader { proxy in
Form { Form {
Section("Built-In Tools") { Section("Built-In Tools") {
Button("Activate Web Toolset", action: activateWeb).disabled(busy) connectionRow(.web, title: BuiltInWebTools.name, subtitle: "Retrieve pages and search via SearXNG", icon: "globe") {
if client is BuiltInWebTools { let search = webSearchEndpoint
LabeledContent("Connection", value: "Active") studio.connectMCP(.web, name: BuiltInWebTools.name) { BuiltInWebTools(searchEndpoint: search) }
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") { Section("Custom MCP Servers") {
HStack { HStack {
Button("Import mcp.json…") { importingConfig = true } Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") { Button("Use LM Studio Config") {
let url = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json") loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json"))
loadConfig(url)
} }
if !configPath.isEmpty { if !configPath.isEmpty {
Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) } Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) }
Button("Edit File") { NSWorkspace.shared.open(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) } if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
@@ -305,60 +279,56 @@ struct MCPSettings: View {
Text("Local stdio").tag("stdio") Text("Local stdio").tag("stdio")
} }
if transport == "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) TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
} else { } else {
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp")) TextField("Endpoint", text: $endpoint)
SecureField("Bearer token (optional)", text: $token) SecureField("Bearer token (optional)", text: $token)
} }
} connectionRow(.manual, title: "Manual server", subtitle: transport == "stdio" ? executable : endpoint,
HStack { icon: "slider.horizontal.3", local: transport == "stdio",
Button("Connect Manually") { available: transport == "stdio" ? !executable.isEmpty : !endpoint.isEmpty,
selectedProfile = "" connect: connectManual)
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 { if let selection, let state = studio.mcpConnections[selection], let toolset = state.toolset {
Section("Tool invocation") { Section("Run a Tool") {
Picker("Tool", selection: $name) { Picker("Connected server", selection: Binding(
ForEach(tools, id: \.name) { tool in Text(tool.name).tag(tool.name) } 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") { DisclosureGroup("Input Schema") {
ScrollView { Text(String(decoding: entry.inputSchemaJSON, as: UTF8.self))
Text(String(decoding: tool.inputSchemaJSON, as: UTF8.self))
.font(.system(.caption, design: .monospaced)).textSelection(.enabled) .font(.system(.caption, design: .monospaced)).textSelection(.enabled)
}.frame(maxHeight: 100)
} }
} }
TextEditor(text: $arguments).font(.system(.body, design: .monospaced)) TextEditor(text: $arguments).font(.system(.body, design: .monospaced))
.frame(height: 80).accessibilityLabel("JSON arguments") .frame(height: 85).accessibilityLabel("JSON arguments")
Button("Review Tool Call…") { confirmingStartup = false; confirm = true }.disabled(busy) Button("Review Tool Call…") { confirm = true }
.disabled(tool.isEmpty || state.progress != nil)
} }
} if !state.output.isEmpty {
if !result.isEmpty {
Section("Result") {
ScrollView { 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(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: 160) }.frame(maxHeight: 160)
if let invokedTool { if let completed = state.completedTool {
Button("Attach Result to Active Chat") { Button("Attach Result to Chat") { studio.attachToolResult(name: completed, output: state.output) }
studio.attachToolResult(name: invokedTool, output: result) .disabled(studio.running)
self.invokedTool = nil
}
.disabled(studio.selected == nil || studio.running)
} }
} }
} }
.id("mcp-tool-inspector")
}
} }
.formStyle(.grouped) .formStyle(.grouped)
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in .fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
@@ -366,120 +336,113 @@ struct MCPSettings: View {
catch { configStatus = error.localizedDescription } catch { configStatus = error.localizedDescription }
} }
.onAppear { .onAppear {
if !configPath.isEmpty { loadConfig(URL(fileURLWithPath: configPath), disconnect: false) } if profiles.isEmpty {
if !tools.contains(where: { $0.name == name }) { name = tools.first?.name ?? "" } if !configPath.isEmpty {
} loadConfig(URL(fileURLWithPath: configPath), invalidateProfiles: false)
.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 { } 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() { private func connectionRow(
run { _ id: MCPConnectionID, title: String, subtitle: String, icon: String,
let server = BuiltInWebTools(searchEndpoint: webSearchEndpoint) local: Bool = false, available: Bool = true, connect: @escaping () -> Void
let discovered = try await server.listTools() ) -> some View {
try Task.checkCancellation() let state = studio.mcpConnections[id]
studio.activeToolset = ActiveToolset(name: BuiltInWebTools.name, client: server, tools: discovered) return VStack(alignment: .leading, spacing: 5) {
name = discovered.first?.name ?? "" HStack {
result = "\(discovered.count) built-in tools available." 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() let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } } defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do { do {
let file = try MCPServerConfiguration.File.read(url) let file = try MCPServerConfiguration.File.read(url)
if disconnect { resetConnection() } if invalidateProfiles {
profiles = file.mcpServers for id in Array(studio.mcpConnections.keys) {
profileErrors = [:] if case .profile(let name) = id,
configPath = url.path configPath != url.path || profiles[name] != file.mcpServers[name] {
if profiles[selectedProfile] == nil && (disconnect || !selectedProfile.isEmpty) { studio.disconnectMCP(id)
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 ?? ""
} }
}
}
profiles = file.mcpServers
configPath = url.path
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)"
} }
} }
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 { actor StdioMCPClient: MCPToolClient {
@@ -694,7 +657,7 @@ private final class StdioTransport: @unchecked Sendable {
} }
} }
struct MCPServerConfiguration: Decodable { struct MCPServerConfiguration: Decodable, Equatable {
let command: String? let command: String?
let args: [String]? let args: [String]?
let env: [String: String]? let env: [String: String]?
@@ -804,7 +767,20 @@ struct ActiveToolset {
let name: String let name: String
let client: any MCPToolClient let client: any MCPToolClient
let tools: [MCPTool] 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 { struct BuiltInWebTools: MCPToolClient {
+69 -4
View File
@@ -24,13 +24,21 @@ final class StudioModel: ObservableObject {
@Published var useExternalKnowledge = false @Published var useExternalKnowledge = false
var connectedKnowledge: (any MCPToolClient)? { var connectedKnowledge: (any MCPToolClient)? {
guard let activeToolset, activeToolset.tools.contains(where: { $0.name == "search_knowledge" }) else { return nil } activeToolsets.first(where: { entry in
return activeToolset.client entry.toolset.tools.contains { $0.name == "search_knowledge" }
})?.toolset.client
} }
@Published private(set) var measurements: [GenerationMeasurement] = [] @Published private(set) var measurements: [GenerationMeasurement] = []
@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 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 activeStack: UUID?
@Published var activeSkill: UUID? @Published var activeSkill: UUID?
@Published var activeContext: UUID? @Published var activeContext: UUID?
@@ -171,7 +179,7 @@ final class StudioModel: ObservableObject {
\(toolAttachment.output) \(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") ?? "" let searchEndpoint = UserDefaults.standard.string(forKey: "webSearchEndpoint") ?? ""
try store.save(user, in: chat) try store.save(user, in: chat)
messages.append(user) messages.append(user)
@@ -535,3 +543,60 @@ final class StudioModel: ObservableObject {
} catch { status = error.localizedDescription } } 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)
}
}
+69
View File
@@ -672,3 +672,72 @@ final class ToolboxRepairTests: XCTestCase {
XCTAssertTrue(context.contains("source: notes.md")) 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())
}
}