Connect with the SDK
Run commands, stream output, manage files, and call ports from your code.
The SDK lets your app or agent drive a machine directly: run commands and read their output, keep long-running processes going, read and write files, and send HTTP requests to servers inside the machine. The SDK handles access tokens for you.
What you'll learn
- How to run commands and stream their output
- How to run background processes
- How to read and write files
- How to call a server running in the machine
Before you start
- A running machine (quickstart)
- The TypeScript or Python SDK
Each helper opens one connection that you can reuse for many calls. Close it when you're done. In Python, the helpers are async and work as async context managers.
Note
Connections need a running machine. Call machines.start() first if the machine is paused or hibernated.
Run commands
command() runs a command to completion and returns its output. A string runs through /bin/sh -c, so pipes and && work. Pass an array to run a program directly without a shell.
Commands that exit with a non-zero code return normally, so check the exit code yourself. When the timeout hits, the command is stopped and timedOut is true.
Stream output and send input
Pass output handlers to see output as it arrives, and stdin to feed the command input. Handlers receive raw bytes.
Run background processes
spawn() starts a process and returns right away. Use it for dev servers, watchers, or interactive programs you write to over time. One connection can run many processes at once.
To write to a process, spawn it with stdin: true, then call write() and finish with closeStdin() (close_stdin() in Python). kill() sends KILL.
Work with files
A few details:
write()accepts text or bytes and replaces existing files unless you passoverwrite: false. Setmode(such as'0755') for executables.read()returns bytes and takes anoffsetandlengthto read part of a large file.stat()returns the entry'stype(file,directory,symlink, orother),size,mode, and modification time.list()reportstruncatedwhen it hits itslimit.
Call a server in the machine
connect() gives you an HTTP client for one port. It adds the access token to every request and refreshes it when it expires. Your server must listen on 0.0.0.0.
To call the port from somewhere else, such as a browser, read the URL from port.url and a token from getToken() (get_token() in Python), and send the token in the Metorial-Sandbox-Token header. Networking explains tokens and public ports.
Handle errors
Connection and protocol problems throw SandboxAccessError. Failures tied to a single command throw SandboxCommandError, a subclass. Both carry a code and a retryable flag. File operations add the path, with codes such as not_found, already_exists, and not_empty.
Idle connections close after the machine's connection idle timeout. Pass onNotice (on_notice in Python) to shell() or files() to get a warning before that happens.