-
Notifications
You must be signed in to change notification settings - Fork 682
Define "MCP Sandbox Interface" and implement limactl mcp serve
#3744
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
AkihiroSuda
wants to merge
1
commit into
lima-vm:master
Choose a base branch
from
AkihiroSuda:mcp
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
// SPDX-FileCopyrightText: Copyright The Lima Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package main | ||
|
||
import ( | ||
"fmt" | ||
"runtime" | ||
"strings" | ||
|
||
"github.com/modelcontextprotocol/go-sdk/mcp" | ||
"github.com/spf13/cobra" | ||
|
||
"github.com/lima-vm/lima/v2/pkg/mcp/toolset" | ||
"github.com/lima-vm/lima/v2/pkg/store" | ||
"github.com/lima-vm/lima/v2/pkg/version" | ||
) | ||
|
||
func newMcpCommand() *cobra.Command { | ||
cmd := &cobra.Command{ | ||
Use: "mcp", | ||
Short: "Model Context Protocol", | ||
GroupID: advancedCommand, | ||
} | ||
cmd.AddCommand( | ||
newMcpServeCommand(), | ||
// TODO: `limactl mcp install-gemini` ? | ||
) | ||
return cmd | ||
} | ||
|
||
func newMcpServeCommand() *cobra.Command { | ||
cmd := &cobra.Command{ | ||
Use: "serve INSTANCE", | ||
Short: "Serve MCP over stdio", | ||
Long: `Serve MCP over stdio. | ||
|
||
Expected to be executed via an AI agent, not by a human`, | ||
Args: WrapArgsError(cobra.MaximumNArgs(1)), | ||
RunE: mcpServeAction, | ||
} | ||
return cmd | ||
} | ||
|
||
func mcpServeAction(cmd *cobra.Command, args []string) error { | ||
ctx := cmd.Context() | ||
instName := DefaultInstanceName | ||
if len(args) > 0 { | ||
instName = args[0] | ||
} | ||
inst, err := store.Inspect(instName) | ||
if err != nil { | ||
return err | ||
} | ||
ts, err := toolset.New(inst) | ||
if err != nil { | ||
return err | ||
} | ||
impl := &mcp.Implementation{ | ||
Name: "lima", | ||
Title: "Lima VM, for sandboxing local command executions and file I/O operations", | ||
Version: version.Version, | ||
} | ||
serverOpts := &mcp.ServerOptions{ | ||
Instructions: `This MCP server provides tools for sandboxing local command executions and file I/O operations, | ||
by wrapping them in Lima VM (https://lima-vm.io). | ||
|
||
Use these tools to avoid accidentally executing malicious codes directly on the host. | ||
`, | ||
} | ||
if runtime.GOOS != "linux" { | ||
serverOpts.Instructions += fmt.Sprintf(` | ||
|
||
NOTE: the guest OS of the VM is Linux, while the host OS is %s. | ||
`, strings.ToTitle(runtime.GOOS)) | ||
} | ||
server := mcp.NewServer(impl, serverOpts) | ||
if err = ts.RegisterServer(server); err != nil { | ||
return err | ||
} | ||
transport := mcp.NewStdioTransport() | ||
return server.Run(ctx, transport) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
// SPDX-FileCopyrightText: Copyright The Lima Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// Portion of AI prompt texts from: | ||
// - https://github.com/google-gemini/gemini-cli/blob/v0.1.12/docs/tools/file-system.md | ||
// | ||
// SPDX-FileCopyrightText: Copyright 2025 Google LLC | ||
|
||
package msi | ||
|
||
import ( | ||
"io/fs" | ||
"time" | ||
|
||
"github.com/modelcontextprotocol/go-sdk/mcp" | ||
) | ||
|
||
var ListDirectory = &mcp.Tool{ | ||
Name: "list_directory", | ||
Description: `Lists the names of files and subdirectories directly within a specified directory path.`, | ||
} | ||
|
||
type ListDirectoryParams struct { | ||
Path string `json:"path" jsonschema:"The absolute path to the directory to list."` | ||
} | ||
|
||
// ListDirectoryResultEntry is similar to [io/fs.FileInfo]. | ||
type ListDirectoryResultEntry struct { | ||
Name string `json:"name" jsonschema:"base name of the file"` | ||
Size *int64 `json:"size,omitempty" jsonschema:"length in bytes for regular files; system-dependent for others"` | ||
Mode *fs.FileMode `json:"mode,omitempty" jsonschema:"file mode bits"` | ||
ModTime *time.Time `json:"time,omitempty" jsonschema:"modification time"` | ||
IsDir *bool `json:"is_dir,omitempty" jsonschema:"true for a directory"` | ||
} | ||
|
||
type ListDirectoryResult struct { | ||
Entries []ListDirectoryResultEntry `json:"entries" jsonschema:"The directory content entries."` | ||
} | ||
|
||
var ReadFile = &mcp.Tool{ | ||
Name: "read_file", | ||
Description: `Reads and returns the content of a specified file.`, | ||
} | ||
|
||
type ReadFileParams struct { | ||
Path string `json:"path" jsonschema:"The absolute path to the file to read."` | ||
// Offset *int `json:"offset,omitempty" jsonschema:"For text files, the 0-based line number to start reading from. Requires limit to be set."` | ||
// 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."` | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
// SPDX-FileCopyrightText: Copyright The Lima Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// Package msi provides the "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 | ||
// | ||
// Notable differences from Gemini CLI's built-in tools: | ||
// - the output format is JSON, not a plain text | ||
// - [RunShellCommandParams].Command is a string slice, not a string | ||
// - [RunShellCommandParams].Directory is a absolute path, not a relative path | ||
// - [RunShellCommandParams].Directory must not be empty | ||
// | ||
// Eventually, this package may be split to a separate repository. | ||
package msi | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
// SPDX-FileCopyrightText: Copyright The Lima Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// Portion of AI prompt texts from: | ||
// - https://github.com/google-gemini/gemini-cli/blob/v0.1.12/docs/tools/shell.md | ||
// | ||
// SPDX-FileCopyrightText: Copyright 2025 Google LLC | ||
|
||
package msi | ||
|
||
import "github.com/modelcontextprotocol/go-sdk/mcp" | ||
|
||
var RunShellCommand = &mcp.Tool{ | ||
Name: "run_shell_command", | ||
Description: `Executes a given shell command.`, | ||
} | ||
|
||
type RunShellCommandParams struct { | ||
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."` | ||
Description string `json:"description,omitempty" jsonschema:"A brief description of the command's purpose, which will be potentially shown to the user."` | ||
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."` | ||
} | ||
|
||
type RunShellCommandResult struct { | ||
Stdout string `json:"stdout" jsonschema:"Output from the standard output stream."` | ||
Stderr string `json:"stderr" jsonschema:"Output from the standard error stream."` | ||
Error string `json:"error,omitempty" jsonschema:"Any error message reported by the subprocess."` | ||
ExitCode *int `json:"exit_code,omitempty" jsonschema:"Exit code of the command."` | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
// SPDX-FileCopyrightText: Copyright The Lima Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package toolset | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"io" | ||
|
||
"github.com/modelcontextprotocol/go-sdk/mcp" | ||
|
||
"github.com/lima-vm/lima/v2/pkg/mcp/msi" | ||
"github.com/lima-vm/lima/v2/pkg/ptr" | ||
) | ||
|
||
func (ts *ToolSet) ListDirectory(ctx context.Context, _ *mcp.ServerSession, | ||
params *mcp.CallToolParamsFor[msi.ListDirectoryParams], | ||
) (*mcp.CallToolResultFor[msi.ListDirectoryResult], error) { | ||
args := params.Arguments | ||
guestPath, err := ts.TranslateHostPath(args.Path) | ||
if err != nil { | ||
return nil, err | ||
} | ||
guestEnts, err := ts.sftp.ReadDirContext(ctx, guestPath) | ||
if err != nil { | ||
return nil, err | ||
} | ||
res := msi.ListDirectoryResult{ | ||
Entries: make([]msi.ListDirectoryResultEntry, len(guestEnts)), | ||
} | ||
for i, f := range guestEnts { | ||
res.Entries[i].Name = f.Name() | ||
res.Entries[i].Size = ptr.Of(f.Size()) | ||
res.Entries[i].Mode = ptr.Of(f.Mode()) | ||
res.Entries[i].ModTime = ptr.Of(f.ModTime()) | ||
res.Entries[i].IsDir = ptr.Of(f.IsDir()) | ||
} | ||
resJ, err := json.Marshal(res) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &mcp.CallToolResultFor[msi.ListDirectoryResult]{ | ||
Content: []mcp.Content{&mcp.TextContent{Text: string(resJ)}}, | ||
}, nil | ||
} | ||
|
||
func (ts *ToolSet) ReadFile(_ context.Context, _ *mcp.ServerSession, | ||
params *mcp.CallToolParamsFor[msi.ReadFileParams], | ||
) (*mcp.CallToolResultFor[any], error) { | ||
args := params.Arguments | ||
guestPath, err := ts.TranslateHostPath(args.Path) | ||
if err != nil { | ||
return nil, err | ||
} | ||
f, err := ts.sftp.Open(guestPath) | ||
if err != nil { | ||
return nil, err | ||
} | ||
defer f.Close() | ||
const limitBytes = 32 * 1024 * 1024 | ||
lr := io.LimitReader(f, limitBytes) | ||
b, err := io.ReadAll(lr) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &mcp.CallToolResultFor[any]{ | ||
Content: []mcp.Content{&mcp.TextContent{Text: string(b)}}, | ||
}, nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
// SPDX-FileCopyrightText: Copyright The Lima Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package toolset | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"encoding/json" | ||
"os/exec" | ||
|
||
"github.com/modelcontextprotocol/go-sdk/mcp" | ||
|
||
"github.com/lima-vm/lima/v2/pkg/mcp/msi" | ||
"github.com/lima-vm/lima/v2/pkg/ptr" | ||
) | ||
|
||
func (ts *ToolSet) RunShellCommand(ctx context.Context, _ *mcp.ServerSession, | ||
params *mcp.CallToolParamsFor[msi.RunShellCommandParams], | ||
) (*mcp.CallToolResultFor[msi.RunShellCommandResult], error) { | ||
args := params.Arguments | ||
guestPath, err := ts.TranslateHostPath(args.Directory) | ||
if err != nil { | ||
return nil, err | ||
} | ||
cmd := exec.CommandContext(ctx, ts.limactl, | ||
append([]string{"shell", "--workdir=" + guestPath, ts.inst.Name}, | ||
args.Command...)...) | ||
var stdout, stderr bytes.Buffer | ||
cmd.Stdout = &stdout | ||
cmd.Stderr = &stderr | ||
cmdErr := cmd.Run() | ||
res := msi.RunShellCommandResult{ | ||
Stdout: stdout.String(), | ||
Stderr: stderr.String(), | ||
} | ||
if cmdErr == nil { | ||
res.ExitCode = ptr.Of(0) | ||
} else { | ||
res.Error = cmdErr.Error() | ||
if st := cmd.ProcessState; st != nil { | ||
res.ExitCode = ptr.Of(st.ExitCode()) | ||
} | ||
} | ||
resJ, err := json.Marshal(res) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &mcp.CallToolResultFor[msi.RunShellCommandResult]{ | ||
Content: []mcp.Content{&mcp.TextContent{Text: string(resJ)}}, | ||
}, nil | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
RFC: "MCP Sandbox Interface" might be a misnomer; it might rather sound like an interface for sandboxing MCP servers, e.g.,
docker run -i --rm example.com/some-mcp-server /usr/bin/some-mcp-server
https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md#docker-based-mcp-server
Alternative names:
Thoughts?