Files
ai_studio/Sources/MCP.swift
T

819 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 = ""
@AppStorage("mcpTransport") private var transport = "http"
@AppStorage("mcpExecutable") private var executable = ""
@AppStorage("mcpArguments") private var launchArguments = ""
@AppStorage("webSearchEndpoint") private var webSearchEndpoint = ""
@AppStorage("mcpConfigPath") private var configPath = ""
@State private var token = ""
@State private var profiles: [String: MCPServerConfiguration] = [:]
@State private var importingConfig = false
@State private var configStatus = ""
@State private var selected: MCPConnectionID?
@State private var tool = ""
@State private var arguments = "{}"
@State private var confirm = false
private var selection: MCPConnectionID? {
if let selected, studio.mcpConnections[selected]?.toolset != nil { return selected }
return studio.activeToolsets.first?.id
}
var body: some View {
HSplitView {
Form {
Section("Built-In Tools") {
connectionRow(.web, title: BuiltInWebTools.name, subtitle: "Retrieve pages and search via SearXNG", icon: "globe") {
let search = webSearchEndpoint
studio.connectMCP(.web, name: BuiltInWebTools.name) { BuiltInWebTools(searchEndpoint: search) }
}
}
Section("Custom MCP Servers") {
VStack(alignment: .leading, spacing: 6) {
Button("Import mcp.json…") { importingConfig = true }
Button("Use LM Studio Config") {
loadConfig(FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json"))
}
if !configPath.isEmpty {
Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) }
Button("Edit File") { NSWorkspace.shared.open(URL(fileURLWithPath: configPath)) }
}
}.buttonStyle(.bordered)
ForEach(profiles.keys.sorted(), id: \.self) { name in
if let profile = profiles[name] {
connectionRow(.profile(name), title: name,
subtitle: profile.command == nil ? "Streamable HTTP" : "Local stdio",
icon: profile.command == nil ? "network" : "terminal",
local: profile.command != nil) {
studio.connectMCP(.profile(name), name: name) { try profile.makeClient() }
}
}
}
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
}
Section("Manual Connection") {
DisclosureGroup("Configure a manual connection") {
Picker("Transport", selection: $transport) {
Text("Streamable HTTP").tag("http")
Text("Local stdio").tag("stdio")
}
if transport == "stdio" {
TextField("Executable or command", text: $executable)
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
} else {
TextField("Endpoint", text: $endpoint)
SecureField("Bearer token (optional)", text: $token)
}
connectionRow(.manual, title: "Manual server", subtitle: transport == "stdio" ? executable : endpoint,
icon: "slider.horizontal.3", local: transport == "stdio",
available: transport == "stdio" ? !executable.isEmpty : !endpoint.isEmpty,
connect: connectManual)
}
}
}
.formStyle(.grouped)
.frame(minWidth: 300, idealWidth: 340)
Form {
if let selection, let state = studio.mcpConnections[selection], let toolset = state.toolset {
Section("Run a Tool") {
Picker("Connected server", selection: Binding(
get: { self.selection }, set: { selected = $0 }
)) {
ForEach(studio.activeToolsets, id: \.id) { entry in
Text(entry.toolset.name).tag(Optional(entry.id))
}
}
if !toolset.tools.isEmpty {
Picker("Tool", selection: $tool) {
ForEach(toolset.tools, id: \.name) { Text($0.name).tag($0.name) }
}
if let entry = toolset.tools.first(where: { $0.name == tool }) {
if !entry.description.isEmpty { Text(entry.description).foregroundStyle(.secondary) }
DisclosureGroup("Input Schema") {
Text(String(decoding: entry.inputSchemaJSON, as: UTF8.self))
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
}
}
TextEditor(text: $arguments).font(.system(.body, design: .monospaced))
.frame(height: 85).accessibilityLabel("JSON arguments")
Button("Review Tool Call…") { confirm = true }
.disabled(tool.isEmpty || state.progress != nil)
}
if !state.output.isEmpty {
ScrollView {
Text(state.output).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: 160)
if let completed = state.completedTool {
Button("Attach Result to Chat") { studio.attachToolResult(name: completed, output: state.output) }
.disabled(studio.running)
}
}
}
} else {
ContentUnavailableView("Select a connected server", systemImage: "wrench.and.screwdriver",
description: Text("Connect a server on the left to see and run its tools."))
}
}
.formStyle(.grouped)
.frame(minWidth: 320)
}
.formStyle(.grouped)
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
do { loadConfig(try result.get()) }
catch { configStatus = error.localizedDescription }
}
.onAppear {
if profiles.isEmpty {
if !configPath.isEmpty {
loadConfig(URL(fileURLWithPath: configPath), invalidateProfiles: false)
} else {
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) { _, _ in selectFirstTool() }
.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 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 }
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, invalidateProfiles: Bool = true) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let file = try MCPServerConfiguration.File.read(url)
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)"
}
}
}
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, Equatable {
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]
}
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 {
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 the web using the default provider or configured SearXNG endpoint.",
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.") }
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).")
}
}
}