Documentation
¶
Overview ¶
Package carbon is a Go client for `carbon mcp`: its Engine API (machines, their files, images), and MCP.
A Client is long-lived: it knows where a server is and how to get in (tokens, headers, an *http.Client of your own), and opens Sessions on it. A Session is one connection, and on the server one session: on a host started with --max-sessions 1 (as a sandbox host on Cloud Run is), each Session gets a host of its own, which exits when the Session is closed.
client, err := carbon.NewClient(ctx, "http://127.0.0.1:8080", carbon.WithToken(token))
defer client.Close()
sess, err := client.NewSession(ctx)
defer sess.Close()
id, err := sess.Machines.Create(ctx, carbon.MachineConfig{Image: "debian:13", Cmd: []string{"sleep", "infinity"}})
err = sess.Machines.Start(ctx, id)
res, err := sess.Machines.Exec(ctx, id, carbon.ExecOptions{Cmd: []string{"make", "test"}, Stdout: os.Stdout, Stderr: os.Stderr})
The server must be started with --engine for the Engine API, and the token (if it needs one) must have the carbon:engine scope. MCP's methods need carbon:mcp.
Nothing here is specific to a cloud. To reach a private Cloud Run service, hand NewClient an *http.Client that adds Google's ID token (google.golang.org/api/idtoken's NewClient) with WithHTTPClient.
Index ¶
- Variables
- type Client
- type CommitOptions
- type Content
- type Error
- type ExecOptions
- type ExecResult
- type FileInfo
- type Files
- func (f *Files) List(ctx context.Context, id, path string) ([]FileInfo, error)
- func (f *Files) Read(ctx context.Context, id, path string, w io.Writer) (int64, error)
- func (f *Files) ReadFile(ctx context.Context, id, path string) ([]byte, error)
- func (f *Files) Remove(ctx context.Context, id, path string, recursive bool) error
- func (f *Files) Stat(ctx context.Context, id, path string) (*FileInfo, error)
- func (f *Files) Write(ctx context.Context, id, path string, r io.Reader, opts *WriteOptions) (int64, error)
- func (f *Files) WriteFile(ctx context.Context, id, path string, data []byte, opts *WriteOptions) error
- type HostConfig
- type Image
- type ImageSummary
- type Images
- func (i *Images) Inspect(ctx context.Context, name string) (*Image, error)
- func (i *Images) List(ctx context.Context) ([]ImageSummary, error)
- func (i *Images) Pull(ctx context.Context, name, platform string) (*Pulled, error)
- func (i *Images) Push(ctx context.Context, name string, opts *PushOptions) (*Pushed, error)
- func (i *Images) Remove(ctx context.Context, name string) error
- func (i *Images) Tag(ctx context.Context, source, repo, tag string) error
- type LogLine
- type MCP
- type Machine
- type MachineConfig
- type MachineState
- type MachineSummary
- type Machines
- func (m *Machines) Commit(ctx context.Context, id string, opts CommitOptions) (string, error)
- func (m *Machines) Create(ctx context.Context, config MachineConfig) (string, error)
- func (m *Machines) Exec(ctx context.Context, id string, opts ExecOptions) (*ExecResult, error)
- func (m *Machines) Inspect(ctx context.Context, id string) (*Machine, error)
- func (m *Machines) Kill(ctx context.Context, id string) error
- func (m *Machines) List(ctx context.Context, labels ...string) ([]MachineSummary, error)
- func (m *Machines) Logs(ctx context.Context, id string, tail int) ([]LogLine, error)
- func (m *Machines) Remove(ctx context.Context, id string, force bool) error
- func (m *Machines) Start(ctx context.Context, id string) error
- func (m *Machines) Stop(ctx context.Context, id string, timeout time.Duration) error
- func (m *Machines) Wait(ctx context.Context, id string, timeout time.Duration) (*WaitResult, error)
- type Mount
- type Notification
- type Option
- func WithHTTPClient(client *http.Client) Option
- func WithHeader(key, value string) Option
- func WithHeaderFunc(f func(ctx context.Context, h http.Header) error) Option
- func WithRetry(attempts int, backoff time.Duration) Option
- func WithTLSConfig(config *tls.Config) Option
- func WithToken(token string) Option
- type Pulled
- type PushOptions
- type Pushed
- type Rules
- type Session
- type SessionOption
- type SystemVersion
- type Tool
- type ToolResult
- type WaitResult
- type WriteOptions
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotFound = &Error{Kind: "not_found"} ErrConflict = &Error{Kind: "conflict"} ErrInvalid = &Error{Kind: "invalid"} ErrForbidden = &Error{Kind: "forbidden"} ErrUnsupported = &Error{Kind: "unsupported"} ErrFailed = &Error{Kind: "failed"} ErrNoMethod = &Error{Kind: "no_method"} // Client.NewSession retries it (WithRetry). ErrUnavailable = &Error{Kind: "unavailable"} // Something in front of the address answered 404: there's no carbon mcp there for this caller (a wrong URL, or // ingress that doesn't let it in). ErrUnreachable = &Error{Kind: "unreachable"} )
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
A Client is where a carbon mcp server is and how to reach it. It opens Sessions, and is safe for concurrent use. Make one per server and keep it.
func NewClient ¶
NewClient makes a Client for the carbon mcp at addr: http://host:port, https://host:port, ws:// and wss:// (the same), or unix:///path/to/carbon.sock. A path is a prefix the server is behind (a trailing /mcp is dropped). It opens no connection: NewSession does.
func (*Client) Close ¶
Close lets go of the Client's idle connections (its own transport's, not a WithHTTPClient one's). Sessions already open aren't affected: close them with their own Close.
func (*Client) NewSession ¶
NewSession opens a session on the server: a WebSocket, carrying calls, relayed MCP messages and byte streams (exec's stdin and output, files) as binary frames. A server that turns it away for now is retried (WithRetry).
The session is the server's until it's closed. On a host started with --max-sessions 1 it's the host's one session, and the host exits when it closes, so close it when the work is done, and not before.
type CommitOptions ¶
type CommitOptions struct {
Repo string `json:"Repo,omitempty"`
Tag string `json:"Tag,omitempty"`
Comment string `json:"Comment,omitempty"`
// Dockerfile instructions for its config: CMD, ENV, LABEL, WORKDIR, ...
Changes []string `json:"Changes,omitempty"`
}
CommitOptions name the image a commit makes, and change its config.
type Content ¶
type Content struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
Content is a piece of a tool's result: text, or an image.
type Error ¶
type Error struct {
Code int
Kind string
Message string
Status int
// The JSON-RPC error's data, as sent.
Data json.RawMessage
// The answer came from something in front of carbon mcp (a load balancer, Cloud Run's front end), not from
// Carbon: an HTTP status whose body isn't Carbon's. Its 404 is ErrUnreachable rather than ErrNotFound, so a
// wrong address, or ingress that won't let this caller in, isn't taken for a missing machine; its 403 (IAM
// refusing the caller) is ErrForbidden, and its 429 and 503 are ErrUnavailable.
Proxy bool
}
An Error is what the server answered a call with: a JSON-RPC error (Code), or an HTTP status before the call got that far (Status: 401 without a good token, 403 for an origin it won't take, 503 once --max-sessions are served). Kind is the Engine API's: not_found, conflict, invalid, forbidden, unsupported, failed.
Compare with errors.Is against ErrNotFound and the others, which match by Kind.
type ExecOptions ¶
type ExecOptions struct {
Cmd []string
Env []string
WorkingDir string
User string
// Killed if it runs longer (0: no limit).
Timeout time.Duration
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
ExecOptions are a command to run in a running machine, and where its input and output go.
Over a WebSocket, a command with Stdin, Stdout or Stderr set is streamed: its input read from Stdin as it runs, its output written as it comes (on the connection's reader, so a writer that blocks holds up the connection). Without them, or over HTTP, it runs to its end, and its output is in the ExecResult (and written to Stdout and Stderr, if they're set). Stdin needs a WebSocket.
type ExecResult ¶
type ExecResult struct {
ExitCode int
// Killed for running past its Timeout (not known for a streamed command, whose code says so: 137).
TimedOut bool
Stdout []byte
Stderr []byte
}
ExecResult is how a command ended, and, if it wasn't streamed, what it wrote.
type FileInfo ¶
type FileInfo struct {
// file, dir or symlink.
Kind string `json:"Kind"`
Size int64 `json:"Size"`
Mode uint32 `json:"Mode"`
UID uint32 `json:"Uid"`
GID uint32 `json:"Gid"`
Modified time.Time `json:"Modified"`
// What a symbolic link points to.
Link string `json:"Link"`
// A folder's entry's name (List).
Name string `json:"Name,omitempty"`
}
FileInfo is what's known of a file.
type Files ¶
type Files struct {
// contains filtered or unexported fields
}
Files are the Engine API's files.* methods: a machine's files, running or stopped. On a running machine they're what its programs see, so a file written into a tmpfs is in the tmpfs.
func (*Files) Read ¶
Read writes a file's bytes to w, and says how many. Over a WebSocket they come as frames, as they're read; over HTTP, whole.
type HostConfig ¶
type HostConfig struct {
// nat (bridge, the default), host, or none.
NetworkMode string `json:"NetworkMode,omitempty"`
// Bytes; the server's default if 0.
Memory int64 `json:"Memory,omitempty"`
// Folders in memory only, as keys: {"/run/secrets": ""}. A tmpfs isn't the disk, so a commit never saves what's in
// one: where secrets go.
Tmpfs map[string]string `json:"Tmpfs,omitempty"`
// SOURCE:TARGET[:ro]: a host folder under the server's --host-dir, or a volume's name.
Binds []string `json:"Binds,omitempty"`
Mounts []Mount `json:"Mounts,omitempty"`
// Lines for its /etc/hosts: NAME:IP.
ExtraHosts []string `json:"ExtraHosts,omitempty"`
}
HostConfig is how a machine sits on its host.
type Image ¶
type Image struct {
ImageSummary
Config struct {
Env []string `json:"Env"`
Entrypoint []string `json:"Entrypoint"`
Cmd []string `json:"Cmd"`
WorkingDir string `json:"WorkingDir"`
User string `json:"User"`
Labels map[string]string `json:"Labels"`
ExposedPorts []string `json:"ExposedPorts"`
Volumes []string `json:"Volumes"`
StopSignal string `json:"StopSignal"`
} `json:"Config"`
History []struct {
Created string `json:"Created"`
CreatedBy string `json:"CreatedBy"`
EmptyLayer bool `json:"EmptyLayer"`
Comment string `json:"Comment"`
} `json:"History"`
}
Image is what engine/images.inspect says of an image.
type ImageSummary ¶
type ImageSummary struct {
// Its whole name: docker.io/library/debian:13.
ID string `json:"Id"`
RepoTags []string `json:"RepoTags"`
Platform string `json:"Platform"`
Created time.Time `json:"Created"`
// Where it came from: pulled, imported, committed from a machine, built.
Source string `json:"Source"`
}
ImageSummary is an image as engine/images.list gives it.
type Images ¶
type Images struct {
// contains filtered or unexported fields
}
Images are the Engine API's images.* methods.
func (*Images) List ¶
func (i *Images) List(ctx context.Context) ([]ImageSummary, error)
List gives the images on the server's host.
func (*Images) Pull ¶
Pull pulls an image from its registry; platform (linux/amd64) picks a build, or "" for the host's.
type LogLine ¶
type LogLine struct {
// stdout or stderr.
Stream string `json:"Stream"`
Text string `json:"Text"`
}
LogLine is a line a machine's first program wrote.
type MCP ¶
type MCP struct {
// contains filtered or unexported fields
}
MCP is the server's MCP side: the tools a model uses. A program that runs an agent can call them itself, or relay the agent's own MCP messages with Relay.
func (*MCP) Relay ¶
Relay forwards one of an agent's MCP messages, as received, and gives back the server's answer to send it: a request's answer, with the agent's own id, or nil for a notification.
It never forwards the Engine API: a message whose method is engine/... is answered here with -32001 (forbidden) and not sent, so an agent sharing the connection can't set its machine up (its keys, its network). An answer the server sends with an error is the agent's to see, so it's in the answer, not an error. The error is for when the message couldn't be relayed at all.
type Machine ¶
type Machine struct {
ID string `json:"Id"`
Name string `json:"Name"`
Image string `json:"Image"`
Platform string `json:"Platform"`
Created time.Time `json:"Created"`
State MachineState `json:"State"`
Config struct {
Hostname string `json:"Hostname"`
Env []string `json:"Env"`
Cmd []string `json:"Cmd"`
Entrypoint []string `json:"Entrypoint"`
WorkingDir string `json:"WorkingDir"`
User string `json:"User"`
Labels map[string]string `json:"Labels"`
} `json:"Config"`
HostConfig struct {
NetworkMode string `json:"NetworkMode"`
ExtraHosts []string `json:"ExtraHosts"`
} `json:"HostConfig"`
NetworkSettings struct {
Ports []string `json:"Ports"`
} `json:"NetworkSettings"`
// Where it last ran: vm/hvf, sandbox/linux, ...
Backend string `json:"Backend"`
}
Machine is what engine/machines.inspect says of a machine.
type MachineConfig ¶
type MachineConfig struct {
// The image it starts from: debian:13, registry.example/ws/8f3a:latest.
Image string `json:"Image"`
// Its name, which is also its Id; one is made from its image if it's empty.
Name string `json:"Name,omitempty"`
// Its host name; its name if it's empty.
Hostname string `json:"Hostname,omitempty"`
// Which build of the image to pull, if it isn't here: linux/arm64, linux/amd64.
Platform string `json:"Platform,omitempty"`
// NAME=VALUE, over the image's.
Env []string `json:"Env,omitempty"`
// What it runs; the image's command if empty. A machine meant for Exec needs one that waits: as in Docker, an
// image whose command is bash ends at once with no stdin. []string{"sleep", "infinity"}.
Cmd []string `json:"Cmd,omitempty"`
WorkingDir string `json:"WorkingDir,omitempty"`
User string `json:"User,omitempty"`
Labels map[string]string `json:"Labels,omitempty"`
HostConfig *HostConfig `json:"HostConfig,omitempty"`
// What it may reach and run, beside the server's own rules.
Rules *Rules `json:"Rules,omitempty"`
}
MachineConfig is what a machine is made with (engine/machines.create): Docker's field names where they mean what Docker's do, and Carbon's Rules.
type MachineState ¶
type MachineState struct {
// created, running or exited.
Status string `json:"Status"`
Running bool `json:"Running"`
ExitCode int `json:"ExitCode"`
Pid int `json:"Pid"`
}
MachineState is whether a machine runs, and how it last ended.
type MachineSummary ¶
type MachineSummary struct {
ID string `json:"Id"`
Name string `json:"Name"`
Image string `json:"Image"`
Created time.Time `json:"Created"`
State string `json:"State"`
Platform string `json:"Platform"`
Labels map[string]string `json:"Labels"`
}
MachineSummary is a machine as engine/machines.list gives it.
type Machines ¶
type Machines struct {
// contains filtered or unexported fields
}
Machines are the Engine API's machines.* methods. A machine is a VM or a process sandbox, with a disk, network and processes of its own.
func (*Machines) Commit ¶
Commit makes an image of a machine's disk, running or stopped: its image, and a layer of what it changed. What's in a tmpfs isn't on the disk, so it isn't in the image. It gives back the image's name.
func (*Machines) Exec ¶
func (m *Machines) Exec(ctx context.Context, id string, opts ExecOptions) (*ExecResult, error)
Exec runs a command in a running machine, and waits for it to end. A command that exits non-zero isn't an error: its code is in the result.
func (*Machines) List ¶
List gives every machine, or with labels (KEY, or KEY=VALUE) only those that have them all.
func (*Machines) Logs ¶
Logs gives what a machine's first program wrote: its last tail lines, or all of it if tail is 0.
func (*Machines) Remove ¶
Remove removes a stopped machine and its files; force kills it first if it's running.
func (*Machines) Start ¶
Start starts a machine that's made or stopped, and returns once its kernel is up.
type Mount ¶
type Mount struct {
// bind, volume or tmpfs.
Type string `json:"Type"`
Source string `json:"Source,omitempty"`
Target string `json:"Target"`
ReadOnly bool `json:"ReadOnly,omitempty"`
}
Mount is one of HostConfig's Mounts.
type Notification ¶
type Notification struct {
Method string
Params json.RawMessage
}
A Notification is a JSON-RPC notification from the server.
type Option ¶
type Option func(*clientOptions)
An Option sets how a Client reaches its server.
func WithHTTPClient ¶
WithHTTPClient uses this client for every request, WebSocket upgrades included: the way in for a transport that signs or authenticates requests, such as google.golang.org/api/idtoken's NewClient for a private Cloud Run service. Its Timeout must be 0 (a Session lives longer than any one timeout; contexts bound each call). It can't be used with WithTLSConfig (set TLS on its transport) or a unix:// address.
func WithHeader ¶
WithHeader sends a header with every request (with the WebSocket's upgrade, for a Session).
func WithHeaderFunc ¶
WithHeaderFunc sets headers made fresh for each request: at a Session's WebSocket upgrade, and for every call of a Session over HTTP. It's for credentials that expire, in a header of your choosing. It runs after WithToken and WithHeader, so it can replace what they set.
Cloud Run reads its ID token from X-Serverless-Authorization as well as Authorization, which leaves Authorization for Carbon's own token:
ts, _ := idtoken.NewTokenSource(ctx, url)
carbon.WithHeaderFunc(func(ctx context.Context, h http.Header) error {
t, err := ts.Token()
if err != nil {
return err
}
h.Set("X-Serverless-Authorization", "Bearer "+t.AccessToken)
return nil
})
func WithRetry ¶
WithRetry sets how NewSession retries a server that turns it away for now: a 429 or 503 (a one-session host on its way out, or a service at its instance limit) or a refused connection. It tries up to attempts times, waiting backoff, then twice that, and so on. The default is 3 attempts from 200 ms; 1 attempt is no retry. Calls are never retried: they aren't idempotent.
func WithTLSConfig ¶
WithTLSConfig sets the TLS config for https:// and wss:// (a private CA's certificate, for one).
type PushOptions ¶
type PushOptions struct {
// Its whole disk as one layer, rather than a layer per step of what made it.
Squash bool `json:"Squash,omitempty"`
// Another name to push it as.
To string `json:"To,omitempty"`
}
PushOptions are how an image is pushed.
type Pushed ¶
type Pushed struct {
Name string `json:"Name"`
Digest string `json:"Digest"`
Layers json.RawMessage `json:"Layers"`
Sent json.RawMessage `json:"Sent"`
}
Pushed is what a push sent.
type Rules ¶
type Rules struct {
// Hosts, addresses or networks, each with an optional :PORT: 0.0.0.0/0, pypi.org:443.
Deny []string `json:"Deny,omitempty"`
Allow []string `json:"Allow,omitempty"`
// Programs by their arguments, as a shell's patterns: "rm -rf *".
DenyExec []string `json:"DenyExec,omitempty"`
}
Rules are Carbon's own: connections and programs refused, or allowed through a refusal. An allow beats a deny.
type Session ¶
type Session struct {
Machines *Machines
Files *Files
Images *Images
MCP *MCP
// contains filtered or unexported fields
}
A Session is one session on a carbon mcp server, from Client.NewSession: one WebSocket (or, with WithHTTPTransport, a POST per call). Its machines, files, images and MCP tools are its fields. It's safe for concurrent use: calls share the connection and are answered as they finish.
func (*Session) Call ¶
Call makes any JSON-RPC call, its result decoded into result (if it isn't nil): an Engine API method by its full name ("engine/machines.list"), or MCP's.
func (*Session) Close ¶
Close ends the session. Calls in flight end with an error. On a host started with --max-sessions 1, the host then exits, and its machines with it.
func (*Session) Ping ¶
Ping checks this session reaches the server's Engine API (engine/system.ping). Client.Ping checks the server is there without a session.
type SessionOption ¶
type SessionOption func(*sessionOptions)
A SessionOption sets how a Session is opened.
func WithHTTPTransport ¶
func WithHTTPTransport() SessionOption
WithHTTPTransport makes a Session that sends each call as its own HTTP POST to the server's /mcp, rather than one WebSocket: no streams (Exec runs to its end, files go whole, no stdin) and no notifications.
Only for servers that keep many sessions. Behind a load balancer in front of one-session hosts (Cloud Run with --max-sessions 1), each call can land on a different host, and each is a session of its own.
func WithNotifications ¶
func WithNotifications(f func(Notification)) SessionOption
WithNotifications is called with each notification the server sends on this Session (MCP's notifications/progress, for one). It's called on the connection's reader, so it shouldn't block. Not with WithHTTPTransport.
type SystemVersion ¶
type SystemVersion struct {
Version string `json:"Version"`
APIVersion string `json:"ApiVersion"`
Os string `json:"Os"`
Arch string `json:"Arch"`
}
SystemVersion is what engine/system.version says of the server.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"inputSchema"`
Annotations json.RawMessage `json:"annotations,omitempty"`
}
Tool is one of the server's tools.
type ToolResult ¶
type ToolResult struct {
Content []Content `json:"content"`
StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
// The call failed (no such machine, a refused path): Content says why. A command that exits non-zero isn't
// this.
IsError bool `json:"isError,omitempty"`
}
ToolResult is what a tool answered.
func (*ToolResult) Text ¶
func (r *ToolResult) Text() string
Text is the result's text, its pieces joined.
type WaitResult ¶
WaitResult is how a machine ended, if it has.
type WriteOptions ¶
type WriteOptions struct {
// Permission bits, as 0o600; a new file's are 0o644 if 0, and an old one keeps its own.
Mode uint32
// user, user:group, or uid:gid, from the machine's /etc/passwd and /etc/group; root's if empty.
Owner string
// Make the folders it's in, if they aren't there.
Parents bool
}
WriteOptions are a written file's mode and owner.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
session
command
A machine's whole life, in one session: made from an image, started, a file written into it, a command run with this program's stdin and its output streamed, then committed as an image (and pushed) if asked, and removed.
|
A machine's whole life, in one session: made from an image, started, a file written into it, a command run with this program's stdin and its output streamed, then committed as an image (and pushed) if asked, and removed. |