Build AI Studio 1.1 for macOS #1

Open
admin wants to merge 38 commits from admin/ai-studio-v1.1 AGit into main
6 changed files with 357 additions and 23 deletions
Showing only changes of commit 515f609f8d - Show all commits
+10 -3
View File
@@ -7,14 +7,15 @@
| 3. Release readiness | Awaiting external checks | Authenticated gateway tests, archive verification, live remote interoperability and distribution signing |
| 4. Chat workspace | Complete | Chat search and rename, formatted answers, global prompt modes, prompt builder, performance dashboard |
| 5. Generation and local tools | Awaiting Docker daemon check | Silent system instructions, runtime parameter overrides, confirmed Docker commands, Finder file actions |
| 6. Compatibility extensions | In progress | OpenAI-compatible endpoint, MCP stdio, broader desktop automation and runtime controls |
| 6. Compatibility extensions | Awaiting live LM Studio check | OpenAI-compatible endpoint and MCP stdio |
| 7. Desktop and runtime controls | Planned | Extend user-initiated desktop actions and local runtime controls |
| Final external verification | Awaiting services and credentials | Live LM Studio, Docker, remote Ollama and MCP, Developer ID signing and notarization |
## Phase 6 checklist
- [x] Verify OpenAI-compatible model discovery and streamed chat.
- [ ] Verify with a running LM Studio server.
- [ ] Add MCP stdio transport.
- [ ] Extend desktop actions and runtime controls.
- [x] Verify MCP stdio discovery, confirmed invocation support, cancellation, and disconnect against a local fixture.
## Phase 3 checklist
@@ -64,3 +65,9 @@ server also completed a direct smoke check of the compatible wire format.
The Debug build succeeded. 26 tests passed and the opt-in catalog download
was skipped. A live LM Studio check remains pending because its local server
was unavailable.
**16 November 2026.** Local MCP stdio passed process startup, version
negotiation, paginated discovery, invocation, cancellation and reconnect
tests. The Debug build passed. 28 tests passed and the opt-in catalog
download was skipped. One implementation phase remains, followed by
external verification.
+7 -1
View File
@@ -19,7 +19,13 @@ Chat history, older-message recall, and document indexes live in `~/Library/Appl
Open **Settings → MCP Tools**, enter an MCP HTTP endpoint, and choose **Discover Tools**. Select a tool, review the schema, enter its JSON arguments, and confirm the invocation. You can attach up to 8,000 characters of the result to the next message in the active conversation. The composer shows the attachment before it is sent.
The client supports Streamable HTTP with current stateless discovery and legacy initialization, session headers, and JSON or server-sent event responses. Remote MCP endpoints require HTTPS. Optional bearer tokens stay in memory. Tool calls require explicit confirmation and are sent once. Stdio, OAuth sign-in, and server-requested follow-up interactions are outside the supported MCP scope.
For a local subprocess, select **Local stdio**, enter the full path of the
server executable, and add one argument per line. Choose **Start Server and
Discover…** and confirm. Use **Disconnect** to stop the subprocess. Local
stdio supports the MCP initialization handshake used by the 2024 and 2025
protocol revisions.
The HTTP client supports Streamable HTTP with current stateless discovery and legacy initialization, session headers, and JSON or server-sent event responses. Remote MCP endpoints require HTTPS. Optional bearer tokens stay in memory. Tool calls require explicit confirmation and are sent once. OAuth sign-in, modern stateless stdio, and server-requested follow-up interactions remain outside the supported MCP scope.
## 4. Customize prompts and review performance
+3
View File
@@ -27,6 +27,9 @@ if [[ -z "${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-}" || -z "${TEST_RUNNER_AISTUDIO
export TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL="${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL:-$fixture/ollama}"
fi
export TEST_RUNNER_AISTUDIO_TEST_STDIO_PYTHON="$(command -v python3)"
export TEST_RUNNER_AISTUDIO_TEST_STDIO_FIXTURE="$PWD/Tests/Fixtures/stdio_server.py"
xcodebuild CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= -project AIStudio.xcodeproj -scheme AIStudio -configuration Debug \
-destination 'platform=macOS,arch=arm64' -derivedDataPath "$base/Derived" \
-clonedSourcePackagesDirPath "$base/Packages" -disablePackageRepositoryCache \
+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.")
}
}
+36
View File
@@ -0,0 +1,36 @@
import json
import sys
import time
initialized = False
tool = {
"name": "echo",
"description": "Echo the supplied text",
"inputSchema": {"type": "object"},
}
for line in sys.stdin:
request = json.loads(line)
method = request["method"]
params = request.get("params", {})
if method == "initialize":
assert request["params"]["protocolVersion"] == "2025-11-25"
result = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}}
elif method == "notifications/initialized":
initialized = True
continue
elif method == "tools/list":
assert initialized
if params.get("cursor") == "next":
result = {"tools": [tool]}
else:
result = {"tools": [], "nextCursor": "next"}
elif method == "tools/call":
assert initialized and params["name"] == "echo"
if params["arguments"].get("wait"):
time.sleep(20)
result = {"content": [{"type": "text", "text": params["arguments"].get("text", "")}]}
else:
raise ValueError(method)
print(json.dumps({"jsonrpc": "2.0", "method": "notifications/message"}), flush=True)
print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)
+43
View File
@@ -387,3 +387,46 @@ final class CompatibleEndpointTests: XCTestCase {
.thinking("Thinking"), .answer("Fixture response")])
}
}
final class StdioMCPTests: XCTestCase {
private func client() throws -> StdioMCPClient {
let env = ProcessInfo.processInfo.environment
guard let python = env["AISTUDIO_TEST_STDIO_PYTHON"],
let fixture = env["AISTUDIO_TEST_STDIO_FIXTURE"] else {
throw XCTSkip("Run Scripts/test.sh to configure the stdio fixture.")
}
return try StdioMCPClient(path: python, arguments: ["-u", fixture])
}
func testLocalDiscoveryInvocationAndDisconnect() async throws {
let local = try client()
let tools = try await local.listTools()
XCTAssertEqual(tools.map(\.name), ["echo"])
let response = try await local.callTool("echo", argumentsJSON: Data(#"{"text":"line one\nline two"}"#.utf8))
XCTAssertTrue(String(decoding: response, as: UTF8.self).contains("line two"))
await local.disconnect()
do {
_ = try await local.callTool("echo", argumentsJSON: Data("{}".utf8))
XCTFail("Expected a disconnected client error.")
} catch let error as StudioError {
XCTAssertTrue(error.message.contains("Discover"))
}
}
func testCancellationStopsWaitingForTheLocalServer() async throws {
let local = try client()
_ = try await local.listTools()
let request = Task {
try await local.callTool("echo", argumentsJSON: Data(#"{"wait":true}"#.utf8))
}
try await Task.sleep(for: .milliseconds(200))
request.cancel()
do {
_ = try await request.value
XCTFail("Expected cancellation.")
} catch is CancellationError {}
let tools = try await local.listTools()
XCTAssertEqual(tools.map(\.name), ["echo"])
await local.disconnect()
}
}