Skip to content

Commit 904302b

Browse files
committed
Define "MCP Sandbox Interface" and implement limactl mcp serve
=== Interface === `pkg/mcp/msi` defines "MCP Sandbox Interface" (tentative) that should be reusable for other projects too. MCP Sandbox Interface defines MCP (Model Context Protocol) tools that can be used for reading, writing, and executing local files with an appropriate sandboxing technology. The sandboxing technology can be more secure and/or efficient than the default tools provided by an AI agent. MCP Sandbox Interface was inspired by Gemini CLI's built-in tools. https://github.com/google-gemini/gemini-cli/tree/v0.1.12/docs/tools === Implementation === `limactl mcp serve INSTANCE` launches an MCP server that implements the MCP Sandbox Interface. Use <https://github.com/modelcontextprotocol/inspector> to play around with the server. ```bash limactl start default brew install mcp-inspector mcp-inspector ``` In the web browser, - Set `Command` to `limactl` - Set `Arguments` to `mcp serve default` - Click `▶️Connect` === Usage with Gemni CLI === 1. Create `.gemini/extensions/lima/gemini-extension.json` as follows: ```json { "name": "lima", "version": "2.0.0", "mcpServers": { "lima": { "command": "limactl", "args": [ "mcp", "serve", "default" ] } } } ``` 2. Modify `.gemini/settings.json` so as to disable Gemini CLI's built-in tools except ones that do not relate to local command execution and file I/O: ```json { "coreTools": ["WebFetchTool", "WebSearchTool", "MemoryTool"] } ``` Signed-off-by: Akihiro Suda <[email protected]>
1 parent d4056f9 commit 904302b

File tree

14 files changed

+496
-1
lines changed

14 files changed

+496
-1
lines changed

cmd/limactl/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ func newApp() *cobra.Command {
194194
newStartAtLoginCommand(),
195195
newNetworkCommand(),
196196
newCloneCommand(),
197+
newMcpCommand(),
197198
)
198199

199200
return rootCmd

cmd/limactl/mcp.go

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// SPDX-FileCopyrightText: Copyright The Lima Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package main
5+
6+
import (
7+
"fmt"
8+
"runtime"
9+
"strings"
10+
11+
"github.com/modelcontextprotocol/go-sdk/mcp"
12+
"github.com/spf13/cobra"
13+
14+
"github.com/lima-vm/lima/v2/pkg/mcp/toolset"
15+
"github.com/lima-vm/lima/v2/pkg/store"
16+
"github.com/lima-vm/lima/v2/pkg/version"
17+
)
18+
19+
func newMcpCommand() *cobra.Command {
20+
cmd := &cobra.Command{
21+
Use: "mcp",
22+
Short: "Model Context Protocol",
23+
GroupID: advancedCommand,
24+
}
25+
cmd.AddCommand(
26+
newMcpServeCommand(),
27+
// TODO: `limactl mcp install-gemini` ?
28+
)
29+
return cmd
30+
}
31+
32+
func newMcpServeCommand() *cobra.Command {
33+
cmd := &cobra.Command{
34+
Use: "serve INSTANCE",
35+
Short: "Serve MCP over stdio",
36+
Long: `Serve MCP over stdio.
37+
38+
Expected to be executed via an AI agent, not by a human`,
39+
Args: WrapArgsError(cobra.MaximumNArgs(1)),
40+
RunE: mcpServeAction,
41+
}
42+
return cmd
43+
}
44+
45+
func mcpServeAction(cmd *cobra.Command, args []string) error {
46+
ctx := cmd.Context()
47+
instName := DefaultInstanceName
48+
if len(args) > 0 {
49+
instName = args[0]
50+
}
51+
inst, err := store.Inspect(instName)
52+
if err != nil {
53+
return err
54+
}
55+
ts, err := toolset.New(inst)
56+
if err != nil {
57+
return err
58+
}
59+
impl := &mcp.Implementation{
60+
Name: "lima",
61+
Title: "Lima VM, for sandboxing local command executions and file I/O operations",
62+
Version: version.Version,
63+
}
64+
serverOpts := &mcp.ServerOptions{
65+
Instructions: `This MCP server provides tools for sandboxing local command executions and file I/O operations,
66+
by wrapping them in Lima VM (https://lima-vm.io).
67+
68+
Use these tools to avoid accidentally executing malicious codes directly on the host.
69+
`,
70+
}
71+
if runtime.GOOS != "linux" {
72+
serverOpts.Instructions += fmt.Sprintf(`
73+
74+
NOTE: the guest OS of the VM is Linux, while the host OS is %s.
75+
`, strings.ToTitle(runtime.GOOS))
76+
}
77+
server := mcp.NewServer(impl, serverOpts)
78+
if err = ts.RegisterServer(server); err != nil {
79+
return err
80+
}
81+
transport := mcp.NewStdioTransport()
82+
return server.Run(ctx, transport)
83+
}

go.mod

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,11 @@ require (
3131
github.com/mdlayher/vsock v1.2.1 // gomodjail:unconfined
3232
github.com/miekg/dns v1.1.67 // gomodjail:unconfined
3333
github.com/mikefarah/yq/v4 v4.45.1
34+
github.com/modelcontextprotocol/go-sdk v0.2.0
3435
github.com/nxadm/tail v1.4.11 // gomodjail:unconfined
3536
github.com/opencontainers/go-digest v1.0.0
3637
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58
38+
github.com/pkg/sftp v1.13.9
3739
github.com/rjeczalik/notify v0.9.3
3840
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
3941
github.com/sethvargo/go-password v0.3.1
@@ -107,13 +109,13 @@ require (
107109
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
108110
github.com/pierrec/lz4/v4 v4.1.22 // indirect
109111
github.com/pkg/errors v0.9.1 // indirect
110-
github.com/pkg/sftp v1.13.9 // indirect
111112
github.com/rivo/uniseg v0.4.7 // indirect
112113
github.com/russross/blackfriday/v2 v2.1.0 // indirect
113114
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 // indirect
114115
// gomodjail:unconfined
115116
github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 // indirect
116117
github.com/x448/float16 v0.8.4 // indirect
118+
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
117119
github.com/yuin/gopher-lua v1.1.1 // indirect
118120
golang.org/x/crypto v0.40.0 // indirect
119121
golang.org/x/mod v0.25.0 // indirect

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,8 @@ github.com/mikefarah/yq/v4 v4.45.1 h1:EW+HjKEVa55pUYFJseEHEHdQ0+ulunY+q42zF3M7Za
190190
github.com/mikefarah/yq/v4 v4.45.1/go.mod h1:djgN2vD749hpjVNGYTShr5Kmv5LYljhCG3lUTuEe3LM=
191191
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
192192
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
193+
github.com/modelcontextprotocol/go-sdk v0.2.0 h1:PESNYOmyM1c369tRkzXLY5hHrazj8x9CY1Xu0fLCryM=
194+
github.com/modelcontextprotocol/go-sdk v0.2.0/go.mod h1:0sL9zUKKs2FTTkeCCVnKqbLJTw5TScefPAzojjU459E=
193195
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
194196
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
195197
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -263,6 +265,8 @@ github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/
263265
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
264266
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
265267
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
268+
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
269+
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
266270
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
267271
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
268272
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=

pkg/mcp/msi/file-system.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// SPDX-FileCopyrightText: Copyright The Lima Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
// Portion of AI prompt texts from:
5+
// - https://github.com/google-gemini/gemini-cli/blob/v0.1.12/docs/tools/file-system.md
6+
//
7+
// SPDX-FileCopyrightText: Copyright 2025 Google LLC
8+
9+
package msi
10+
11+
import (
12+
"io/fs"
13+
"time"
14+
15+
"github.com/modelcontextprotocol/go-sdk/mcp"
16+
)
17+
18+
var ListDirectory = &mcp.Tool{
19+
Name: "list_directory",
20+
Description: `Lists the names of files and subdirectories directly within a specified directory path.`,
21+
}
22+
23+
type ListDirectoryParams struct {
24+
Path string `json:"path" jsonschema:"The absolute path to the directory to list."`
25+
}
26+
27+
// ListDirectoryResultEntry is similar to [io/fs.FileInfo].
28+
type ListDirectoryResultEntry struct {
29+
Name string `json:"name" jsonschema:"base name of the file"`
30+
Size *int64 `json:"size,omitempty" jsonschema:"length in bytes for regular files; system-dependent for others"`
31+
Mode *fs.FileMode `json:"mode,omitempty" jsonschema:"file mode bits"`
32+
ModTime *time.Time `json:"time,omitempty" jsonschema:"modification time"`
33+
IsDir *bool `json:"is_dir,omitempty" jsonschema:"true for a directory"`
34+
}
35+
36+
type ListDirectoryResult struct {
37+
Entries []ListDirectoryResultEntry `json:"entries" jsonschema:"The directory content entries."`
38+
}
39+
40+
var ReadFile = &mcp.Tool{
41+
Name: "read_file",
42+
Description: `Reads and returns the content of a specified file.`,
43+
}
44+
45+
type ReadFileParams struct {
46+
Path string `json:"path" jsonschema:"The absolute path to the file to read."`
47+
// Offset *int `json:"offset,omitempty" jsonschema:"For text files, the 0-based line number to start reading from. Requires limit to be set."`
48+
// Limit *int `json:"limit,omitempty" jsonschema:"For text files, the maximum number of lines to read. If omitted, reads a default maximum (e.g., 2000 lines) or the entire file if feasible."`
49+
}

pkg/mcp/msi/msi.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// SPDX-FileCopyrightText: Copyright The Lima Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
// Package msi provides the "MCP Sandbox Interface" (tentative)
5+
// that should be reusable for other projects too.
6+
//
7+
// MCP Sandbox Interface defines MCP (Model Context Protocol) tools
8+
// that can be used for reading, writing, and executing local files
9+
// with an appropriate sandboxing technology. The sandboxing technology
10+
// can be more secure and/or efficient than the default tools provided
11+
// by an AI agent.
12+
//
13+
// MCP Sandbox Interface was inspired by Gemini CLI's built-in tools.
14+
// https://github.com/google-gemini/gemini-cli/tree/v0.1.12/docs/tools
15+
//
16+
// Notable differences from Gemini CLI's built-in tools:
17+
// - the output format is JSON, not a plain text
18+
// - [RunShellCommandParams].Command is a string slice, not a string
19+
// - [RunShellCommandParams].Directory is a absolute path, not a relative path
20+
// - [RunShellCommandParams].Directory must not be empty
21+
//
22+
// Eventually, this package may be split to a separate repository.
23+
package msi

pkg/mcp/msi/shell.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// SPDX-FileCopyrightText: Copyright The Lima Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
// Portion of AI prompt texts from:
5+
// - https://github.com/google-gemini/gemini-cli/blob/v0.1.12/docs/tools/shell.md
6+
//
7+
// SPDX-FileCopyrightText: Copyright 2025 Google LLC
8+
9+
package msi
10+
11+
import "github.com/modelcontextprotocol/go-sdk/mcp"
12+
13+
var RunShellCommand = &mcp.Tool{
14+
Name: "run_shell_command",
15+
Description: `Executes a given shell command.`,
16+
}
17+
18+
type RunShellCommandParams struct {
19+
Command []string `json:"command" jsonschema:"The exact shell command to execute. Defined as a string slice, unlike Gemini's run_shell_command that defines it as a single string."`
20+
Description string `json:"description,omitempty" jsonschema:"A brief description of the command's purpose, which will be potentially shown to the user."`
21+
Directory string `json:"directory" jsonschema:"The absolute directory in which to execute the command. Unlike Gemini's run_shell_command, this must not be a relative path, and must not be empty."`
22+
}
23+
24+
type RunShellCommandResult struct {
25+
Stdout string `json:"stdout" jsonschema:"Output from the standard output stream."`
26+
Stderr string `json:"stderr" jsonschema:"Output from the standard error stream."`
27+
Error string `json:"error,omitempty" jsonschema:"Any error message reported by the subprocess."`
28+
ExitCode *int `json:"exit_code,omitempty" jsonschema:"Exit code of the command."`
29+
}

pkg/mcp/toolset/file-system.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// SPDX-FileCopyrightText: Copyright The Lima Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package toolset
5+
6+
import (
7+
"context"
8+
"encoding/json"
9+
"io"
10+
11+
"github.com/modelcontextprotocol/go-sdk/mcp"
12+
13+
"github.com/lima-vm/lima/v2/pkg/mcp/msi"
14+
"github.com/lima-vm/lima/v2/pkg/ptr"
15+
)
16+
17+
func (ts *ToolSet) ListDirectory(ctx context.Context, cc *mcp.ServerSession,
18+
params *mcp.CallToolParamsFor[msi.ListDirectoryParams]) (*mcp.CallToolResultFor[msi.ListDirectoryResult], error) {
19+
args := params.Arguments
20+
guestPath, err := ts.TranslateHostPath(args.Path)
21+
if err != nil {
22+
return nil, err
23+
}
24+
guestEnts, err := ts.sftp.ReadDirContext(ctx, guestPath)
25+
if err != nil {
26+
return nil, err
27+
}
28+
res := msi.ListDirectoryResult{
29+
Entries: make([]msi.ListDirectoryResultEntry, len(guestEnts)),
30+
}
31+
for i, f := range guestEnts {
32+
res.Entries[i].Name = f.Name()
33+
res.Entries[i].Size = ptr.Of(f.Size())
34+
res.Entries[i].Mode = ptr.Of(f.Mode())
35+
res.Entries[i].ModTime = ptr.Of(f.ModTime())
36+
res.Entries[i].IsDir = ptr.Of(f.IsDir())
37+
}
38+
resJ, err := json.Marshal(res)
39+
if err != nil {
40+
return nil, err
41+
}
42+
return &mcp.CallToolResultFor[msi.ListDirectoryResult]{
43+
Content: []mcp.Content{&mcp.TextContent{Text: string(resJ)}},
44+
}, nil
45+
}
46+
47+
func (ts *ToolSet) ReadFile(ctx context.Context, cc *mcp.ServerSession,
48+
params *mcp.CallToolParamsFor[msi.ReadFileParams]) (*mcp.CallToolResultFor[any], error) {
49+
args := params.Arguments
50+
guestPath, err := ts.TranslateHostPath(args.Path)
51+
if err != nil {
52+
return nil, err
53+
}
54+
f, err := ts.sftp.Open(guestPath)
55+
if err != nil {
56+
return nil, err
57+
}
58+
defer f.Close()
59+
const limitBytes = 32 * 1024 * 1024
60+
lr := io.LimitReader(f, limitBytes)
61+
b, err := io.ReadAll(lr)
62+
if err != nil {
63+
return nil, err
64+
}
65+
return &mcp.CallToolResultFor[any]{
66+
Content: []mcp.Content{&mcp.TextContent{Text: string(b)}},
67+
}, nil
68+
}

pkg/mcp/toolset/shell.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// SPDX-FileCopyrightText: Copyright The Lima Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package toolset
5+
6+
import (
7+
"bytes"
8+
"context"
9+
"encoding/json"
10+
"os/exec"
11+
12+
"github.com/modelcontextprotocol/go-sdk/mcp"
13+
14+
"github.com/lima-vm/lima/v2/pkg/mcp/msi"
15+
"github.com/lima-vm/lima/v2/pkg/ptr"
16+
)
17+
18+
func (ts *ToolSet) RunShellCommand(ctx context.Context, cc *mcp.ServerSession,
19+
params *mcp.CallToolParamsFor[msi.RunShellCommandParams]) (*mcp.CallToolResultFor[msi.RunShellCommandResult], error) {
20+
args := params.Arguments
21+
guestPath, err := ts.TranslateHostPath(args.Directory)
22+
if err != nil {
23+
return nil, err
24+
}
25+
cmd := exec.Command(ts.limactl,
26+
append([]string{"shell", "--workdir=" + guestPath, ts.inst.Name},
27+
args.Command...)...)
28+
var stdout, stderr bytes.Buffer
29+
cmd.Stdout = &stdout
30+
cmd.Stderr = &stderr
31+
cmdErr := cmd.Run()
32+
res := msi.RunShellCommandResult{
33+
Stdout: stdout.String(),
34+
Stderr: stderr.String(),
35+
}
36+
if cmdErr == nil {
37+
res.ExitCode = ptr.Of(0)
38+
} else {
39+
res.Error = cmdErr.Error()
40+
if st := cmd.ProcessState; st != nil {
41+
res.ExitCode = ptr.Of(st.ExitCode())
42+
}
43+
}
44+
resJ, err := json.Marshal(res)
45+
if err != nil {
46+
return nil, err
47+
}
48+
return &mcp.CallToolResultFor[msi.RunShellCommandResult]{
49+
Content: []mcp.Content{&mcp.TextContent{Text: string(resJ)}},
50+
}, nil
51+
}

0 commit comments

Comments
 (0)