Connect to local MCP servers over stdio

This commit is contained in:
Mark Gregory
2026-11-16 14:04:16 +00:00
parent caa0a8733b
commit 515f609f8d
6 changed files with 357 additions and 23 deletions
+258 -19
View File
@@ -1,4 +1,5 @@
import Foundation
import Darwin
import SwiftUI
actor HTTPMCPClient: MCPToolClient {
@@ -50,16 +51,7 @@ actor HTTPMCPClient: MCPToolClient {
repeat {
let params = cursor.map { ["cursor": $0] } ?? [:]
let (page, _) = try await exchange("tools/list", params: params, connection: connection)
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])))
}
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.")
@@ -79,6 +71,21 @@ actor HTTPMCPClient: MCPToolClient {
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.")
@@ -203,7 +210,11 @@ struct MCPSettings: View {
@ObservedObject var studio: StudioModel
@AppStorage("mcpEndpoint") private var endpoint = ""
@State private var token = ""
@State private var client: HTTPMCPClient?
@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 = "{}"
@@ -216,10 +227,26 @@ struct MCPSettings: View {
var body: some View {
Form {
Section("MCP server") {
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("Discover Tools", action: discover).disabled(busy || endpoint.isEmpty)
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() } }
}
}
@@ -262,21 +289,35 @@ struct MCPSettings: View {
.onChange(of: endpoint) { _, _ in resetConnection() }
.onChange(of: token) { _, _ in resetConnection() }
.onChange(of: name) { _, _ in arguments = "{}" }
.onDisappear { operation?.cancel() }
.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 \(endpoint):\n\(arguments.prefix(800))")
Text("Send these arguments to \(transport == "stdio" ? executable : endpoint):\n\(arguments.prefix(800))")
}
}
private func discover() {
run {
resetConnection(cancel: false)
let remote = try HTTPMCPClient(endpoint: endpoint, token: token)
let discovered = try await remote.listTools()
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 = remote
client = server
tools = discovered
name = discovered.first?.name ?? ""
result = discovered.isEmpty ? "This server has no exposed tools." : "\(discovered.count) tools discovered."
@@ -316,3 +357,201 @@ struct MCPSettings: View {
}
}
}
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.")
}
}