Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(lume): add MCP resources and prompts for AI agent guidance (#838)
Francesco Bonacci8932544ff15a
diff --git a/docs/content/docs/lume/guide/advanced/mcp-server.mdx b/docs/content/docs/lume/guide/advanced/mcp-server.mdxindex e543d00530..2d11a625d9 100644--- a/docs/content/docs/lume/guide/advanced/mcp-server.mdx+++ b/docs/content/docs/lume/guide/advanced/mcp-server.mdx@@ -71,6 +71,25 @@ Ask Claude:| `lume_delete_vm` | Delete a VM and its files || `lume_exec` | Execute commands inside a VM via SSH |+## Resources++The MCP server provides documentation resources that AI agents can read:++| Resource | Description |+|----------|-------------|+| `lume://usage-guide` | Comprehensive guide with workflows, best practices, and status reference |+| `lume://credentials` | Default SSH credentials for VMs created with unattended setup |++## Prompts++Pre-defined workflow prompts guide AI agents through common tasks:++| Prompt | Description |+|--------|-------------|+| `create-sandbox` | Create a new macOS VM with unattended setup |+| `run-in-sandbox` | Execute a command in an existing VM |+| `reset-sandbox` | Reset a sandbox by cloning from a golden image |+## Creating VMsThe `lume_create_vm` tool creates new macOS VMs asynchronously. Since VM creation takes 15-30 minutes (downloading IPSW, installing macOS, optional unattended setup), the tool returns immediately while provisioning continues in the background.diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swiftindex 01dc07b0ab..b4a50057a0 100644--- a/libs/lume/src/LumeController.swift+++ b/libs/lume/src/LumeController.swift@@ -614,239 +614,6 @@ final class LumeController {}}- /// Creates a VM asynchronously, returning immediately while the VM is being provisioned.- /// The VM will appear with status "provisioning" in `lume ls` until creation completes.- /// Poll VM status to check progress.- ///- /// - Parameters:- /// - name: Name for the new VM- /// - os: Operating system type ("macos" or "linux")- /// - diskSize: Disk size in bytes- /// - cpuCount: Number of CPU cores- /// - memorySize: Memory size in bytes- /// - display: Display resolution string (e.g., "1920x1080")- /// - ipsw: Path to IPSW file or "latest" for macOS- /// - storage: Optional storage location name or path- /// - unattendedConfig: Optional unattended setup configuration- @MainActor- public func createAsync(- name: String,- os: String,- diskSize: UInt64,- cpuCount: Int,- memorySize: UInt64,- display: String,- ipsw: String?,- storage: String? = nil,- unattendedConfig: UnattendedConfig? = nil- ) throws {- Logger.info(- "Starting async VM creation",- metadata: [- "name": name,- "os": os,- "location": storage ?? "default",- "unattended": unattendedConfig != nil ? "yes" : "no",- ])-- // Validate parameters upfront (this checks VM doesn't already exist)- try validateCreateParameters(name: name, os: os, ipsw: ipsw, storage: storage)-- Logger.info("Spawning background task for VM creation", metadata: ["name": name])-- // All parameters passed to Task are value types (Sendable)- // The Task will create its own LumeController instance- Task.detached { @MainActor @Sendable in- // Create a new controller for the background task- let controller = LumeController()-- // Get the VM directory- let vmDir: VMDirectory- do {- vmDir = try controller.home.getVMDirectory(name, storage: storage)- } catch {- Logger.error("Failed to get VM directory",- metadata: ["name": name, "error": error.localizedDescription])- return- }-- // Create the VM directory and write provisioning marker first- // so VM appears in list immediately- do {- try FileManager.default.createDirectory(- atPath: vmDir.dir.path,- withIntermediateDirectories: true- )-- // Create minimal config so VM shows up in list- let config = try VMConfig(- os: os,- cpuCount: cpuCount,- memorySize: memorySize,- diskSize: diskSize,- display: display- )- try vmDir.saveConfig(config)-- // Write provisioning marker- try vmDir.saveProvisioningMarker(ProvisioningMarker(operation: "ipsw_install"))- Logger.info("Provisioning marker created", metadata: ["name": name])- } catch {- Logger.error("Failed to create provisioning marker",- metadata: ["name": name, "error": error.localizedDescription])- return- }-- do {- // Run the internal create which does all the work- // (skips validation since we already validated)- try await controller.createInternal(- name: name,- os: os,- diskSize: diskSize,- cpuCount: cpuCount,- memorySize: memorySize,- display: display,- ipsw: ipsw,- storage: storage,- unattendedConfig: unattendedConfig,- vmDir: vmDir- )-- // Clear marker on success- vmDir.clearProvisioningMarker()- Logger.info("Async VM creation completed successfully", metadata: ["name": name])-- } catch {- // Clear marker and cleanup on failure- vmDir.clearProvisioningMarker()- do {- try vmDir.delete()- } catch let cleanupError {- Logger.error("Failed to clean up VM directory after async creation failure",- metadata: ["error": cleanupError.localizedDescription])- }- Logger.error("Async VM creation failed",- metadata: ["name": name, "error": error.localizedDescription])- }- }- }-- /// Internal create method that skips validation (used by createAsync)- @MainActor- private func createInternal(- name: String,- os: String,- diskSize: UInt64,- cpuCount: Int,- memorySize: UInt64,- display: String,- ipsw: String?,- storage: String? = nil,- unattendedConfig: UnattendedConfig? = nil,- debug: Bool = false,- debugDir: String? = nil,- noDisplay: Bool = true,- vncPort: Int = 0,- vmDir: VMDirectory? = nil- ) async throws {- Logger.info(- "Creating VM (internal)",- metadata: [- "name": name,- "os": os,- "location": storage ?? "default",- ])-- let vm = try await createTempVMConfig(- os: os,- cpuCount: cpuCount,- memorySize: memorySize,- diskSize: diskSize,- display: display- )-- // Track the temp directory for cleanup on failure- let tempVMDir = vm.vmDirContext.dir-- do {- try await vm.setup(- ipswPath: ipsw ?? "none",- cpuCount: cpuCount,- memorySize: memorySize,- diskSize: diskSize,- display: display- )-- // If vmDir was pre-created (async flow), we need to handle finalization differently- if let existingVmDir = vmDir {- // Delete the pre-created directory (with just config and marker)- // and let finalize create it fresh with all the VM files- try existingVmDir.delete()- }-- try vm.finalize(to: name, home: home, storage: storage)- } catch {- // Clean up the temporary VM directory on setup/finalize failure- Logger.info("Cleaning up temporary VM directory after failed creation",- metadata: ["path": tempVMDir.dir.path])- do {- try tempVMDir.delete()- } catch let cleanupError {- Logger.error("Failed to clean up temporary VM directory",- metadata: ["error": cleanupError.localizedDescription])- }- throw error- }-- Logger.info("VM created successfully", metadata: ["name": name])-- // Run unattended setup if config is provided- if let config = unattendedConfig, os.lowercased() == "macos" {- // Update provisioning marker for unattended phase (only if async flow)- if vmDir != nil {- // Re-get the vmDir since we deleted and recreated it- let updatedVmDir = try home.getVMDirectory(name, storage: storage)- try updatedVmDir.saveProvisioningMarker(ProvisioningMarker(operation: "unattended_setup"))- }-- // Wait for the installation VZVirtualMachine to fully release auxiliary storage locks.- Logger.info("Waiting for installation resources to be released before unattended setup")- try await Task.sleep(nanoseconds: 3_000_000_000) // 3 seconds- Logger.info("Starting unattended Setup Assistant automation", metadata: ["name": name])-- // Load the finalized VM- let finalVM = try get(name: name, storage: storage)-- // Run the unattended installer- let installer = UnattendedInstaller()- do {- try await installer.install(- vm: finalVM,- config: config,- vncPort: vncPort,- noDisplay: noDisplay,- debug: debug,- debugDir: debugDir- )- } catch {- // Clean up the finalized VM directory on unattended setup failure- Logger.info("Cleaning up VM after failed unattended setup",- metadata: ["name": name])- do {- let vmDirToDelete = try home.getVMDirectory(name, storage: storage)- try vmDirToDelete.delete()- } catch let cleanupError {- Logger.error("Failed to clean up VM after unattended setup failure",- metadata: ["error": cleanupError.localizedDescription])- }- throw error- }-- Logger.info("Unattended setup completed", metadata: ["name": name])- }- }-/// Run unattended Setup Assistant automation on an existing macOS VM@MainActorpublic func setup(diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swiftindex 5dbeaf9fcc..3c82c2e647 100644--- a/libs/lume/src/Server/MCPServer.swift+++ b/libs/lume/src/Server/MCPServer.swift@@ -16,17 +16,21 @@ final class LumeMCPServer {mcpServer = MCP.Server(name: "lume",version: "1.0.0",- capabilities: .init(tools: .init(listChanged: false))+ capabilities: .init(+ prompts: .init(listChanged: false),+ resources: .init(subscribe: false, listChanged: false),+ tools: .init(listChanged: false)+ ))- await registerTools()+ await registerHandlers()let transport = StdioTransport()try await mcpServer?.start(transport: transport)await mcpServer?.waitUntilCompleted()}- private func registerTools() async {+ private func registerHandlers() async {// Register ListTools handlerawait mcpServer?.withMethodHandler(ListTools.self) { [weak self] _ inguard let self = self else {@@ -44,6 +48,268 @@ final class LumeMCPServer {}return await self.handleToolCall(params)}++ // Register ListResources handler+ await mcpServer?.withMethodHandler(ListResources.self) { [weak self] _ in+ guard let self = self else {+ return ListResources.Result(resources: [])+ }+ return await MainActor.run {+ ListResources.Result(resources: self.resourceDefinitions)+ }+ }++ // Register ReadResource handler+ await mcpServer?.withMethodHandler(ReadResource.self) { [weak self] params in+ guard let self = self else {+ return ReadResource.Result(contents: [])+ }+ return await MainActor.run {+ self.handleReadResource(params)+ }+ }++ // Register ListPrompts handler+ await mcpServer?.withMethodHandler(ListPrompts.self) { [weak self] _ in+ guard let self = self else {+ return ListPrompts.Result(prompts: [])+ }+ return await MainActor.run {+ ListPrompts.Result(prompts: self.promptDefinitions)+ }+ }++ // Register GetPrompt handler+ await mcpServer?.withMethodHandler(GetPrompt.self) { [weak self] params in+ guard let self = self else {+ return GetPrompt.Result(description: nil, messages: [])+ }+ return await MainActor.run {+ self.handleGetPrompt(params)+ }+ }+ }++ // MARK: - Resource Definitions++ private var resourceDefinitions: [Resource] {+ [+ Resource(+ name: "Lume Usage Guide",+ uri: "lume://usage-guide",+ description: "Best practices and workflows for managing macOS VMs with Lume",+ mimeType: "text/markdown"+ ),+ Resource(+ name: "Default Credentials",+ uri: "lume://credentials",+ description: "Default SSH credentials for VMs created with unattended setup",+ mimeType: "text/plain"+ )+ ]+ }++ private func handleReadResource(_ params: ReadResource.Parameters) -> ReadResource.Result {+ switch params.uri {+ case "lume://usage-guide":+ return ReadResource.Result(contents: [+ .text(usageGuideContent, uri: params.uri, mimeType: "text/markdown")+ ])+ case "lume://credentials":+ return ReadResource.Result(contents: [+ .text(credentialsContent, uri: params.uri, mimeType: "text/plain")+ ])+ default:+ return ReadResource.Result(contents: [])+ }+ }++ private var usageGuideContent: String {+ """+ # Lume VM Management Guide++ ## Overview+ Lume manages macOS virtual machines on Apple Silicon. Use these tools to create, run, and manage VMs for sandboxed development and testing.++ ## Typical Workflow++ ### 1. Check Existing VMs+ Always start by listing VMs to see what's available:+ ```+ lume_list_vms+ ```++ ### 2. Create a New VM (if needed)+ Creating a VM takes 15-30 minutes. Use `unattended: "tahoe"` for automatic setup with SSH enabled:+ ```+ lume_create_vm(name: "sandbox", unattended: "tahoe")+ ```+ The tool returns immediately. Poll `lume_list_vms` to monitor progress—status changes from `provisioning (ipsw_install)` → `provisioning (unattended_setup)` → `stopped`.++ ### 3. Start the VM+ Start with optional shared directory for file access:+ ```+ lume_run_vm(name: "sandbox", shared_dir: "~/project", no_display: true)+ ```+ Shared files appear in the VM at `/Volumes/My Shared Files/`.++ ### 4. Execute Commands+ Run commands via SSH (requires `sshpass` installed on host):+ ```+ lume_exec(name: "sandbox", command: "cd /Volumes/My\\\\ Shared\\\\ Files && npm test")+ ```++ ### 5. Stop the VM+ ```+ lume_stop_vm(name: "sandbox")+ ```++ ## Best Practices++ ### VM Naming+ - Use descriptive names: `dev-sandbox`, `test-runner`, `build-agent`+ - Avoid spaces and special characters++ ### Resource Allocation+ - Default: 4 CPU cores, 8GB RAM, 64GB disk+ - For builds: Consider 8 CPU cores, 16GB RAM+ - Disk grows dynamically (sparse files)++ ### Unattended Presets+ - `tahoe`: macOS Tahoe with SSH enabled, user `lume`/`lume`+ - `sequoia`: macOS Sequoia with SSH enabled, user `lume`/`lume`++ ### Golden Images+ Create a fully configured VM, then clone it for fast resets:+ ```+ lume_clone_vm(name: "configured-vm", new_name: "fresh-sandbox")+ ```++ ### Shared Directories+ - Read-write by default+ - Path in VM: `/Volumes/My Shared Files/`+ - Escape spaces in commands: `My\\ Shared\\ Files`++ ## Status Reference++ | Status | Meaning |+ |--------|---------|+ | `stopped` | Ready to start |+ | `running` | VM is active |+ | `provisioning (ipsw_install)` | Installing macOS |+ | `provisioning (unattended_setup)` | Running Setup Assistant |++ ## Limitations+ - Max 2 macOS VMs running simultaneously (Apple licensing)+ - Linux VMs: Unlimited+ - Nested virtualization: Not supported for macOS guests+ """+ }++ private var credentialsContent: String {+ """+ Default credentials for VMs created with --unattended tahoe or sequoia:++ Username: lume+ Password: lume++ SSH is enabled automatically. Connect with:+ ssh lume@<vm-ip-address>++ Get VM IP with lume_get_vm(name: "vm-name")+ """+ }++ // MARK: - Prompt Definitions++ private var promptDefinitions: [Prompt] {+ [+ Prompt(+ name: "create-sandbox",+ description: "Create a new macOS sandbox VM with unattended setup",+ arguments: [+ .init(name: "name", description: "Name for the new VM", required: true)+ ]+ ),+ Prompt(+ name: "run-in-sandbox",+ description: "Run a command in an existing sandbox VM",+ arguments: [+ .init(name: "vm_name", description: "Name of the VM", required: true),+ .init(name: "command", description: "Command to execute", required: true)+ ]+ ),+ Prompt(+ name: "reset-sandbox",+ description: "Reset a sandbox by cloning from a golden image",+ arguments: [+ .init(name: "golden_image", description: "Name of the golden image VM", required: true),+ .init(name: "sandbox_name", description: "Name for the fresh sandbox", required: true)+ ]+ )+ ]+ }++ private func handleGetPrompt(_ params: GetPrompt.Parameters) -> GetPrompt.Result {+ switch params.name {+ case "create-sandbox":+ let vmName = params.arguments?["name"] ?? "sandbox"+ return GetPrompt.Result(+ description: "Create a macOS sandbox VM",+ messages: [+ .user("""+ Create a new macOS sandbox VM named '\(vmName)' with these requirements:+ 1. Use unattended setup (tahoe preset) for automatic configuration+ 2. The VM should have SSH enabled with credentials lume/lume+ 3. Monitor the provisioning status until complete+ 4. Once ready, start the VM in headless mode+ 5. Verify SSH connectivity by running a simple command+ """)+ ]+ )++ case "run-in-sandbox":+ let vmName = params.arguments?["vm_name"] ?? "sandbox"+ let command = params.arguments?["command"] ?? "echo 'Hello from sandbox'"+ return GetPrompt.Result(+ description: "Run command in sandbox VM",+ messages: [+ .user("""+ Run this command in the '\(vmName)' VM:+ ```+ \(command)+ ```++ Steps:+ 1. First check if the VM exists and is running (lume_list_vms)+ 2. If stopped, start it with lume_run_vm+ 3. Wait for it to get an IP address (lume_get_vm)+ 4. Execute the command with lume_exec+ 5. Report the output+ """)+ ]+ )++ case "reset-sandbox":+ let goldenImage = params.arguments?["golden_image"] ?? "golden"+ let sandboxName = params.arguments?["sandbox_name"] ?? "sandbox"+ return GetPrompt.Result(+ description: "Reset sandbox from golden image",+ messages: [+ .user("""+ Reset the sandbox by cloning from the golden image:+ 1. Stop '\(sandboxName)' if it's running+ 2. Delete '\(sandboxName)' if it exists+ 3. Clone '\(goldenImage)' to '\(sandboxName)'+ 4. Start the new '\(sandboxName)' VM+ 5. Verify it's working with a simple SSH command+ """)+ ]+ )++ default:+ return GetPrompt.Result(description: nil, messages: [])+ }}// MARK: - Tool Definitions