Add custom MCP profiles and reusable workspace libraries
This commit is contained in:
+233
-35
@@ -1,6 +1,8 @@
|
||||
import Foundation
|
||||
import Darwin
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
actor HTTPMCPClient: MCPToolClient {
|
||||
private struct Connection {
|
||||
@@ -19,12 +21,13 @@ actor HTTPMCPClient: MCPToolClient {
|
||||
|
||||
private let endpoint: URL
|
||||
private let token: String
|
||||
private let headers: [String: String]
|
||||
private let session: URLSession
|
||||
private var connection: Connection?
|
||||
private static let modern = "2026-07-28"
|
||||
private let versions = ["2025-11-25", "2025-06-18", "2025-03-26"]
|
||||
|
||||
init(endpoint: String, token: String = "") throws {
|
||||
init(endpoint: String, token: String = "", headers: [String: String] = [:]) throws {
|
||||
guard let parsed = URLComponents(string: endpoint.trimmingCharacters(in: .whitespacesAndNewlines)),
|
||||
let host = parsed.host?.lowercased(), !host.isEmpty,
|
||||
parsed.user == nil, parsed.password == nil, parsed.fragment == nil, let url = parsed.url else {
|
||||
@@ -37,6 +40,13 @@ actor HTTPMCPClient: MCPToolClient {
|
||||
guard !token.contains(where: \.isNewline) else { throw StudioError("The bearer token must be a single line.") }
|
||||
self.endpoint = url
|
||||
self.token = token
|
||||
self.headers = headers
|
||||
let protected = Set(["host", "content-length", "transfer-encoding", "connection", "content-type",
|
||||
"accept", "mcp-protocol-version", "mcp-session-id", "mcp-method", "mcp-name"])
|
||||
guard headers.allSatisfy({ name, value in
|
||||
guard !name.isEmpty, !protected.contains(name.lowercased()), !value.contains(where: \.isNewline) else { return false }
|
||||
return name.utf8.allSatisfy { (33...126).contains($0) && $0 != 58 }
|
||||
}) else { throw StudioError("A custom MCP HTTP header has an invalid or reserved name or value.") }
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.timeoutIntervalForRequest = 30
|
||||
config.timeoutIntervalForResource = 120
|
||||
@@ -151,6 +161,7 @@ actor HTTPMCPClient: MCPToolClient {
|
||||
request.setValue(params["name"] as? String, forHTTPHeaderField: "Mcp-Name")
|
||||
}
|
||||
}
|
||||
for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }
|
||||
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
||||
let (bytes, response) = try await session.bytes(for: request)
|
||||
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
|
||||
@@ -213,9 +224,18 @@ struct MCPSettings: View {
|
||||
@AppStorage("mcpTransport") private var transport = "http"
|
||||
@AppStorage("mcpExecutable") private var executable = ""
|
||||
@AppStorage("mcpArguments") private var launchArguments = ""
|
||||
@State private var client: (any MCPToolClient)?
|
||||
private var client: (any MCPToolClient)? { studio.activeToolset?.client }
|
||||
@State private var confirmLaunch = false
|
||||
@State private var tools: [MCPTool] = []
|
||||
@AppStorage("mcpConfigPath") private var configPath = ""
|
||||
@AppStorage("mcpSelectedProfile") private var selectedProfile = ""
|
||||
@State private var profiles: [String: MCPServerConfiguration] = [:]
|
||||
@State private var importingConfig = false
|
||||
@State private var configStatus = ""
|
||||
|
||||
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 arguments = "{}"
|
||||
@State private var result = ""
|
||||
@@ -226,24 +246,49 @@ struct MCPSettings: View {
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section("MCP server") {
|
||||
Picker("Transport", selection: $transport) {
|
||||
Text("Streamable HTTP").tag("http")
|
||||
Text("Local stdio").tag("stdio")
|
||||
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)) }
|
||||
}
|
||||
}
|
||||
if transport == "stdio" {
|
||||
TextField("Executable path", text: $executable, prompt: Text("/absolute/path/to/server"))
|
||||
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
|
||||
if !profiles.isEmpty {
|
||||
Picker("Server", selection: $selectedProfile) {
|
||||
Text("Manual connection").tag("")
|
||||
ForEach(profiles.keys.sorted(), id: \.self) { name in Text(name).tag(name) }
|
||||
}
|
||||
}
|
||||
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
|
||||
}
|
||||
Section("MCP server") {
|
||||
if let profile {
|
||||
LabeledContent("Transport", value: local ? "Local stdio" : "Streamable HTTP")
|
||||
LabeledContent("Target", value: profile.target)
|
||||
} else {
|
||||
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
|
||||
SecureField("Bearer token (optional)", text: $token)
|
||||
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)
|
||||
} else {
|
||||
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
|
||||
SecureField("Bearer token (optional)", text: $token)
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
Button(transport == "stdio" ? "Start Server and Discover…" : "Discover Tools") {
|
||||
if transport == "stdio" { confirmLaunch = true }
|
||||
Button(local ? "Start Server and Discover…" : "Discover Tools") {
|
||||
if local { confirmLaunch = true }
|
||||
else { discover() }
|
||||
}
|
||||
.disabled(busy || (transport == "stdio" ? executable.isEmpty : endpoint.isEmpty))
|
||||
.disabled(busy || target.isEmpty)
|
||||
if client != nil {
|
||||
Button("Disconnect") { resetConnection() }.disabled(busy)
|
||||
}
|
||||
@@ -286,22 +331,48 @@ struct MCPSettings: View {
|
||||
}
|
||||
}
|
||||
.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: selectedProfile) { _, _ in resetConnection() }
|
||||
.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 { resetConnection() }
|
||||
.onDisappear { operation?.cancel() }
|
||||
.confirmationDialog("Start local MCP server?", isPresented: $confirmLaunch, titleVisibility: .visible) {
|
||||
Button("Start and Discover", action: discover)
|
||||
} message: {
|
||||
Text("Launch \(executable) with the listed arguments using your macOS account.")
|
||||
Text("Launch \(target) with its configured arguments using your macOS account.")
|
||||
}
|
||||
.confirmationDialog("Run \(name)?", isPresented: $confirm, titleVisibility: .visible) {
|
||||
Button("Run Tool", action: invoke)
|
||||
} message: {
|
||||
Text("Send these arguments to \(transport == "stdio" ? executable : endpoint):\n\(arguments.prefix(800))")
|
||||
Text("Send these arguments to \(target):\n\(arguments.prefix(800))")
|
||||
}
|
||||
}
|
||||
|
||||
private func loadConfig(_ url: URL, disconnect: 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
|
||||
configPath = url.path
|
||||
if profiles[selectedProfile] == nil && (disconnect || !selectedProfile.isEmpty) {
|
||||
selectedProfile = profiles.keys.sorted().first ?? ""
|
||||
}
|
||||
configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)."
|
||||
} catch {
|
||||
configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,7 +380,9 @@ struct MCPSettings: View {
|
||||
run {
|
||||
resetConnection(cancel: false)
|
||||
let server: any MCPToolClient
|
||||
if transport == "stdio" {
|
||||
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 {
|
||||
@@ -317,8 +390,8 @@ struct MCPSettings: View {
|
||||
}
|
||||
let discovered = try await server.listTools()
|
||||
try Task.checkCancellation()
|
||||
client = server
|
||||
tools = discovered
|
||||
studio.activeToolset = ActiveToolset(name: profile == nil ? target : selectedProfile,
|
||||
client: server, tools: discovered)
|
||||
name = discovered.first?.name ?? ""
|
||||
result = discovered.isEmpty ? "This server has no exposed tools." : "\(discovered.count) tools discovered."
|
||||
}
|
||||
@@ -338,8 +411,7 @@ struct MCPSettings: View {
|
||||
|
||||
private func resetConnection(cancel: Bool = true) {
|
||||
if cancel { operation?.cancel() }
|
||||
client = nil
|
||||
tools = []
|
||||
studio.activeToolset = nil
|
||||
name = ""
|
||||
invokedTool = nil
|
||||
result = ""
|
||||
@@ -361,18 +433,19 @@ struct MCPSettings: View {
|
||||
actor StdioMCPClient: MCPToolClient {
|
||||
private let executable: URL
|
||||
private let arguments: [String]
|
||||
private let environment: [String: String]
|
||||
private let workingDirectory: URL?
|
||||
private var transport: StdioTransport?
|
||||
private var ready = false
|
||||
private var busy = false
|
||||
private static let versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
|
||||
|
||||
init(path: String, arguments: [String]) throws {
|
||||
let expanded = (path.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath
|
||||
guard expanded.hasPrefix("/"), FileManager.default.isExecutableFile(atPath: expanded) else {
|
||||
throw StudioError("Choose the absolute path to a local MCP server executable.")
|
||||
}
|
||||
executable = URL(fileURLWithPath: expanded)
|
||||
init(path: String, arguments: [String], environment: [String: String] = [:], cwd: String? = nil) throws {
|
||||
let launch = try MCPServerConfiguration.resolveCommand(path, environment: environment, cwd: cwd)
|
||||
executable = launch.executable
|
||||
self.arguments = arguments
|
||||
self.environment = launch.environment
|
||||
workingDirectory = launch.workingDirectory
|
||||
}
|
||||
|
||||
func disconnect() {
|
||||
@@ -385,7 +458,7 @@ actor StdioMCPClient: MCPToolClient {
|
||||
busy = true
|
||||
defer { busy = false }
|
||||
if !ready {
|
||||
transport = try StdioTransport(executable: executable, arguments: arguments)
|
||||
transport = try StdioTransport(executable: executable, arguments: arguments, environment: environment, cwd: workingDirectory)
|
||||
do {
|
||||
let info = try await exchange("initialize", params: [
|
||||
"protocolVersion": Self.versions[0], "capabilities": [:],
|
||||
@@ -466,19 +539,31 @@ private final class StdioTransport: @unchecked Sendable {
|
||||
private let child = Process()
|
||||
private let input: FileHandle
|
||||
private let output: FileHandle
|
||||
private let errorOutput: FileHandle
|
||||
private let diagnostics = MCPDiagnostics()
|
||||
private var buffered = Data()
|
||||
private let limit = 2_000_000
|
||||
|
||||
init(executable: URL, arguments: [String]) throws {
|
||||
init(executable: URL, arguments: [String], environment: [String: String], cwd: URL?) throws {
|
||||
let source = Pipe()
|
||||
let sink = Pipe()
|
||||
let errors = Pipe()
|
||||
errorOutput = errors.fileHandleForReading
|
||||
input = source.fileHandleForWriting
|
||||
output = sink.fileHandleForReading
|
||||
child.executableURL = executable
|
||||
child.arguments = arguments
|
||||
child.environment = environment
|
||||
child.currentDirectoryURL = cwd
|
||||
child.standardInput = source
|
||||
child.standardOutput = sink
|
||||
child.standardError = FileHandle.nullDevice
|
||||
child.standardError = errors
|
||||
let diagnostics = diagnostics
|
||||
errorOutput.readabilityHandler = { handle in
|
||||
let data = handle.availableData
|
||||
if data.isEmpty { handle.readabilityHandler = nil }
|
||||
else { diagnostics.append(data) }
|
||||
}
|
||||
guard fcntl(input.fileDescriptor, F_SETNOSIGPIPE, 1) != -1,
|
||||
fcntl(input.fileDescriptor, F_SETFL, O_NONBLOCK) != -1 else {
|
||||
throw StudioError("Could not configure the local MCP input pipe.")
|
||||
@@ -490,6 +575,7 @@ private final class StdioTransport: @unchecked Sendable {
|
||||
if child.isRunning { child.terminate() }
|
||||
try? input.close()
|
||||
try? output.close()
|
||||
errorOutput.readabilityHandler = nil
|
||||
}
|
||||
|
||||
func exchange(_ payload: Data, id: String?) throws -> Data {
|
||||
@@ -524,7 +610,7 @@ private final class StdioTransport: @unchecked Sendable {
|
||||
Darwin.read(output.fileDescriptor, $0.baseAddress, $0.count)
|
||||
}
|
||||
if count < 0 && errno == EINTR { continue }
|
||||
guard count > 0 else { throw StudioError("The local MCP server closed its output.") }
|
||||
guard count > 0 else { throw diagnostics.error("The local MCP server closed its output.") }
|
||||
buffered.append(contentsOf: bytes.prefix(count))
|
||||
guard buffered.count <= limit else { throw StudioError("The local MCP response is too large.") }
|
||||
}
|
||||
@@ -538,7 +624,7 @@ private final class StdioTransport: @unchecked Sendable {
|
||||
try wait(input.fileDescriptor, event: Int16(POLLOUT), until: deadline)
|
||||
let count = Darwin.write(input.fileDescriptor, start.advanced(by: sent), bytes.count - sent)
|
||||
if count < 0 && (errno == EINTR || errno == EAGAIN) { continue }
|
||||
guard count > 0 else { throw StudioError("The local MCP server closed its input.") }
|
||||
guard count > 0 else { throw diagnostics.error("The local MCP server closed its input.") }
|
||||
sent += count
|
||||
}
|
||||
}
|
||||
@@ -552,6 +638,118 @@ private final class StdioTransport: @unchecked Sendable {
|
||||
if result > 0 { return }
|
||||
if result < 0 && errno != EINTR { throw StudioError("An MCP pipe error occurred.") }
|
||||
}
|
||||
throw StudioError("The local MCP server timed out.")
|
||||
throw diagnostics.error("The local MCP server timed out.")
|
||||
}
|
||||
}
|
||||
|
||||
struct MCPServerConfiguration: Decodable {
|
||||
let command: String?
|
||||
let args: [String]?
|
||||
let env: [String: String]?
|
||||
let cwd: String?
|
||||
let url: String?
|
||||
let headers: [String: String]?
|
||||
|
||||
struct File: Decodable {
|
||||
let mcpServers: [String: MCPServerConfiguration]
|
||||
|
||||
static func read(_ url: URL) throws -> Self {
|
||||
let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
|
||||
guard size <= 1_048_576 else { throw StudioError("Choose an MCP configuration under 1 MB.") }
|
||||
return try JSONDecoder().decode(Self.self, from: Data(contentsOf: url))
|
||||
}
|
||||
}
|
||||
|
||||
var target: String { command ?? url ?? "Unconfigured server" }
|
||||
|
||||
func makeClient() throws -> any MCPToolClient {
|
||||
switch (command, url) {
|
||||
case (let command?, nil):
|
||||
let arguments = args ?? []
|
||||
let launcher = Self.projectPython(command, arguments: arguments, environment: env ?? [:]) ?? command
|
||||
if let script = arguments.first(where: { $0.hasPrefix("/") && $0.hasSuffix(".py") }),
|
||||
["python", "python3"].contains(URL(fileURLWithPath: command).lastPathComponent),
|
||||
!FileManager.default.fileExists(atPath: script) {
|
||||
throw StudioError("The configured Python script does not exist: \(script)")
|
||||
}
|
||||
return try StdioMCPClient(path: launcher, arguments: arguments, environment: env ?? [:], cwd: cwd)
|
||||
case (nil, let url?):
|
||||
return try HTTPMCPClient(endpoint: url, headers: headers ?? [:])
|
||||
default:
|
||||
throw StudioError("An MCP server must specify either command or url.")
|
||||
}
|
||||
}
|
||||
|
||||
static func projectPython(_ command: String, arguments: [String], environment: [String: String]) -> String? {
|
||||
guard ["python", "python3"].contains(command), environment["PATH"] == nil,
|
||||
let script = arguments.first(where: { $0.hasPrefix("/") && $0.hasSuffix(".py") }) else { return nil }
|
||||
let folder = URL(fileURLWithPath: script).deletingLastPathComponent()
|
||||
return [folder, folder.deletingLastPathComponent()]
|
||||
.map { $0.appending(path: ".venv/bin/" + command).path }
|
||||
.first(where: FileManager.default.isExecutableFile(atPath:))
|
||||
}
|
||||
|
||||
static func resolveCommand(_ command: String, environment: [String: String], cwd: String?) throws
|
||||
-> (executable: URL, environment: [String: String], workingDirectory: URL?) {
|
||||
let command = (command.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath
|
||||
guard !command.isEmpty else { throw StudioError("Enter an MCP executable or command name.") }
|
||||
let manager = FileManager.default
|
||||
let home = manager.homeDirectoryForCurrentUser.path
|
||||
var childEnvironment = ProcessInfo.processInfo.environment.merging(environment) { _, new in new }
|
||||
let common = ["/opt/homebrew/bin", "/usr/local/bin", "/Applications/ServBay/bin",
|
||||
home + "/.local/bin", home + "/.cargo/bin", "/usr/bin", "/bin"]
|
||||
let directories = (childEnvironment["PATH"] ?? "").split(separator: ":").map(String.init) + common
|
||||
childEnvironment["PATH"] = directories.joined(separator: ":")
|
||||
let folder: URL?
|
||||
if let cwd {
|
||||
let path = (cwd as NSString).expandingTildeInPath
|
||||
var isDirectory: ObjCBool = false
|
||||
guard path.hasPrefix("/"), manager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else {
|
||||
throw StudioError("The configured MCP working directory does not exist.")
|
||||
}
|
||||
folder = URL(fileURLWithPath: path, isDirectory: true)
|
||||
} else {
|
||||
folder = nil
|
||||
}
|
||||
let candidates: [String]
|
||||
if command.hasPrefix("/") {
|
||||
candidates = [command]
|
||||
} else if command.contains("/") {
|
||||
candidates = folder.map { [$0.appending(path: command).path] } ?? []
|
||||
} else {
|
||||
let names = command == "python" ? ["python", "python3"] : [command]
|
||||
candidates = names.flatMap { name in
|
||||
directories.filter { $0.hasPrefix("/") }.map { URL(fileURLWithPath: $0).appending(path: name).path }
|
||||
}
|
||||
}
|
||||
guard let path = candidates.first(where: manager.isExecutableFile(atPath:)) else {
|
||||
throw StudioError("Could not find the MCP executable ‘\(command)’. Check PATH or use an absolute path.")
|
||||
}
|
||||
return (URL(fileURLWithPath: path), childEnvironment, folder)
|
||||
}
|
||||
}
|
||||
|
||||
private final class MCPDiagnostics: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var tail = Data()
|
||||
|
||||
func append(_ bytes: Data) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
tail.append(bytes)
|
||||
if tail.count > 4096 { tail = Data(tail.suffix(4096)) }
|
||||
}
|
||||
|
||||
func error(_ message: String) -> StudioError {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
let context = String(decoding: tail, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return StudioError(context.isEmpty ? message : message + "\n" + context)
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveToolset {
|
||||
let name: String
|
||||
let client: any MCPToolClient
|
||||
let tools: [MCPTool]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user