Files
ai_studio/Sources/MCP.swift
T

558 lines
25 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
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 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 {
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
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")
}
}
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 = ""
@State private var client: (any MCPToolClient)?
@State private var confirmLaunch = false
@State private var tools: [MCPTool] = []
@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("MCP server") {
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 }
else { discover() }
}
.disabled(busy || (transport == "stdio" ? executable.isEmpty : endpoint.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…") { 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)
.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() }
.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.")
}
.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))")
}
}
private func discover() {
run {
resetConnection(cancel: false)
let server: any MCPToolClient
if transport == "stdio" {
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()
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)
run {
let output = try await client.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() }
client = nil
tools = []
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 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)
self.arguments = arguments
}
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)
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 var buffered = Data()
private let limit = 2_000_000
init(executable: URL, arguments: [String]) throws {
let source = Pipe()
let sink = Pipe()
input = source.fileHandleForWriting
output = sink.fileHandleForReading
child.executableURL = executable
child.arguments = arguments
child.standardInput = source
child.standardOutput = sink
child.standardError = FileHandle.nullDevice
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()
}
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 StudioError("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 StudioError("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 StudioError("The local MCP server timed out.")
}
}