Files
ai_studio/Sources/MCP.swift
T

820 lines
39 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
import Darwin
import SwiftUI
import AppKit
import UniformTypeIdentifiers
actor HTTPMCPClient: MCPToolClient {
private struct Connection {
let version: String
let session: String?
}
private final class NoRedirects: NSObject, URLSessionTaskDelegate, Sendable {
func urlSession(_ session: URLSession, task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
completionHandler(nil)
}
}
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 = "", 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 {
throw StudioError("Enter an MCP endpoint URL without embedded credentials.")
}
let local = ["localhost", "127.0.0.1", "[::1]", "::1"].contains(host)
guard parsed.scheme?.lowercased() == "https" || (local && parsed.scheme?.lowercased() == "http") else {
throw StudioError("Use HTTPS for a remote MCP server.")
}
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
session = URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil)
}
func listTools() async throws -> [MCPTool] {
let connection = try await connect()
var tools: [MCPTool] = []
var cursor: String?
var seen: Set<String> = []
repeat {
let params = cursor.map { ["cursor": $0] } ?? [:]
let (page, _) = try await exchange("tools/list", params: params, connection: connection)
tools += try Self.decodeTools(page)
cursor = page["nextCursor"] as? String
if let cursor, !seen.insert(cursor).inserted || seen.count > 50 {
throw StudioError("The server did not complete tool discovery.")
}
} while cursor != nil
return tools
}
func callTool(_ name: String, argumentsJSON: Data) async throws -> Data {
let arguments = try Self.arguments(argumentsJSON)
guard let connection else { throw StudioError("Discover tools before running one.") }
let (result, _) = try await exchange("tools/call", params: ["name": name, "arguments": arguments],
connection: connection)
if result["resultType"] as? String == "input_required" {
throw StudioError("This tool requires a follow-up interaction that AI Studio does not support.")
}
return try JSONSerialization.data(withJSONObject: result, options: [.prettyPrinted, .sortedKeys])
}
static func decodeTools(_ page: [String: Any]) throws -> [MCPTool] {
var tools: [MCPTool] = []
guard let entries = page["tools"] as? [[String: Any]] else {
throw StudioError("The server returned an invalid tool list.")
}
for entry in entries {
guard let name = entry["name"] as? String, let schema = entry["inputSchema"] as? [String: Any] else {
throw StudioError("The server returned an invalid tool definition.")
}
tools.append(MCPTool(name: name, description: entry["description"] as? String ?? "",
inputSchemaJSON: try JSONSerialization.data(withJSONObject: schema, options: [.prettyPrinted, .sortedKeys])))
}
return tools
}
static func arguments(_ data: Data) throws -> [String: Any] {
guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw StudioError("Tool arguments must be a JSON object.")
}
return object
}
private func connect() async throws -> Connection {
if let connection { return connection }
let modern = Connection(version: Self.modern, session: nil)
do {
let (discovery, _) = try await exchange("server/discover", params: [:], connection: modern)
if let supported = discovery["supportedVersions"] as? [String], supported.contains(Self.modern) {
guard let capabilities = discovery["capabilities"] as? [String: Any],
capabilities["tools"] != nil else {
throw StudioError("The server does not advertise MCP tools.")
}
connection = modern
return modern
}
} catch {
try Task.checkCancellation()
}
let (reply, response) = try await exchange("initialize", params: [
"protocolVersion": versions[0], "capabilities": [:],
"clientInfo": ["name": "AI Studio", "version": "1.1"]
], connection: nil)
guard let version = reply["protocolVersion"] as? String, versions.contains(version),
let capabilities = reply["capabilities"] as? [String: Any], capabilities["tools"] != nil else {
throw StudioError("The server does not advertise tools on a supported MCP version.")
}
let active = Connection(version: version, session: response.value(forHTTPHeaderField: "Mcp-Session-Id"))
_ = try await exchange("notifications/initialized", params: [:], connection: active, notification: true)
connection = active
return active
}
private func exchange(_ method: String, params: [String: Any], connection: Connection?,
notification: Bool = false) async throws -> ([String: Any], HTTPURLResponse) {
let id = UUID().uuidString
var body: [String: Any] = ["jsonrpc": "2.0", "method": method]
var params = params
let modern = connection?.version == Self.modern
if modern {
params["_meta"] = [
"io.modelcontextprotocol/protocolVersion": Self.modern,
"io.modelcontextprotocol/clientInfo": ["name": "AI Studio", "version": "1.1"],
"io.modelcontextprotocol/clientCapabilities": [:]
] as [String: Any]
}
if !params.isEmpty { body["params"] = params }
if !notification { body["id"] = id }
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.httpBody = try JSONSerialization.data(withJSONObject: body)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept")
request.setValue(connection?.version, forHTTPHeaderField: "MCP-Protocol-Version")
request.setValue(connection?.session, forHTTPHeaderField: "Mcp-Session-Id")
if modern {
request.setValue(method, forHTTPHeaderField: "Mcp-Method")
if method == "tools/call" {
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 {
if let http = response as? HTTPURLResponse, http.statusCode == 404 { self.connection = nil }
throw StudioError("MCP returned HTTP \((response as? HTTPURLResponse)?.statusCode ?? 0).")
}
if notification { return ([:], http) }
if http.mimeType == "text/event-stream" {
var event: [String] = []
var line = Data()
var count = 0
for try await byte in bytes {
count += 1
guard count <= 2_000_000 else { throw StudioError("MCP response is too large.") }
if byte != 10 {
line.append(byte)
continue
}
if line.last == 13 { line.removeLast() }
if line.isEmpty {
if !event.isEmpty, let result = try Self.result(Data(event.joined(separator: "\n").utf8), id: id) {
return (result, http)
}
event.removeAll(keepingCapacity: true)
} else {
let text = String(decoding: line, as: UTF8.self)
if text.hasPrefix("data:") {
let value = text.dropFirst(5)
event.append(String(value.first == " " ? value.dropFirst() : value))
}
}
line.removeAll(keepingCapacity: true)
}
} else {
var data = Data()
for try await byte in bytes {
guard data.count < 2_000_000 else { throw StudioError("MCP response is too large.") }
data.append(byte)
}
if let result = try Self.result(data, id: id) { return (result, http) }
}
throw StudioError("The MCP server closed the response without a result.")
}
static func result(_ data: Data, id: String) throws -> [String: Any]? {
guard let envelope = try JSONSerialization.jsonObject(with: data) as? [String: Any],
envelope["jsonrpc"] as? String == "2.0", envelope["id"] as? String == id else { return nil }
if let error = envelope["error"] as? [String: Any] {
throw StudioError(error["message"] as? String ?? "MCP request failed.")
}
return envelope["result"] as? [String: Any]
}
}
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 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 = ""
@State private var invokedTool: String?
@State private var busy = false
@State private var confirm = false
@State private var operation: Task<Void, Never>?
var body: some View {
Form {
Section("Built-In Tools") {
Button("Activate Web Toolset", action: activateWeb).disabled(busy)
if client is BuiltInWebTools {
LabeledContent("Connection", value: "Active")
Button("Disconnect Web Toolset") { resetConnection() }.disabled(busy)
}
Text("Retrieve pages directly. Search uses the SearXNG endpoint configured in Toolbox → Web.")
.foregroundStyle(.secondary)
}
Section("Custom MCP Servers") {
HStack {
Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") {
let url = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")
loadConfig(url)
}
if !configPath.isEmpty {
Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) }
Button("Edit File") { NSWorkspace.shared.open(URL(fileURLWithPath: configPath)) }
}
}
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 {
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(local ? "Start Server and Discover…" : "Discover Tools") {
if local { confirmingStartup = true; confirm = true }
else { discover() }
}
.disabled(busy || target.isEmpty)
if client != nil {
Button("Disconnect") { resetConnection() }.disabled(busy)
}
if busy { Button("Cancel") { operation?.cancel() } }
}
}
if !tools.isEmpty {
Section("Tool invocation") {
Picker("Tool", selection: $name) {
ForEach(tools, id: \.name) { tool in Text(tool.name).tag(tool.name) }
}
if let tool = tools.first(where: { $0.name == name }) {
if !tool.description.isEmpty { Text(tool.description).foregroundStyle(.secondary) }
DisclosureGroup("Input Schema") {
ScrollView {
Text(String(decoding: tool.inputSchemaJSON, as: UTF8.self))
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
}.frame(maxHeight: 100)
}
}
TextEditor(text: $arguments).font(.system(.body, design: .monospaced))
.frame(height: 80).accessibilityLabel("JSON arguments")
Button("Review Tool Call…") { confirmingStartup = false; confirm = true }.disabled(busy)
}
}
if !result.isEmpty {
Section("Result") {
ScrollView {
Text(result).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: 160)
if let invokedTool {
Button("Attach Result to Active Chat") {
studio.attachToolResult(name: invokedTool, output: result)
self.invokedTool = nil
}
.disabled(studio.selected == nil || studio.running)
}
}
}
}
.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 { operation?.cancel() }
.confirmationDialog(confirmingStartup ? "Start local MCP server?" : "Run \(name)?",
isPresented: $confirm, titleVisibility: .visible) {
if confirmingStartup { Button("Start and Discover", action: discover) }
else { Button("Run Tool", action: invoke) }
} message: {
if confirmingStartup {
Text("Launch \(target) with its configured arguments using your macOS account.")
} else {
Text("Send these arguments to \(studio.activeToolset?.name ?? target):\n\(arguments.prefix(800))")
}
}
}
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 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) {
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 ?? ""
}
configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)."
} catch {
configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)"
}
}
private func discover() {
run {
resetConnection(cancel: false)
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)
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(_ 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 { result = Task.isCancelled ? "Cancelled" : error.localizedDescription }
}
}
}
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], 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() {
transport = nil
ready = false
}
func listTools() async throws -> [MCPTool] {
guard !busy else { throw StudioError("The local server is already handling a request.") }
busy = true
defer { busy = false }
if !ready {
transport = try StdioTransport(executable: executable, arguments: arguments, environment: environment, cwd: workingDirectory)
do {
let info = try await exchange("initialize", params: [
"protocolVersion": Self.versions[0], "capabilities": [:],
"clientInfo": ["name": "AI Studio", "version": "1.1"]
])
guard let version = info["protocolVersion"] as? String, Self.versions.contains(version),
let capabilities = info["capabilities"] as? [String: Any], capabilities["tools"] != nil else {
throw StudioError("The local server did not advertise tools on a supported MCP version.")
}
_ = try await exchange("notifications/initialized", notification: true)
ready = true
} catch {
disconnect()
throw error
}
}
var tools: [MCPTool] = []
var cursor: String?
var seen: Set<String> = []
repeat {
let page = try await exchange("tools/list", params: cursor.map { ["cursor": $0] } ?? [:])
tools += try HTTPMCPClient.decodeTools(page)
cursor = page["nextCursor"] as? String
if let cursor, !seen.insert(cursor).inserted || seen.count > 50 {
throw StudioError("The local server did not complete tool discovery.")
}
} while cursor != nil
return tools
}
func callTool(_ name: String, argumentsJSON: Data) async throws -> Data {
guard ready, !busy else { throw StudioError("Discover the local server’s tools before invoking one.") }
busy = true
defer { busy = false }
let args = try HTTPMCPClient.arguments(argumentsJSON)
let result = try await exchange("tools/call", params: ["name": name, "arguments": args])
return try JSONSerialization.data(withJSONObject: result, options: [.prettyPrinted, .sortedKeys])
}
private func exchange(
_ method: String, params: [String: Any] = [:], notification: Bool = false
) async throws -> [String: Any] {
try Task.checkCancellation()
guard let transport else { throw StudioError("The local MCP server is disconnected.") }
let id = UUID().uuidString
var request: [String: Any] = ["jsonrpc": "2.0", "method": method]
if !params.isEmpty { request["params"] = params }
if !notification { request["id"] = id }
var data = try JSONSerialization.data(withJSONObject: request)
data.append(10)
let payload = data
let worker = Task.detached {
try transport.exchange(payload, id: notification ? nil : id)
}
let response: Data
do {
response = try await withTaskCancellationHandler {
try await worker.value
} onCancel: {
worker.cancel()
}
try Task.checkCancellation()
} catch {
disconnect()
throw error
}
if notification { return [:] }
guard let result = try HTTPMCPClient.result(response, id: id) else {
throw StudioError("The local MCP server returned an invalid result.")
}
return result
}
}
// Access to the pipe buffer is serialized by StdioMCPClient's operation guard.
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], 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 = 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.")
}
try child.run()
}
deinit {
if child.isRunning { child.terminate() }
try? input.close()
try? output.close()
errorOutput.readabilityHandler = nil
}
func exchange(_ payload: Data, id: String?) throws -> Data {
guard payload.count <= limit else { throw StudioError("The MCP request is too large.") }
let deadline = ProcessInfo.processInfo.systemUptime + 30
try write(payload, until: deadline)
guard let id else { return Data() }
var consumed = 0
var bytes = [UInt8](repeating: 0, count: 16_384)
while true {
try Task.checkCancellation()
if let newline = buffered.firstIndex(of: 10) {
let line = Data(buffered[..<newline])
buffered.removeSubrange(...newline)
consumed += line.count + 1
guard consumed <= limit else { throw StudioError("The local MCP response is too large.") }
if line.isEmpty { continue }
guard let frame = try JSONSerialization.jsonObject(with: line) as? [String: Any] else {
throw StudioError("The local MCP server emitted invalid JSON.")
}
if frame["id"] as? String == id { return line }
if let id = frame["id"], frame["method"] is String {
try write(try JSONSerialization.data(withJSONObject: [
"jsonrpc": "2.0", "id": id,
"error": ["code": -32601, "message": "Client method unavailable"]
]) + Data([10]), until: deadline)
}
continue
}
try wait(output.fileDescriptor, event: Int16(POLLIN), until: deadline)
let count = bytes.withUnsafeMutableBytes {
Darwin.read(output.fileDescriptor, $0.baseAddress, $0.count)
}
if count < 0 && errno == EINTR { continue }
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.") }
}
}
private func write(_ payload: Data, until deadline: Double) throws {
try payload.withUnsafeBytes { bytes in
guard let start = bytes.baseAddress else { return }
var sent = 0
while sent < bytes.count {
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 diagnostics.error("The local MCP server closed its input.") }
sent += count
}
}
}
private func wait(_ fd: Int32, event: Int16, until deadline: Double) throws {
var descriptor = pollfd(fd: fd, events: event, revents: 0)
while ProcessInfo.processInfo.systemUptime < deadline {
try Task.checkCancellation()
let result = poll(&descriptor, 1, 100)
if result > 0 { return }
if result < 0 && errno != EINTR { throw StudioError("An MCP pipe error occurred.") }
}
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]
}
struct BuiltInWebTools: MCPToolClient {
static let name = "Built-In Web"
let searchEndpoint: String
func listTools() async throws -> [MCPTool] {
[
MCPTool(name: "retrieve_page", description: "Retrieve readable text from an HTTP or HTTPS page.",
inputSchemaJSON: Data(#"{"type":"object","properties":{"url":{"type":"string","format":"uri"}},"required":["url"]}"#.utf8)),
MCPTool(name: "web_search", description: "Search via the SearXNG endpoint configured in Toolbox → Web.",
inputSchemaJSON: Data(#"{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}"#.utf8))
]
}
func callTool(_ name: String, argumentsJSON: Data) async throws -> Data {
let arguments = try HTTPMCPClient.arguments(argumentsJSON)
switch name {
case "retrieve_page":
guard let address = arguments["url"] as? String else { throw StudioError("Provide a page URL in the url field.") }
let page = try await WebClipCapture.page(from: address)
return try JSONSerialization.data(withJSONObject: ["url": page.url.absoluteString, "text": page.text],
options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
case "web_search":
guard let query = arguments["query"] as? String else { throw StudioError("Provide a search query in the query field.") }
guard !searchEndpoint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw StudioError("Set a SearXNG search URL in Toolbox → Web before using web_search.")
}
let results = try await WebSearch.results(endpoint: searchEndpoint, query: query)
return try JSONSerialization.data(withJSONObject: results.map {
["title": $0.title, "url": $0.url.absoluteString, "snippet": $0.snippet]
}, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
default:
throw StudioError("Unknown built-in tool: \(name).")
}
}
}