carbon

package module
v0.0.0-...-bbe1a6f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

carbon-go

A Go client for carbon mcp: Carbon's Engine API (machines, their files, images) and its MCP tools. Use it to start machines, run commands in them, move files in and out, and make and push images, from Go.

go get github.com/tensorai-co/carbon-go
client, err := carbon.NewClient(ctx, "http://127.0.0.1:8080")
if err != nil {
	return err
}
defer client.Close()

sess, err := client.NewSession(ctx)
if err != nil {
	return err
}
defer sess.Close()

// A machine that keeps running, for commands to run in.
id, err := sess.Machines.Create(ctx, carbon.MachineConfig{
	Image:      "python:3.13-slim",
	Cmd:        []string{"sleep", "infinity"},
	WorkingDir: "/work", // made if the image hasn't one
})
err = sess.Machines.Start(ctx, id)

// A file in, a command run with its output streamed here, a file back out.
err = sess.Files.WriteFile(ctx, id, "/work/main.py", source, nil)
res, err := sess.Machines.Exec(ctx, id, carbon.ExecOptions{
	Cmd:    []string{"python3", "main.py"},
	Stdout: os.Stdout,
	Stderr: os.Stderr,
})
report, err := sess.Files.ReadFile(ctx, id, "/work/report.json")

// Its disk as an image, to start more machines from; then it's gone.
image, err := sess.Machines.Commit(ctx, id, carbon.CommitOptions{Repo: "myapp", Tag: "built"})
err = sess.Machines.Remove(ctx, id, true)

The Engine API needs the server started with --engine, as in carbon mcp -H 127.0.0.1:8080 --engine. examples/session is a whole program.

A Client, and Sessions from it

What it is Lives
carbon.NewClient(ctx, addr, ...Option) Where the server is and how to get in. Opens no connection As long as the program: make one per server
client.NewSession(ctx, ...SessionOption) One session on the server: a WebSocket carrying calls, relayed MCP and byte streams One piece of work. On a host started with --max-sessions 1, the host's one session: it exits when the session closes
client.Ping(ctx) GET /_ping: is the server there, and does it let this client in Doesn't open a session, so it doesn't use up a one-session host

Addresses are http://, https:// (or ws://, wss://, the same), and unix:///path/to/carbon.sock. A path is a prefix the server is behind.

Client options:

  • WithToken: a token from carbon mcp token, as Authorization: Bearer. The Engine API needs the carbon:engine scope, and MCP needs carbon:mcp. Unix sockets, and loopback without a --token-file, need no token.
  • WithHTTPClient: an *http.Client of your own for every request, WebSocket upgrades included: a transport that signs or authenticates requests (below).
  • WithHeaderFunc: headers made fresh for each request, for credentials that expire.
  • WithRetry: how NewSession retries a server that turns it away for now (429, 503, a refused connection): 3 attempts from 200 ms by default. Calls are never retried.
  • WithTLSConfig: for a private CA. WithHeader: a fixed header.

Session options: WithNotifications for server notifications, and WithHTTPTransport for a session that sends each call as its own POST to /mcp: no streams (exec runs to its end and answers with its output, files go whole, no stdin), and only for servers that keep many sessions.

A Session is safe for concurrent use: calls share the connection and are answered as they finish.

A private Cloud Run service

carbon-go has nothing cloud-specific in it. Google's own packages make the ID token, and the Client carries it:

import "google.golang.org/api/idtoken"

// On GCP, as the workload's service account (the metadata server); elsewhere, with option.WithCredentialsFile, or
// google.golang.org/api/impersonate's IDTokenSource and oauth2.NewClient.
hc, err := idtoken.NewClient(ctx, hostURL)
client, err := carbon.NewClient(ctx, hostURL, carbon.WithHTTPClient(hc))
sess, err := client.NewSession(ctx) // one instance, if the service runs --max-sessions 1 with --concurrency 1

Cloud Run asks only whether the caller's identity has run.invoker, so this is the same for every private service, whatever its ingress. When Carbon also checks a --token-file token, send Google's in X-Serverless-Authorization, which Cloud Run reads too, and leave Authorization for Carbon's:

ts, err := idtoken.NewTokenSource(ctx, hostURL)
client, err := carbon.NewClient(ctx, hostURL,
	carbon.WithToken(carbonToken),
	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
	}),
)

What's here

sess.Machines Create, Start, Stop (waits, then kills), Kill, Wait, Remove, Inspect, List (by label), Logs, Commit, Exec
sess.Files Stat, List, Read / ReadFile, Write / WriteFile, Remove, on a running or stopped machine. On a running one, files are where its programs see them: a file written into a tmpfs is in the tmpfs
sess.Images List, Inspect, Pull, Push, Tag, Remove
sess.MCP ListTools, CallTool, and Relay
sess Version, Ping (the Engine API's), Streams, Call for any method by name, and Close
client NewSession, Ping (GET /_ping, no session), Close

Field names are the Engine API's own (Image, Env, Cmd, HostConfig, Rules, …), as its OpenAPI file and the mcp README list them.

  • A machine for Exec needs a command that waits. As in Docker, an image whose command is bash ends at once with no stdin, so give it Cmd: []string{"sleep", "infinity"}.
  • A streamed command's output is written on the connection's reader, so a writer that blocks holds the connection up. Give it a buffer or a pipe that's drained.
  • What's in a tmpfs (HostConfig.Tmpfs) lives in memory, not on the machine's disk, so Commit doesn't save it. It's the place for scratch files, and for anything that mustn't end up in an image.
  • Rules limit what a machine reaches and runs, on top of the server's own: Rules: &carbon.Rules{Deny: []string{"0.0.0.0/0"}, Allow: []string{"pypi.org:443"}}.

Relaying an agent's MCP

A program running an agent can hand the agent's own MCP messages to the server with sess.MCP.Relay(ctx, message). It gives back the server's answer, with the agent's own id, or nil for a notification. Messages for the Engine API (engine/…) are never forwarded: they're answered with -32001 there and then. That way the agent can use the tools, but it can't reconfigure the machines it runs in, even when it shares the program's connection.

Errors

A call the server refuses gives a *carbon.Error. Its Kind is the Engine API's (not_found, conflict, invalid, forbidden, unsupported, failed), or unauthorized and unavailable for an HTTP 401, or a 429 or 503. Match it with errors.Is(err, carbon.ErrNotFound) and the others. A command that exits non-zero isn't an error: its code is in the ExecResult.

Error.Proxy is set when the answer came from something in front of carbon mcp (Cloud Run's front end, a load balancer) rather than Carbon. Its 404 is ErrUnreachable, not ErrNotFound, so a wrong URL, or ingress that won't let the caller in, isn't taken for a missing machine; its 403 (IAM refusing the caller) is ErrForbidden.

Testing

go test -race ./...                                    # frames, addresses, errors, a fake server, a fake Cloud Run front end
CARBON_INTEGRATION=1 go test -race -run Integration -v # against the carbon on the PATH ($CARBON), with real machines

The integration tests start carbon mcp themselves, on loopback with tokens, on a Unix socket, and with --max-sessions 1 (where Client.Ping mustn't use up the one session). They need $CARBON_IMAGE (debian:latest by default) pulled, and on macOS a carbon signed for the hypervisor.

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

Constants

This section is empty.

Variables

View Source
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"}
	ErrUnauthorized = &Error{Kind: "unauthorized"}
	// The server has served its --max-sessions, or the service in front of it has no host free for now (429).
	// 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

func NewClient(ctx context.Context, addr string, opts ...Option) (*Client, error)

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

func (c *Client) Close() error

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

func (c *Client) NewSession(ctx context.Context, opts ...SessionOption) (*Session, error)

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.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks the server is there and lets this Client in, with GET /_ping. It doesn't open a session, so it doesn't use up a host started with --max-sessions. A front end that refuses the request (Cloud Run's IAM, its ingress) answers instead, as an *Error with Proxy set.

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.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches another *Error of the same Kind: errors.Is(err, carbon.ErrNotFound).

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) List

func (f *Files) List(ctx context.Context, id, path string) ([]FileInfo, error)

List gives a folder's entries.

func (*Files) Read

func (f *Files) Read(ctx context.Context, id, path string, w io.Writer) (int64, error)

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.

func (*Files) ReadFile

func (f *Files) ReadFile(ctx context.Context, id, path string) ([]byte, error)

ReadFile gives a file's bytes.

func (*Files) Remove

func (f *Files) Remove(ctx context.Context, id, path string, recursive bool) error

Remove removes a file, or a folder and all in it if recursive.

func (*Files) Stat

func (f *Files) Stat(ctx context.Context, id, path string) (*FileInfo, error)

Stat says what's at path.

func (*Files) Write

func (f *Files) Write(ctx context.Context, id, path string, r io.Reader, opts *WriteOptions) (int64, error)

Write writes what r has as a file, replacing what's there, and says how many bytes. Over a WebSocket they go as frames, as r is read; over HTTP, whole.

func (*Files) WriteFile

func (f *Files) WriteFile(ctx context.Context, id, path string, data []byte, opts *WriteOptions) error

WriteFile writes data as a file, replacing what's there.

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) Inspect

func (i *Images) Inspect(ctx context.Context, name string) (*Image, error)

Inspect says what's known of an image.

func (*Images) List

func (i *Images) List(ctx context.Context) ([]ImageSummary, error)

List gives the images on the server's host.

func (*Images) Pull

func (i *Images) Pull(ctx context.Context, name, platform string) (*Pulled, error)

Pull pulls an image from its registry; platform (linux/amd64) picks a build, or "" for the host's.

func (*Images) Push

func (i *Images) Push(ctx context.Context, name string, opts *PushOptions) (*Pushed, error)

Push pushes an image to its registry, with the server host's login for it.

func (*Images) Remove

func (i *Images) Remove(ctx context.Context, name string) error

Remove forgets an image's name.

func (*Images) Tag

func (i *Images) Tag(ctx context.Context, source, repo, tag string) error

Tag gives an image another name: repo, and tag (latest if "").

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) CallTool

func (m *MCP) CallTool(ctx context.Context, name string, args any) (*ToolResult, error)

CallTool calls a tool with its arguments (a struct or a map, as JSON).

func (*MCP) ListTools

func (m *MCP) ListTools(ctx context.Context) ([]Tool, error)

ListTools gives the server's tools.

func (*MCP) Relay

func (m *MCP) Relay(ctx context.Context, message []byte) ([]byte, error)

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

func (m *Machines) Commit(ctx context.Context, id string, opts CommitOptions) (string, error)

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) Create

func (m *Machines) Create(ctx context.Context, config MachineConfig) (string, error)

Create makes a machine without starting it, and gives back its Id.

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) Inspect

func (m *Machines) Inspect(ctx context.Context, id string) (*Machine, error)

Inspect says what's known of a machine.

func (*Machines) Kill

func (m *Machines) Kill(ctx context.Context, id string) error

Kill ends everything in a machine at once.

func (*Machines) List

func (m *Machines) List(ctx context.Context, labels ...string) ([]MachineSummary, error)

List gives every machine, or with labels (KEY, or KEY=VALUE) only those that have them all.

func (*Machines) Logs

func (m *Machines) Logs(ctx context.Context, id string, tail int) ([]LogLine, error)

Logs gives what a machine's first program wrote: its last tail lines, or all of it if tail is 0.

func (*Machines) Remove

func (m *Machines) Remove(ctx context.Context, id string, force bool) error

Remove removes a stopped machine and its files; force kills it first if it's running.

func (*Machines) Start

func (m *Machines) Start(ctx context.Context, id string) error

Start starts a machine that's made or stopped, and returns once its kernel is up.

func (*Machines) Stop

func (m *Machines) Stop(ctx context.Context, id string, timeout time.Duration) error

Stop asks a machine to stop (SIGTERM), waits timeout (10 seconds if 0), then kills it. It returns once it has stopped.

func (*Machines) Wait

func (m *Machines) Wait(ctx context.Context, id string, timeout time.Duration) (*WaitResult, error)

Wait waits for a machine to end, for at most timeout (0: as long as it takes).

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

func WithHTTPClient(client *http.Client) Option

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

func WithHeader(key, value string) Option

WithHeader sends a header with every request (with the WebSocket's upgrade, for a Session).

func WithHeaderFunc

func WithHeaderFunc(f func(ctx context.Context, h http.Header) error) Option

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

func WithRetry(attempts int, backoff time.Duration) Option

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

func WithTLSConfig(config *tls.Config) Option

WithTLSConfig sets the TLS config for https:// and wss:// (a private CA's certificate, for one).

func WithToken

func WithToken(token string) Option

WithToken sends a token as `Authorization: Bearer`: one from `carbon mcp token`, whose line is in the server's --token-file. Not needed on a Unix socket, or on loopback without a token file.

type Pulled

type Pulled struct {
	ID       string `json:"Id"`
	Platform string `json:"Platform"`
}

Pulled is an image a pull got.

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

func (s *Session) Call(ctx context.Context, method string, params, result any) error

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

func (s *Session) Close() error

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

func (s *Session) Ping(ctx context.Context) error

Ping checks this session reaches the server's Engine API (engine/system.ping). Client.Ping checks the server is there without a session.

func (*Session) Streams

func (s *Session) Streams() bool

Streams reports whether this session carries streams (a WebSocket).

func (*Session) Version

func (s *Session) Version(ctx context.Context) (*SystemVersion, error)

Version says which Carbon the server is, and its Engine API's version.

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

type WaitResult struct {
	StatusCode int  `json:"StatusCode"`
	Ended      bool `json:"Ended"`
}

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址