Compare commits

...

2 commits

Author SHA1 Message Date
0664591b57
docs: ship illustrated MCP and Tailscale guides for v2.2.0
Some checks are pending
CI / vet-build-test (push) Waiting to run
2026-11-27 21:48:32 -06:00
9f28f979d6
feat: add built-in stdio MCP with explicit write permissions 2026-11-27 21:43:50 -06:00
14 changed files with 1253 additions and 12 deletions

View file

@ -2,14 +2,14 @@
# 📦 devbox
### Your working tree, everywhere. Now with built-in Tailscale. 🔒
### Your working tree, everywhere. Built-in Tailscale. Built-in MCP. 🔒
Continuous file sync for developers: private networking, selective mounts,
conflict copies, snapshot history, and a secret guard that keeps credentials home.
conflict copies, snapshot history, and structured tools for your AI coding agent.
**Linux · macOS · Windows · Raspberry Pi**
[Install](#-install) · [Tailscale quick start](#-tailscale-quick-start) · [Commands](#-commands) · [Configuration](#-configuration) · [Build](#-build-and-release)
[Install](#-install) · [Tailscale quick start](#-tailscale-quick-start) · [Agent MCP](#-built-in-mcp-for-agents) · [Commands](#-commands) · [Configuration](#-configuration) · [Build](#-build-and-release)
</div>
@ -26,6 +26,10 @@ router port forwarding, or reverse proxy is required for this mode.
devbox-hub serve --data ./hub-data --tailscale --tailscale-hostname devbox-hub
```
![Built-in Tailscale flags captured from the devbox-hub CLI](docs/images/tailscale-help.png)
*Actual CLI help, rendered for readability. The hub joins the tailnet itself.*
On first launch, open the authentication URL printed in the terminal. Once
connected, the hub prints its private endpoint:
@ -44,6 +48,52 @@ uses the private URL through that connection. Embedded client networking is not
included in this release. The embedded hub is a separate Tailscale device, even
if its host machine already runs Tailscale.
## 🤖 Built-in MCP for agents
**New in v2.2.0:** connect your coding agent directly to devbox with the built-in
Model Context Protocol server. It ships in the same client binary:
```bash
codex mcp add devbox -- /absolute/path/to/devbox mcp
```
Or configure any agent that accepts `mcpServers` JSON:
```json
{
"mcpServers": {
"devbox": {
"command": "/absolute/path/to/devbox",
"args": ["mcp"]
}
}
}
```
![Actual MCP tool discovery and selected status fields from a live demo](docs/images/mcp-tools.png)
*Captured from the built-in stdio server using an isolated enrolled device.*
Ask your agent to check sync status, diagnose a failing mount, inspect history,
or list conflicts. Default tools inspect the existing enrolled device.
`--allow-writes` enables pause/resume, publish, and mount;
`--allow-writes --allow-destructive` additionally enables restore, deploy, and
unmount. Tools use the CLI's authentication and conflict behavior.
**Tailscale connects your machines; MCP connects your agent.** The hub embeds
Tailscale, client machines use their regular Tailscale connection, and the MCP
server talks locally over stdio. No extra MCP service or Node runtime is needed.
```mermaid
flowchart LR
Agent["AI coding agent"] -->|"local stdio"| MCP["devbox mcp"]
MCP --> Client["Enrolled devbox client"]
Client -->|"regular Tailscale app"| Hub["Hub with embedded Tailscale"]
```
Read the [MCP setup guide](docs/MCP.md) for tool names, configuration, execution
limits, and errors, or the [implementation plan](docs/MCP-PLAN.md) for scope.
## ✨ Why devbox?
Git records the work you choose to commit. devbox continuously mirrors the
@ -200,6 +250,7 @@ probes the host-network API, so it must be replaced for tailnet-only mode.
| Client command | Purpose |
|---|---|
| `devbox mcp` | Serve structured agent tools over local stdio |
| `devbox setup` | Interactive first-run setup |
| `devbox join <hub> <token>` | Enroll this device |
| `devbox publish <localdir> <share>` | Create a share and push its files |
@ -226,7 +277,10 @@ planned, so use a hub for a trusted group rather than mutually untrusted tenants
## 📊 Built-in dashboard
<p align="center"><img src="docs/images/dashboard.png" alt="devbox live sync dashboard" width="860"></p>
<p align="center"><img src="docs/images/dashboard.png" alt="Live devbox dashboard showing three devices and three demo shares" width="1000"></p>
*Live hub dashboard with isolated demo data. The capture uses a local hub; it is
not evidence of production Tailscale enrollment.*
```bash
devbox-hub serve --data ./hub-data --tailscale --dashboard
@ -288,7 +342,7 @@ pinned Tailscale dependency. Downloading prebuilt binaries needs no Go toolchain
go build ./cmd/devbox ./cmd/devbox-hub
go vet ./...
go test -race ./...
VERSION=v2.1.0 ./scripts/build-release.sh
VERSION=v2.2.0 ./scripts/build-release.sh
```
The release script cross-compiles both binaries for six platform/architecture

View file

@ -64,6 +64,7 @@ func main() {
doctorCmd(),
setupCmd(),
versionCmd(),
mcpCmd(),
)
// First run: on a bare `devbox` (no subcommand) on a terminal, offer the setup
// wizard if this machine isn't joined yet and the user hasn't opted out.
@ -313,11 +314,15 @@ func writeJSON(w io.Writer, v any) error {
func logCmd() *cobra.Command {
var asJSON bool
var limit int
cmd := &cobra.Command{
Use: "log <share>",
Short: "🕓 show a share's snapshot history",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if limit < 1 || limit > 100 {
return fmt.Errorf("limit must be between 1 and 100")
}
share := args[0]
dir, err := config.Dir()
if err != nil {
@ -336,6 +341,9 @@ func logCmd() *cobra.Command {
if err != nil {
return err
}
if len(snaps) > limit {
snaps = snaps[:limit]
}
out := cmd.OutOrStdout()
if asJSON {
return writeJSON(out, snaps)
@ -348,6 +356,7 @@ func logCmd() *cobra.Command {
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON")
cmd.Flags().IntVar(&limit, "limit", 100, "maximum snapshots (1-100)")
return cmd
}
@ -1068,15 +1077,18 @@ func doctorCmd() *cobra.Command {
}
// fsnotify watcher (catches inotify exhaustion on Linux).
probe := filepath.Join(os.TempDir(), "devbox-doctor-watch")
_ = os.MkdirAll(probe, 0o755)
if w, err := watch.New(probe, 100*time.Millisecond); err != nil {
check(false, false, "file watcher", err.Error())
probe, probeErr := os.MkdirTemp("", "devbox-doctor-watch-")
if probeErr != nil {
check(false, false, "file watcher", probeErr.Error())
} else {
w.Close()
check(true, false, "file watcher", "fsnotify ok")
if w, err := watch.New(probe, 100*time.Millisecond); err != nil {
check(false, false, "file watcher", err.Error())
} else {
w.Close()
check(true, false, "file watcher", "fsnotify ok")
}
_ = os.RemoveAll(probe)
}
_ = os.RemoveAll(probe)
// macOS Full Disk Access — needed to sync TCC-protected folders
// (~/Desktop, ~/Documents, ~/Downloads, iCloud). A background daemon

337
cmd/devbox/mcp.go Normal file
View file

@ -0,0 +1,337 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"unicode"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/spf13/cobra"
)
const mcpOutputLimit = 1 << 20
const mcpStderrLimit = 64 << 10
func mcpCmd() *cobra.Command {
var writes, destructive bool
var timeout time.Duration
cmd := &cobra.Command{
Use: "mcp", Short: "serve MCP tools over stdin/stdout (inspection only by default)", Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
if destructive && !writes {
return fmt.Errorf("--allow-destructive requires --allow-writes")
}
if timeout <= 0 {
return fmt.Errorf("--command-timeout must be positive")
}
executable, err := os.Executable()
if err != nil {
return err
}
return newMCPServer(executable, writes, destructive, timeout).Run(cmd.Context(), &mcp.StdioTransport{})
},
}
cmd.Flags().BoolVar(&writes, "allow-writes", false, "expose pause, resume, publish, and mount")
cmd.Flags().BoolVar(&destructive, "allow-destructive", false, "also expose restore, deploy, and unmount (requires --allow-writes)")
cmd.Flags().DurationVar(&timeout, "command-timeout", 2*time.Minute, "positive timeout for each tool command, including queue time")
return cmd
}
type mcpArguments struct {
Share string `json:"share"`
LocalDir string `json:"local_dir"`
Snapshot string `json:"snapshot"`
Path string `json:"path"`
ReadOnly bool `json:"read_only"`
Exclude []string `json:"exclude"`
Duration string `json:"duration"`
Limit *int `json:"limit"`
}
type mcpCommandResult struct {
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
ExitCode int `json:"exit_code"`
Truncated bool `json:"truncated"`
Data any `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
type mcpToolSpec struct {
name, description string
fields, required []string
write, destructive, idempotent, openWorld bool
}
func newMCPServer(executable string, writes, destructive bool, timeout time.Duration) *mcp.Server {
server := mcp.NewServer(&mcp.Implementation{Name: "devbox", Version: version}, nil)
// CLI config/state updates are atomic files, but not multi-process transactions.
// Serialize calls in this server to avoid two mutating children losing updates.
gate := make(chan struct{}, 1)
specs := []mcpToolSpec{
{name: "status", description: "Inspect enrollment, mounts, and running daemon state. Does not test hub connectivity.", idempotent: true},
{name: "doctor", description: "Diagnose enrollment, hub connectivity, mounts, and watcher. Failed checks remain in data with isError=true.", idempotent: true, openWorld: true},
{name: "conflicts", description: "List conflict copies across configured mounts; never deletes files.", idempotent: true},
{name: "history", description: "Get the newest share snapshots, bounded by limit (default 20; maximum 100).", fields: []string{"share", "limit"}, required: []string{"share"}, idempotent: true, openWorld: true},
{name: "members", description: "List share members and roles using the enrolled device's access.", fields: []string{"share"}, required: []string{"share"}, idempotent: true, openWorld: true},
{name: "pause", description: "Pause the running sync daemon. Optional positive duration auto-resumes it; omitted means until resume.", fields: []string{"duration"}, write: true, idempotent: false},
{name: "resume", description: "Resume the running sync daemon and catch up configured mounts.", write: true, idempotent: true, openWorld: true},
{name: "publish", description: "Create a hub share and upload a local directory with the existing secret guard. Does not configure a mount.", fields: []string{"share", "local_dir"}, required: []string{"share", "local_dir"}, write: true, openWorld: true},
{name: "mount", description: "Clone and sync a share or share/subpath into a local directory; may merge local files and push changes unless read_only=true. Replaces that mount's configuration and clears its pin. Review conflicts after mounting.", fields: []string{"share", "local_dir", "read_only", "exclude"}, required: []string{"share", "local_dir"}, write: true, destructive: true, openWorld: true},
{name: "restore", description: "Restore a mounted share or relative path from a snapshot, modifying local files and publishing a new head.", fields: []string{"share", "snapshot", "path"}, required: []string{"share", "snapshot"}, write: true, destructive: true, openWorld: true},
{name: "deploy", description: "Rewrite a mount to a snapshot without pushing, then pin it against live advancement.", fields: []string{"share", "snapshot"}, required: []string{"share", "snapshot"}, write: true, destructive: true, idempotent: true, openWorld: true},
{name: "unmount", description: "Remove a share's mount configuration and sync state. Files remain on disk.", fields: []string{"share"}, required: []string{"share"}, write: true, destructive: true},
}
for _, spec := range specs {
if spec.write && !writes {
continue
}
// mount is available with writes as planned, but accurately advertises its
// existing merge/config-replacement behavior as potentially destructive.
if (spec.name == "restore" || spec.name == "deploy" || spec.name == "unmount") && !destructive {
continue
}
props := map[string]any{}
for _, field := range spec.fields {
props[field] = mcpFieldSchema(field, spec.name)
}
schema := map[string]any{"type": "object", "properties": props, "additionalProperties": false}
if len(spec.required) > 0 {
schema["required"] = spec.required
}
server.AddTool(&mcp.Tool{
Name: "devbox_" + spec.name, Description: spec.description, InputSchema: schema,
OutputSchema: map[string]any{"type": "object", "properties": map[string]any{
"stdout": map[string]any{"type": "string"}, "stderr": map[string]any{"type": "string"},
"exit_code": map[string]any{"type": "integer"}, "truncated": map[string]any{"type": "boolean"},
"data": map[string]any{"description": "Parsed CLI JSON, when complete and valid (object or array)."}, "error": map[string]any{"type": "string"},
}, "required": []string{"stdout", "stderr", "exit_code", "truncated"}, "additionalProperties": false},
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !spec.write, DestructiveHint: &spec.destructive, IdempotentHint: spec.idempotent, OpenWorldHint: &spec.openWorld},
}, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args, err := mcpCommandArgs(spec, req.Params.Arguments)
if err != nil {
return mcpResult(mcpCommandResult{ExitCode: -1, Error: err.Error()}), nil
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
select {
case gate <- struct{}{}:
defer func() { <-gate }()
case <-ctx.Done():
return mcpResult(mcpCommandResult{ExitCode: -1, Error: ctx.Err().Error()}), nil
}
return mcpResult(runMCPCommand(ctx, executable, args)), nil
})
}
return server
}
func mcpFieldSchema(field, tool string) map[string]any {
switch field {
case "limit":
return map[string]any{"type": "integer", "minimum": 1, "maximum": 100, "default": 20, "description": "Maximum newest snapshots to return."}
case "read_only":
return map[string]any{"type": "boolean", "default": false, "description": "Pull only; never push local files."}
case "exclude":
return map[string]any{"type": "array", "maxItems": 100, "items": map[string]any{"type": "string", "minLength": 1, "maxLength": 4096}, "description": "Device-local gitignore patterns layered over .devignore."}
case "local_dir":
return map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": "Absolute local directory path. Shell characters are literal; no expansion."}
case "snapshot":
return map[string]any{"type": "string", "pattern": "^[a-f0-9]{64}$", "description": "Full 64-character snapshot ID from devbox_history."}
case "duration":
return map[string]any{"type": "string", "minLength": 1, "maxLength": 128, "description": "Positive Go duration, e.g. 30m or 2h; omitted pauses until resume."}
case "path":
return map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": "Relative forward-slash file path within the share; no dot or parent components."}
default:
desc := "Share name (letters, digits, dots, underscores, hyphens; no leading dot or hyphen)."
if tool == "mount" {
desc += " Optionally append /relative/subpath."
}
return map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": desc}
}
}
var mcpSharePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
var mcpSnapshotPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
func mcpCommandArgs(spec mcpToolSpec, raw json.RawMessage) ([]string, error) {
if len(raw) == 0 {
raw = []byte("{}")
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil || fields == nil {
return nil, fmt.Errorf("arguments must be an object")
}
allowed := map[string]bool{}
for _, k := range spec.fields {
allowed[k] = true
}
for k, v := range fields {
if !allowed[k] {
return nil, fmt.Errorf("unknown argument %q", k)
}
if bytes.Equal(bytes.TrimSpace(v), []byte("null")) {
return nil, fmt.Errorf("%s must not be null", k)
}
}
for _, k := range spec.required {
if _, ok := fields[k]; !ok {
return nil, fmt.Errorf("%s is required", k)
}
}
var a mcpArguments
if err := json.Unmarshal(raw, &a); err != nil {
return nil, fmt.Errorf("invalid arguments: %w", err)
}
for k, v := range map[string]string{"share": a.Share, "local_dir": a.LocalDir, "snapshot": a.Snapshot, "path": a.Path, "duration": a.Duration} {
if _, ok := fields[k]; ok && (v == "" || len(v) > 4096 || strings.IndexFunc(v, unicode.IsControl) >= 0) {
return nil, fmt.Errorf("%s must be nonempty, at most 4096 bytes, and contain no control characters", k)
}
}
if a.Share != "" {
share, sub := splitShare(a.Share)
if !mcpSharePattern.MatchString(share) || strings.HasSuffix(share, ".") {
return nil, fmt.Errorf("invalid share name")
}
if strings.Contains(a.Share, "/") && (spec.name != "mount" || !mcpRelativePath(sub)) {
return nil, fmt.Errorf("only mount accepts share/subpath; subpath must be a safe relative path")
}
}
if a.LocalDir != "" && !filepath.IsAbs(a.LocalDir) {
return nil, fmt.Errorf("local_dir must be an absolute path")
}
if a.Snapshot != "" && !mcpSnapshotPattern.MatchString(a.Snapshot) {
return nil, fmt.Errorf("snapshot must be a full lowercase 64-character hex ID")
}
if a.Path != "" && !mcpRelativePath(a.Path) {
return nil, fmt.Errorf("path must be relative without dot or parent components")
}
if a.Duration != "" {
d, err := time.ParseDuration(a.Duration)
if err != nil || d <= 0 || len(a.Duration) > 128 {
return nil, fmt.Errorf("duration must be a positive Go duration, e.g. 30m")
}
}
if len(a.Exclude) > 100 {
return nil, fmt.Errorf("exclude supports at most 100 patterns")
}
for _, p := range a.Exclude {
if p == "" || len(p) > 4096 || strings.IndexFunc(p, unicode.IsControl) >= 0 {
return nil, fmt.Errorf("invalid exclude pattern")
}
}
command := spec.name
if command == "history" {
command = "log"
}
args := []string{command}
switch spec.name {
case "status", "doctor", "conflicts":
args = append(args, "--json")
case "history":
limit := 20
if a.Limit != nil {
limit = *a.Limit
}
if limit < 1 || limit > 100 {
return nil, fmt.Errorf("limit must be between 1 and 100")
}
args = append(args, "--json", fmt.Sprintf("--limit=%d", limit))
case "pause":
if a.Duration != "" {
args = append(args, "--for="+a.Duration)
}
case "mount":
if a.ReadOnly {
args = append(args, "--ro")
}
for _, p := range a.Exclude {
args = append(args, "--exclude="+p)
}
}
args = append(args, "--")
switch spec.name {
case "history", "members", "unmount":
args = append(args, a.Share)
case "publish":
args = append(args, a.LocalDir, a.Share)
case "mount":
args = append(args, a.Share, a.LocalDir)
case "restore", "deploy":
args = append(args, a.Share, a.Snapshot)
if a.Path != "" {
args = append(args, a.Path)
}
}
return args, nil
}
func mcpRelativePath(p string) bool {
if p == "" || strings.HasPrefix(p, "-") || strings.ContainsAny(p, `\:`) || strings.IndexFunc(p, unicode.IsControl) >= 0 {
return false
}
for _, part := range strings.Split(p, "/") {
if part == "" || part == "." || part == ".." {
return false
}
}
return true
}
// Keep draining after the cap so a noisy child cannot deadlock on a full pipe.
type mcpCapture struct {
buffer bytes.Buffer
limit int
truncated bool
}
func (b *mcpCapture) Write(p []byte) (int, error) {
n := len(p)
if len(p) > b.limit-b.buffer.Len() {
p = p[:b.limit-b.buffer.Len()]
b.truncated = true
}
_, _ = b.buffer.Write(p)
return n, nil
}
func runMCPCommand(ctx context.Context, executable string, args []string) mcpCommandResult {
out, stderr := &mcpCapture{limit: mcpOutputLimit}, &mcpCapture{limit: mcpStderrLimit}
cmd := exec.CommandContext(ctx, executable, args...)
cmd.Stdout, cmd.Stderr = out, stderr
cmd.Stdin = nil // Commands must never prompt or consume MCP protocol input.
cmd.WaitDelay = time.Second
err := cmd.Run()
result := mcpCommandResult{Stdout: strings.ToValidUTF8(out.buffer.String(), ""), Stderr: strings.ToValidUTF8(stderr.buffer.String(), ""), Truncated: out.truncated || stderr.truncated}
if err != nil {
result.ExitCode = -1
if cmd.ProcessState != nil {
result.ExitCode = cmd.ProcessState.ExitCode()
}
result.Error = err.Error()
}
if ctx.Err() != nil {
result.Error = ctx.Err().Error() + "; completed side effects are not rolled back; inspect state before retrying"
}
if !out.truncated {
var data any
if json.Unmarshal(out.buffer.Bytes(), &data) == nil {
result.Data = data
}
}
return result
}
func mcpResult(result mcpCommandResult) *mcp.CallToolResult {
// Emit the same envelope as text for clients without structured-content support.
data, _ := json.Marshal(result)
return &mcp.CallToolResult{IsError: result.Error != "", StructuredContent: result, Content: []mcp.Content{&mcp.TextContent{Text: string(data)}}}
}

545
cmd/devbox/mcp_test.go Normal file
View file

@ -0,0 +1,545 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/shoemoney/devbox/internal/config"
"github.com/shoemoney/devbox/internal/control"
"github.com/shoemoney/devbox/internal/daemon"
"github.com/shoemoney/devbox/internal/hub"
"github.com/shoemoney/devbox/internal/hub/blobstore"
"github.com/shoemoney/devbox/internal/hub/meta"
"github.com/shoemoney/devbox/internal/identity"
"github.com/shoemoney/devbox/internal/ignore"
"github.com/shoemoney/devbox/internal/secret"
"github.com/shoemoney/devbox/internal/syncer"
"github.com/shoemoney/devbox/internal/transport"
"github.com/shoemoney/devbox/pkg/proto"
)
// DEVBOX_MCP_TEST_BINARY reruns these protocol checks against a packaged binary.
// Otherwise build the actual command with the race detector, not a test shim.
func TestMCPStdio(t *testing.T) {
binary := os.Getenv("DEVBOX_MCP_TEST_BINARY")
if binary == "" {
binary = filepath.Join(t.TempDir(), "devbox")
if runtime.GOOS == "windows" {
binary += ".exe"
}
build := exec.Command("go", "build", "-race", "-o", binary, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build actual binary: %v\n%s", err, out)
}
}
t.Run("permissions-and-errors", func(t *testing.T) {
for _, mode := range []struct {
flags []string
count int
}{{nil, 5}, {[]string{"--allow-writes"}, 9}, {[]string{"--allow-writes", "--allow-destructive"}, 12}} {
t.Run(fmt.Sprint(mode.count), func(t *testing.T) {
cfg := t.TempDir()
cs := mcpTestClient(t, binary, cfg, mode.flags...)
listed, err := cs.ListTools(t.Context(), nil)
if err != nil {
t.Fatal(err)
}
if len(listed.Tools) != mode.count {
t.Fatalf("tool count %d, want %d", len(listed.Tools), mode.count)
}
names := map[string]bool{}
for _, tool := range listed.Tools {
names[tool.Name] = true
if tool.InputSchema == nil || tool.OutputSchema == nil || tool.Annotations == nil {
t.Fatalf("missing schema/annotations: %s", tool.Name)
}
read := tool.Name == "devbox_status" || tool.Name == "devbox_doctor" || tool.Name == "devbox_conflicts" || tool.Name == "devbox_history" || tool.Name == "devbox_members"
if tool.Annotations.ReadOnlyHint != read {
t.Fatalf("wrong read annotation: %s", tool.Name)
}
}
for _, name := range []string{"devbox_status", "devbox_doctor", "devbox_conflicts", "devbox_history", "devbox_members"} {
if !names[name] {
t.Fatalf("missing %s", name)
}
}
for _, name := range []string{"devbox_pause", "devbox_resume", "devbox_publish", "devbox_mount"} {
if names[name] != (mode.count >= 9) {
t.Fatalf("bad gating %s", name)
}
}
for _, name := range []string{"devbox_restore", "devbox_deploy", "devbox_unmount"} {
if names[name] != (mode.count == 12) {
t.Fatalf("bad gating %s", name)
}
}
got := mcpCall(t, cs, "status", nil, false)
var status statusJSON
mcpData(t, got, &status)
if status.Joined {
t.Fatal("fabricated enrollment")
}
doctor := mcpCall(t, cs, "doctor", nil, true)
var checks []struct{ Name, Status, Detail string }
mcpData(t, doctor, &checks)
if doctor.ExitCode == 0 || len(checks) != 1 || checks[0].Name != "identity" || checks[0].Status != "fail" {
t.Fatalf("lost failed diagnostics: %+v", doctor)
}
mcpCall(t, cs, "conflicts", nil, false)
mcpCall(t, cs, "history", map[string]any{"share": "demo"}, true)
if mode.count == 5 {
for _, name := range []string{"pause", "resume", "publish", "mount", "restore", "deploy", "unmount"} {
_, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "devbox_" + name, Arguments: map[string]any{}})
if err == nil {
t.Fatalf("disabled tool callable: %s", name)
}
}
}
// A command error must leave stdout readable as protocol traffic.
mcpCall(t, cs, "status", nil, false)
})
}
for _, flags := range [][]string{{"--allow-destructive"}, {"--command-timeout=0s"}, {"--command-timeout=-1s"}} {
cmd := exec.Command(binary, append([]string{"mcp"}, flags...)...)
cmd.Env = mcpTestEnv(t.TempDir())
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err == nil || stdout.Len() != 0 || stderr.Len() == 0 {
t.Fatalf("invalid flags accepted or stdout polluted: %v", flags)
}
}
})
t.Run("input-validation", func(t *testing.T) {
cs := mcpTestClient(t, binary, t.TempDir(), "--allow-writes", "--allow-destructive")
for _, tc := range []struct {
name string
args any
}{
{"status", map[string]any{"command": "whoami"}},
{"conflicts", map[string]any{"rm": true}},
{"history", map[string]any{"share": "--help"}},
{"history", map[string]any{"share": "demo; touch /tmp/unwanted"}},
{"history", map[string]any{"share": "demo", "limit": 0}},
{"history", map[string]any{"share": "demo", "limit": 101}},
{"history", map[string]any{"share": "demo", "limit": 1.5}},
{"history", map[string]any{"share": "demo", "limit": nil}},
{"history", map[string]any{}},
{"history", map[string]any{"share": "demo/sub"}},
{"mount", map[string]any{"share": "demo/../escape", "local_dir": t.TempDir()}},
{"mount", map[string]any{"share": "demo", "local_dir": "--help"}},
{"mount", map[string]any{"share": "demo", "local_dir": t.TempDir(), "read_only": "true"}},
{"mount", map[string]any{"share": "demo", "local_dir": t.TempDir(), "exclude": []string{"x\n--help"}}},
{"publish", map[string]any{"share": "demo", "local_dir": "relative"}},
{"pause", map[string]any{"duration": "-1s"}},
{"pause", map[string]any{"duration": "1s --help"}},
{"restore", map[string]any{"share": "demo", "snapshot": "--help"}},
{"restore", map[string]any{"share": "demo", "snapshot": strings.Repeat("a", 64), "path": "../escape"}},
{"deploy", map[string]any{"share": "demo", "snapshot": strings.Repeat("a", 64), "path": "file"}},
{"unmount", map[string]any{"share": "demo\x00evil"}},
} {
r := mcpCall(t, cs, tc.name, tc.args, true)
if r.ExitCode != -1 || r.Stdout != "" || r.Stderr != "" {
t.Fatalf("invalid input reached child: %s %+v", tc.name, r)
}
}
mcpCall(t, cs, "status", nil, false)
})
t.Run("actual-isolated-hub", func(t *testing.T) { mcpTestHub(t, binary) })
t.Run("cancellation-and-timeout", func(t *testing.T) { mcpTestCancellation(t, binary) })
t.Run("output-cap", func(t *testing.T) {
cfg := t.TempDir()
dir := filepath.Join(cfg, "devbox")
if _, err := identity.LoadOrCreate(dir); err != nil {
t.Fatal(err)
}
d := config.Daemon{Hub: "http://127.0.0.1:1", Bearer: "fixture-secret-must-not-appear"}
for i := 0; i < 10000; i++ {
d.Mounts = append(d.Mounts, config.Mount{Share: fmt.Sprintf("share%d", i), Local: "/unused/" + strings.Repeat("x", 128)})
}
if err := config.SaveDaemon(dir, d); err != nil {
t.Fatal(err)
}
cs := mcpTestClient(t, binary, cfg)
r := mcpCall(t, cs, "status", nil, false)
if !r.Truncated || len(r.Stdout) != mcpOutputLimit || r.Data != nil {
t.Fatalf("cap not enforced: bytes=%d, truncated=%v", len(r.Stdout), r.Truncated)
}
if strings.Contains(r.Stdout, d.Bearer) {
t.Fatal("bearer leaked")
}
mcpCall(t, cs, "history", map[string]any{"share": "demo", "limit": 0}, true)
})
}
func mcpTestEnv(cfg string) []string {
env := []string{}
for _, v := range os.Environ() {
if !strings.HasPrefix(v, "XDG_CONFIG_HOME=") && !strings.HasPrefix(v, "GORACE=") {
env = append(env, v)
}
}
return append(env, "XDG_CONFIG_HOME="+cfg, "GORACE=atexit_sleep_ms=0")
}
func mcpTestClient(t *testing.T, binary, cfg string, flags ...string) *mcp.ClientSession {
t.Helper()
cmd := exec.Command(binary, append([]string{"mcp"}, flags...)...)
cmd.Env = mcpTestEnv(cfg)
var stderr bytes.Buffer
cmd.Stderr = &stderr
client := mcp.NewClient(&mcp.Implementation{Name: "devbox-mcp-test", Version: "1"}, nil)
cs, err := client.Connect(t.Context(), &mcp.CommandTransport{Command: cmd}, nil)
if err != nil {
t.Fatalf("stdio initialize: %v; stderr: %s", err, stderr.String())
}
t.Cleanup(func() {
if err := cs.Close(); err != nil {
t.Errorf("stdio close: %v", err)
}
if stderr.Len() != 0 {
t.Errorf("unexpected server stderr: %s", stderr.String())
}
})
return cs
}
func mcpCall(t *testing.T, cs *mcp.ClientSession, name string, args any, wantError bool) mcpCommandResult {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
defer cancel()
r, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "devbox_" + name, Arguments: args})
if err != nil {
t.Fatalf("%s protocol call: %v", name, err)
}
if r.IsError != wantError {
t.Fatalf("%s isError=%v, want %v: %+v", name, r.IsError, wantError, r.Content)
}
raw, err := json.Marshal(r.StructuredContent)
if err != nil {
t.Fatal(err)
}
var result mcpCommandResult
if err := json.Unmarshal(raw, &result); err != nil {
t.Fatal(err)
}
if len(r.Content) != 1 || r.Content[0].(*mcp.TextContent).Text == "" {
t.Fatalf("missing readable result: %s", name)
}
var text mcpCommandResult
if err := json.Unmarshal([]byte(r.Content[0].(*mcp.TextContent).Text), &text); err != nil || text.Stdout != result.Stdout || text.Error != result.Error {
t.Fatalf("text/structured mismatch: %s", name)
}
return result
}
func mcpData(t *testing.T, r mcpCommandResult, dst any) {
t.Helper()
b, err := json.Marshal(r.Data)
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(b, dst); err != nil {
t.Fatal(err)
}
}
func mcpTestHub(t *testing.T, binary string) {
db, err := meta.Open(filepath.Join(t.TempDir(), "hub.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
store, err := blobstore.NewDisk(t.TempDir())
if err != nil {
t.Fatal(err)
}
server := httptest.NewServer(hub.NewServer(db, store).Handler())
defer server.Close()
cfg := t.TempDir()
dir := filepath.Join(cfg, "devbox")
if err := db.CreateToken(hub.HashToken("isolated-mcp-fixture"), time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
joined, err := joinHub(dir, server.URL, "isolated-mcp-fixture")
if err != nil {
t.Fatal(err)
}
cs := mcpTestClient(t, binary, cfg, "--allow-writes", "--allow-destructive")
inspection := mcpTestClient(t, binary, cfg)
src := t.TempDir()
content := "MCP fixture first version\n"
if err := os.WriteFile(filepath.Join(src, "hello.txt"), []byte(content), 0600); err != nil {
t.Fatal(err)
}
mcpCall(t, cs, "publish", map[string]any{"share": "fixture", "local_dir": src}, false)
client := transport.New(server.URL)
client.SetBearer(joined.Bearer)
initial, err := client.Log("fixture")
if err != nil || len(initial) != 1 {
t.Fatalf("initial snapshot: %v", err)
}
// A second enrolled device exercises actual two-way mount and creates history
// without racing any daemon or touching the worker's own configuration.
cfg2 := t.TempDir()
dir2 := filepath.Join(cfg2, "devbox")
if err := db.CreateToken(hub.HashToken("second-mcp-fixture"), time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
if _, err := joinHub(dir2, server.URL, "second-mcp-fixture"); err != nil {
t.Fatal(err)
}
cs2 := mcpTestClient(t, binary, cfg2, "--allow-writes")
// Shell syntax is a literal directory name; never interpreted or expanded.
dst := filepath.Join(t.TempDir(), "literal $(echo injected); --help")
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst, "exclude": []string{"--ro"}}, false)
got, err := os.ReadFile(filepath.Join(dst, "hello.txt"))
if err != nil || string(got) != content {
t.Fatal("mount did not download fixture")
}
if err := os.WriteFile(filepath.Join(dst, "hello.txt"), []byte("second version\n"), 0600); err != nil {
t.Fatal(err)
}
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst}, false)
// Multiple distinct versions prove default and explicit history limits.
ig, err := syncer.LoadIgnoreWith(dst, nil)
if err != nil {
t.Fatal(err)
}
for i := 0; i < 22; i++ {
if err := os.WriteFile(filepath.Join(dst, "hello.txt"), []byte(fmt.Sprintf("version %d\n", i)), 0600); err != nil {
t.Fatal(err)
}
head, err := client.Head("fixture")
if err != nil {
t.Fatal(err)
}
if err := pushFixture(client, dst, ig, head); err != nil {
t.Fatal(err)
}
}
history := mcpCall(t, inspection, "history", map[string]any{"share": "fixture"}, false)
var snaps []proto.SnapshotInfo
mcpData(t, history, &snaps)
if len(snaps) != 20 {
t.Fatalf("default limit=%d", len(snaps))
}
latest := snaps[0].ID
history = mcpCall(t, inspection, "history", map[string]any{"share": "fixture", "limit": 1}, false)
mcpData(t, history, &snaps)
if len(snaps) != 1 || snaps[0].ID != latest {
t.Fatal("limit/order mismatch")
}
mcpCall(t, inspection, "members", map[string]any{"share": "fixture"}, false)
mcpCall(t, cs, "mount", map[string]any{"share": "fixture", "local_dir": src, "read_only": true}, false)
mcpCall(t, cs, "deploy", map[string]any{"share": "fixture", "snapshot": initial[0].ID}, false)
got, err = os.ReadFile(filepath.Join(src, "hello.txt"))
if err != nil || string(got) != content {
t.Fatal("deploy did not restore original file")
}
d, err := config.LoadDaemon(dir)
if err != nil || len(d.Mounts) != 1 || !d.Mounts[0].Pinned {
t.Fatal("deploy pin missing")
}
head, err := client.Head("fixture")
if err != nil || head != latest {
t.Fatal("deploy changed hub head")
}
// Restore requires a read-write mount, so re-mount the second device to pick
// up the latest head, then opt that MCP process into destructive operations.
cs2destructive := mcpTestClient(t, binary, cfg2, "--allow-writes", "--allow-destructive")
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst}, false)
mcpCall(t, cs2destructive, "restore", map[string]any{"share": "fixture", "snapshot": initial[0].ID, "path": "hello.txt"}, false)
got, err = os.ReadFile(filepath.Join(dst, "hello.txt"))
if err != nil || string(got) != content {
t.Fatal("restore did not restore original file")
}
head, err = client.Head("fixture")
if err != nil || head == latest {
t.Fatal("restore did not publish new head")
}
if err := os.WriteFile(filepath.Join(src, "hello.conflict-fixture-1.txt"), []byte("conflict"), 0600); err != nil {
t.Fatal(err)
}
conflicts := mcpCall(t, inspection, "conflicts", nil, false)
var copies []struct{ Share, Path string }
mcpData(t, conflicts, &copies)
if len(copies) != 1 || copies[0].Share != "fixture" {
t.Fatal("conflict missing")
}
// A real control server and daemon instance prove pause/resume IPC without
// starting a watcher or syncing background data on the shared host.
if runtime.GOOS != "windows" {
dmn, err := daemon.New(dir, d, "mcp-fixture", func(string, ...any) {})
if err != nil {
t.Fatal(err)
}
controlCtx, stop := context.WithCancel(t.Context())
defer stop()
if _, err := control.Serve(controlCtx, dir, dmn, nil); err != nil {
t.Fatal(err)
}
mcpCall(t, cs, "pause", map[string]any{"duration": "1h"}, false)
status := mcpCall(t, inspection, "status", nil, false)
var st statusJSON
mcpData(t, status, &st)
if !st.Live || !st.Paused {
t.Fatal("pause not reflected in live status")
}
mcpCall(t, cs, "resume", nil, false)
if dmn.StateSnapshot().Paused {
t.Fatal("resume did not clear pause")
}
}
mcpCall(t, cs, "unmount", map[string]any{"share": "fixture"}, false)
if _, err := os.Stat(filepath.Join(src, "hello.txt")); err != nil {
t.Fatal("unmount removed files")
}
d, err = config.LoadDaemon(dir)
if err != nil || len(d.Mounts) != 0 {
t.Fatal("unmount retained mount")
}
// Inspect result envelopes, including failed commands, for private material.
for _, result := range []mcpCommandResult{history, conflicts, mcpCall(t, inspection, "doctor", nil, false)} {
b, _ := json.Marshal(result)
if strings.Contains(string(b), joined.Bearer) || strings.Contains(string(b), "DEVBOX PRIVATE KEY") {
t.Fatal("private material in MCP result")
}
}
}
func pushFixture(c *transport.Client, dir string, ig *ignore.Matcher, head string) error {
guard, err := secret.New(nil)
if err != nil {
return err
}
result, err := syncer.Push(c, dir, "fixture", "", ig, guard, head, nil)
if err == nil && result.Conflict {
return fmt.Errorf("fixture push unexpectedly conflicted")
}
return err
}
func mcpTestCancellation(t *testing.T, binary string) {
for _, kind := range []string{"cancel", "timeout"} {
t.Run(kind, func(t *testing.T) {
started, ended := make(chan struct{}), make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != proto.PathLog {
http.NotFound(w, r)
return
}
close(started)
<-r.Context().Done()
close(ended)
}))
defer func() { server.CloseClientConnections(); server.Close() }()
cfg := t.TempDir()
dir := filepath.Join(cfg, "devbox")
if _, err := identity.LoadOrCreate(dir); err != nil {
t.Fatal(err)
}
if err := config.SaveDaemon(dir, config.Daemon{Hub: server.URL, Bearer: "isolated-fake-bearer"}); err != nil {
t.Fatal(err)
}
flags := []string{}
if kind == "timeout" {
flags = append(flags, "--command-timeout=750ms")
}
cs := mcpTestClient(t, binary, cfg, flags...)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
type response struct {
r *mcp.CallToolResult
err error
}
done := make(chan response, 1)
go func() {
r, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "devbox_history", Arguments: map[string]any{"share": "demo"}})
done <- response{r, err}
}()
select {
case <-started:
case <-time.After(10 * time.Second):
t.Fatal("child did not reach HTTP request")
}
if kind == "cancel" {
cancel()
}
select {
case <-ended:
case <-time.After(5 * time.Second):
t.Fatal("cancellation did not terminate child HTTP connection")
}
select {
case got := <-done:
if kind == "timeout" {
if got.err != nil || got.r == nil || !got.r.IsError {
t.Fatalf("timeout lost tool error: %v", got.err)
}
b, _ := json.Marshal(got.r.StructuredContent)
if !strings.Contains(string(b), "context deadline exceeded") || !strings.Contains(string(b), "not rolled back") {
t.Fatal("missing timeout/retry explanation")
}
} else if got.err == nil && (got.r == nil || !got.r.IsError) {
t.Fatal("cancelled command reported success")
}
case <-time.After(5 * time.Second):
t.Fatal("call did not finish after cancellation")
}
// Completion and a subsequent call prove the gate/stdio session survives.
mcpCall(t, cs, "status", nil, false)
})
}
}
func TestMCPCapture(t *testing.T) {
for _, limit := range []int{0, 1, 10} {
b := &mcpCapture{limit: limit}
for i := 0; i < 3; i++ {
if n, err := b.Write([]byte("0123456789")); err != nil || n != 10 {
t.Fatal("writer must drain all bytes")
}
}
if b.buffer.Len() != limit || !b.truncated {
t.Fatal("capture exceeded bound")
}
}
}
// This subprocess exercises both pipe-draining paths and nonzero exit handling;
// the stdio suite separately exercises the stdout cap on the actual CLI binary.
func TestMCPCommandCapture(t *testing.T) {
t.Setenv("DEVBOX_MCP_COMMAND_FIXTURE", "1")
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
got := runMCPCommand(ctx, executable, []string{"-test.run=^TestMCPCommandFixture$", "--"})
if got.ExitCode != 7 || got.Error == "" || !got.Truncated || len(got.Stdout) != mcpOutputLimit || len(got.Stderr) != mcpStderrLimit || got.Data != nil {
t.Fatalf("capture failed: exit=%d, error=%q, trunc=%v, stdout=%d, stderr=%d", got.ExitCode, got.Error, got.Truncated, len(got.Stdout), len(got.Stderr))
}
}
func TestMCPCommandFixture(t *testing.T) {
if os.Getenv("DEVBOX_MCP_COMMAND_FIXTURE") != "1" {
return
}
_, _ = os.Stdout.Write(bytes.Repeat([]byte("x"), mcpOutputLimit+4096))
_, _ = os.Stderr.Write(bytes.Repeat([]byte("y"), mcpStderrLimit+4096))
os.Exit(7)
}

135
docs/MCP.md Normal file
View file

@ -0,0 +1,135 @@
# Use devbox from an AI agent
`devbox mcp` runs a Model Context Protocol server over stdin/stdout, built into
the devbox client binary. It gives local agents structured access to the same
device, mounts, and hub that the CLI uses. No separate MCP package, Node runtime,
or additional network listener is required.
![MCP tool discovery and selected status fields from an isolated demo](images/mcp-tools.png)
## Connect your device first
Enroll with `devbox setup` or `devbox join`, and configure mounts through the
CLI. Start the sync daemon separately with `devbox start`. The MCP process
inherits the launching user's config directory; `XDG_CONFIG_HOME` can select a
different one. It does not ask for a join token through a tool.
For a Tailscale hub, connect the client machine's regular Tailscale app. Your
hub runs embedded Tailscale with `devbox-hub serve --tailscale`; MCP tools use the
private hub URL already stored by `devbox join`. MCP itself remains local stdio.
## Add it to an agent
Use the absolute path to the installed **file-sync devbox executable**. If you
also have a fleet administration command named `devbox`, do not point the agent
at that script.
### Codex
```bash
codex mcp add devbox -- /absolute/path/to/devbox mcp
```
For a separate devbox configuration:
```bash
codex mcp add devbox --env XDG_CONFIG_HOME=/absolute/path/to/config-base -- /absolute/path/to/devbox mcp
```
Equivalent TOML:
```toml
[mcp_servers.devbox]
command = "/absolute/path/to/devbox"
args = ["mcp"]
```
### Clients using `mcpServers` JSON
```json
{
"mcpServers": {
"devbox": {
"command": "/absolute/path/to/devbox",
"args": ["mcp"]
}
}
}
```
Use the MCP configuration location supported by your agent. On Windows, select
the absolute path to `devbox.exe`. Restart or reconnect the agent after adding
the server.
## Available tools
The default server exposes inspection tools only:
| Tool | Purpose |
|---|---|
| `devbox_status` | Joined state, hub, configured mounts, and live daemon state when available |
| `devbox_doctor` | Structured configuration, hub, filesystem, and watcher diagnostics |
| `devbox_conflicts` | List conflict copies without deleting them |
| `devbox_history` | Bounded snapshot history for a share |
| `devbox_members` | Membership information for a share |
To allow sync operations, set `args` to `["mcp", "--allow-writes"]`:
| Additional tool | Purpose |
|---|---|
| `devbox_pause` | Pause the running sync daemon |
| `devbox_resume` | Resume the running sync daemon |
| `devbox_publish` | Create a share from a local directory and push its files |
| `devbox_mount` | Mount a share or subdirectory, optionally read-only |
To also allow restore, deployment, and unmounting, use
`["mcp", "--allow-writes", "--allow-destructive"]`:
| Additional tool | Purpose |
|---|---|
| `devbox_restore` | Restore a snapshot or selected path |
| `devbox_deploy` | Apply a snapshot and pin the local mount |
| `devbox_unmount` | Remove a mount from configuration |
`devbox_mount` may merge local files, push changes, replace its mount config,
and clear a deployment pin. It is available with `--allow-writes` and advertises
`destructiveHint: true`; set `read_only: true` for a pull-only mount. Publish and
mount require an absolute `local_dir`; shell expansions such as `~` are not
performed. Snapshot IDs must be the full lowercase 64-character value from
history.
Unavailable tools are omitted from discovery. `--allow-destructive` requires
`--allow-writes`. Tool descriptions and schemas specify the exact parameters.
Use tool discovery rather than guessing arguments.
## Results and failures
Tools return structured results with the underlying command's output. A failed
operation is marked as an MCP tool error, including failed doctor checks; an
agent should inspect the diagnostic result before taking another action.
The command timeout defaults to `2m` and includes time waiting for another tool
call in this server. Set a positive `--command-timeout`, for example
`["mcp", "--command-timeout", "5m"]`, for large transfers. Captured stdout is
limited to 1 MiB and stderr to 64 KiB; `truncated` reports clipping. Results have
`stdout`, `stderr`, `exit_code`, `truncated`, optional parsed `data`, and optional
`error` fields. History accepts `limit` from 1 to 100 (default 20).
Calls are serialized within one MCP server. Coordinate mount/config changes
across multiple agents or CLI processes. Cancellation stops
the child command. An interrupted write may have completed some work already;
inspect status and history before retrying. Existing lifecycle hooks and
conflict-preservation behavior apply exactly as they do through the CLI.
MCP stdout contains protocol traffic only. Logs and startup errors go to stderr.
The server does not expose the stored bearer token, device private key, arbitrary
shell commands, or conflict-copy deletion as tools.
## Useful agent requests
- “Check whether this device is joined and whether its sync daemon is running.”
- “List conflicts and the latest snapshots for this share; don't change files.”
- “Diagnose why this mount isn't syncing and explain the failing checks.”
- With writes enabled: “Pause sync while I change dependencies, then resume it.”
See the [implementation plan](MCP-PLAN.md) for the scope and acceptance checks.

19
docs/images/README.md Normal file
View file

@ -0,0 +1,19 @@
# Documentation screenshots
These images show released CLI output and a running isolated demo. They do not
show production data, credentials, or production-tailnet enrollment.
- `tailscale-help.png`: screenshot of an HTML terminal-style presentation of the
actual `devbox-hub serve --help | grep -- --tailscale` output. The presentation
adds a title/caption; the flag descriptions are captured from the binary.
- `mcp-tools.png`: screenshot of a terminal-style presentation of actual MCP
tool discovery and a `devbox_status` result from the built-in stdio server.
The server uses an isolated enrolled demo config.
- `dashboard.png`: browser screenshot of the live dashboard from a local hub
with three demo device identities and shares (`web-app`, `api-service`, and
`shared-tools`). Changes are sent through actual sync daemons. The dashboard
is separate from the API and is not itself published by `--tailscale`.
The Tailscale client/server distinction remains the same in every capture:
the hub embeds tsnet, client machines use regular Tailscale, and MCP runs over
local stdin/stdout in the client binary.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 946 KiB

After

Width:  |  Height:  |  Size: 2.6 MiB

BIN
docs/images/mcp-tools.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

45
docs/mcp-evaluation.xml Normal file
View file

@ -0,0 +1,45 @@
<evaluation>
<!-- Read-only agent evaluation prompts. Launch the documented modes and use
tool discovery/schemas, the setup guide, and an isolated enrolled fixture.
These prompts are not a claim that an LLM benchmark has been run. -->
<qa_pair>
<question>Discover the tools in default mode, inspect their annotations, and compare them with the guide. How many tools are available?</question>
<answer>5</answer>
</qa_pair>
<qa_pair>
<question>Discover tools in default mode and with --allow-writes. How many additional tools does the write flag enable?</question>
<answer>4</answer>
</qa_pair>
<qa_pair>
<question>Compare discovery in all three documented access modes. How many tools are available when both write and destructive flags are enabled?</question>
<answer>12</answer>
</qa_pair>
<qa_pair>
<question>Inspect the tools available with --allow-writes and the schemas described in the guide. Can an agent restore a snapshot in this mode without the destructive flag?</question>
<answer>no</answer>
</qa_pair>
<qa_pair>
<question>Use status on a fresh unjoined configuration, then inspect the setup guide. What CLI command can enroll the device interactively before MCP uses its hub connection?</question>
<answer>devbox setup</answer>
</qa_pair>
<qa_pair>
<question>Discover tools and inspect the schema for conflict inspection. Which tool lists conflict copies without deleting them?</question>
<answer>devbox_conflicts</answer>
</qa_pair>
<qa_pair>
<question>Compare the restore and deployment tool descriptions without calling either. Which one applies a snapshot and pins the local mount?</question>
<answer>devbox_deploy</answer>
</qa_pair>
<qa_pair>
<question>Use status on an enrolled fixture and compare it with the tool-discovery list. Which history tool can inspect the snapshots for one of its mounted shares without changing files?</question>
<answer>devbox_history</answer>
</qa_pair>
<qa_pair>
<question>Inspect the agent launch configuration and the Tailscale setup guide. Does devbox mcp require a remote HTTP MCP listener or communicate through local stdio?</question>
<answer>local stdio</answer>
</qa_pair>
<qa_pair>
<question>Compare the Tailscale client setup and MCP launch configuration. Which command starts the embedded Tailscale hub rather than the local agent MCP server?</question>
<answer>devbox-hub serve --tailscale</answer>
</qa_pair>
</evaluation>

59
docs/releases/v2.2.0.md Normal file
View file

@ -0,0 +1,59 @@
# v2.2.0 — Built-in MCP + Tailscale
Your working tree on every machine. Structured sync tools for your coding agent.
## Tailscale is built into the hub
```bash
devbox-hub serve --data ./hub-data --tailscale --tailscale-hostname devbox-hub
```
The hub joins your tailnet itself, without a separate Tailscale installation,
root privileges, TUN device, router port forwarding, or reverse proxy. Enroll
using the first-run login URL or a securely supplied `TS_AUTHKEY`; preserve
`<data>/tailscale` across upgrades. Clients use the regular Tailscale app and
the private endpoint printed by the hub. Devbox join tokens remain required.
![Actual Tailscale CLI options](https://raw.githubusercontent.com/shoemoney/devbox/main/docs/images/tailscale-help.png)
## MCP is built into the client
```bash
codex mcp add devbox -- /absolute/path/to/devbox mcp
```
The new `devbox mcp` command serves tools over local stdio. Inspect status,
diagnostics, conflicts, history, and memberships by default. Enable pause,
resume, publish, and mount with `--allow-writes`. Restore, deploy, and unmount
also require `--allow-destructive`. The server uses the enrolled device's
existing config and connection, including access to Tailscale hubs.
![Actual MCP tool discovery and selected status fields](https://raw.githubusercontent.com/shoemoney/devbox/main/docs/images/mcp-tools.png)
See the [MCP guide](https://github.com/shoemoney/devbox/blob/main/docs/MCP.md)
for configuration examples and tool details. No separate MCP package or Node
runtime is needed. Start the sync daemon separately with `devbox start`.
## Install
```bash
curl -fsSL https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/latest/install.sh | sh
```
For the hub too, download the installer and run `sh install.sh --hub --no-service`.
Both binaries ship for Linux amd64/arm64/arm, macOS amd64/arm64, and Windows amd64.
`SHA256SUMS` covers the 12 binaries and both installers. Public downloads are
available on GitHub and Forgejo. Source builds require Go 1.27.4+.
## Validation
Passed vet, 189 race tests across 19 packages, and real SDK stdio tests for
initialization, discovery, calls, permissions, authenticated hub operations,
input validation, cancellation, timeouts, and output caps. The embedded Tailscale
regression uses real nodes against an isolated local control/DERP plane; no
production-tailnet enrollment is claimed.
![Live dashboard with isolated demo data](https://raw.githubusercontent.com/shoemoney/devbox/main/docs/images/dashboard.png)
The dashboard capture uses a local demo hub and real sync daemons. It is not a
production-tailnet capture.

5
go.mod
View file

@ -6,6 +6,7 @@ require (
github.com/BurntSushi/toml v1.6.0
github.com/fsnotify/fsnotify v1.10.1
github.com/jotfs/fastcdc-go v0.2.0
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/spf13/cobra v1.10.2
github.com/zeebo/blake3 v0.2.4
golang.org/x/time v0.16.0
@ -57,6 +58,7 @@ require (
github.com/google/btree v1.1.3 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/go-tpm v0.9.8 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/nftables v0.3.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hdevalence/ed25519consensus v0.2.0 // indirect
@ -82,6 +84,8 @@ require (
github.com/pkg/sftp v1.13.11 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/safchain/ethtool v0.7.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d // indirect
github.com/tailscale/gliderssh v0.3.4-0.20261026144310-31f7cf365d3a // indirect
@ -97,6 +101,7 @@ require (
github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 // indirect
github.com/vishvananda/netns v0.0.5 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb // indirect
golang.org/x/crypto v0.59.0 // indirect

12
go.sum
View file

@ -97,6 +97,8 @@ github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737 h1:cf60tHxREO
github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737/go.mod h1:MIS0jDzbU/vuM9MC4YnBITCv+RYuTRq8dJzmCrFsK9g=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
@ -107,6 +109,8 @@ github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/nftables v0.3.0 h1:bkyZ0cbpVeMHXOrtlFc8ISmfVqq5gPJukoYieyVmITg=
github.com/google/nftables v0.3.0/go.mod h1:BCp9FsrbF1Fn/Yu6CLUc9GGZFw/+hsxfluNXXmxBfRM=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
@ -162,6 +166,8 @@ github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
@ -185,6 +191,10 @@ github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52Z
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/safchain/ethtool v0.7.0 h1:rlJzfDetsVvT61uz8x1YIcFn12akMfuPulHtZjtb7Is=
github.com/safchain/ethtool v0.7.0/go.mod h1:MenQKEjXdfkjD3mp2QdCk8B/hwvkrlOTm/FD4gTpFxQ=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
@ -229,6 +239,8 @@ github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zd
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=

18
scripts/mcp-smoke.sh Executable file
View file

@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Run the real SDK stdio integration checks against a native packaged binary.
# Requires the repository's Go toolchain; never uses the caller's devbox config.
set -euo pipefail
if [[ $# -ne 1 ]]; then
echo "usage: $0 /absolute/path/to/devbox" >&2
exit 2
fi
case "$1" in
/*) ;;
*) echo "binary path must be absolute" >&2; exit 2 ;;
esac
if [[ ! -x "$1" ]]; then
echo "binary is not executable: $1" >&2
exit 2
fi
cd "$(dirname "$0")/.."
DEVBOX_MCP_TEST_BINARY="$1" go test ./cmd/devbox -run '^TestMCPStdio$' -count=1 -v