devbox/cmd/devbox/mcp.go

337 lines
14 KiB
Go

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