cli/pkg/mcp/mcp.go
Snider d2c0553b6d refactor: flatten CLI to root, simplify pkg/mcp for CLI-only use
- Move cmd/core/cmd/* to cmd/* (flatten directory structure)
- Update module path from github.com/host-uk/core/cmd/core to github.com/host-uk/core
- Remove go.mod files from pkg/* (single module now)
- Simplify pkg/mcp to file operations only (no GUI deps)
- GUI features (display, webview, process) stay in core-gui/pkg/mcp
- Fix import aliases (sdkpkg) for package name conflicts
- Remove old backup directory (cmdbk)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 18:13:51 +00:00

409 lines
12 KiB
Go

// Package mcp provides a lightweight MCP (Model Context Protocol) server for CLI use.
// For full GUI integration (display, webview, process management), see core-gui/pkg/mcp.
package mcp
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// Service provides a lightweight MCP server with file operations only.
// For full GUI features, use the core-gui package.
type Service struct {
server *mcp.Server
}
// New creates a new MCP service with file operations.
func New() *Service {
impl := &mcp.Implementation{
Name: "core-cli",
Version: "0.1.0",
}
server := mcp.NewServer(impl, nil)
s := &Service{server: server}
s.registerTools()
return s
}
// registerTools adds file operation tools to the MCP server.
func (s *Service) registerTools() {
// File operations
mcp.AddTool(s.server, &mcp.Tool{
Name: "file_read",
Description: "Read the contents of a file",
}, s.readFile)
mcp.AddTool(s.server, &mcp.Tool{
Name: "file_write",
Description: "Write content to a file",
}, s.writeFile)
mcp.AddTool(s.server, &mcp.Tool{
Name: "file_delete",
Description: "Delete a file or empty directory",
}, s.deleteFile)
mcp.AddTool(s.server, &mcp.Tool{
Name: "file_rename",
Description: "Rename or move a file",
}, s.renameFile)
mcp.AddTool(s.server, &mcp.Tool{
Name: "file_exists",
Description: "Check if a file or directory exists",
}, s.fileExists)
mcp.AddTool(s.server, &mcp.Tool{
Name: "file_edit",
Description: "Edit a file by replacing old_string with new_string. Use replace_all=true to replace all occurrences.",
}, s.editDiff)
// Directory operations
mcp.AddTool(s.server, &mcp.Tool{
Name: "dir_list",
Description: "List contents of a directory",
}, s.listDirectory)
mcp.AddTool(s.server, &mcp.Tool{
Name: "dir_create",
Description: "Create a new directory",
}, s.createDirectory)
// Language detection
mcp.AddTool(s.server, &mcp.Tool{
Name: "lang_detect",
Description: "Detect the programming language of a file",
}, s.detectLanguage)
mcp.AddTool(s.server, &mcp.Tool{
Name: "lang_list",
Description: "Get list of supported programming languages",
}, s.getSupportedLanguages)
}
// Tool input/output types
type ReadFileInput struct {
Path string `json:"path"`
}
type ReadFileOutput struct {
Content string `json:"content"`
Language string `json:"language"`
Path string `json:"path"`
}
type WriteFileInput struct {
Path string `json:"path"`
Content string `json:"content"`
}
type WriteFileOutput struct {
Success bool `json:"success"`
Path string `json:"path"`
}
type ListDirectoryInput struct {
Path string `json:"path"`
}
type ListDirectoryOutput struct {
Entries []DirectoryEntry `json:"entries"`
Path string `json:"path"`
}
type DirectoryEntry struct {
Name string `json:"name"`
Path string `json:"path"`
IsDir bool `json:"isDir"`
Size int64 `json:"size"`
}
type CreateDirectoryInput struct {
Path string `json:"path"`
}
type CreateDirectoryOutput struct {
Success bool `json:"success"`
Path string `json:"path"`
}
type DeleteFileInput struct {
Path string `json:"path"`
}
type DeleteFileOutput struct {
Success bool `json:"success"`
Path string `json:"path"`
}
type RenameFileInput struct {
OldPath string `json:"oldPath"`
NewPath string `json:"newPath"`
}
type RenameFileOutput struct {
Success bool `json:"success"`
OldPath string `json:"oldPath"`
NewPath string `json:"newPath"`
}
type FileExistsInput struct {
Path string `json:"path"`
}
type FileExistsOutput struct {
Exists bool `json:"exists"`
IsDir bool `json:"isDir"`
Path string `json:"path"`
}
type DetectLanguageInput struct {
Path string `json:"path"`
}
type DetectLanguageOutput struct {
Language string `json:"language"`
Path string `json:"path"`
}
type GetSupportedLanguagesInput struct{}
type GetSupportedLanguagesOutput struct {
Languages []LanguageInfo `json:"languages"`
}
type LanguageInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Extensions []string `json:"extensions"`
}
type EditDiffInput struct {
Path string `json:"path"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
ReplaceAll bool `json:"replace_all,omitempty"`
}
type EditDiffOutput struct {
Path string `json:"path"`
Success bool `json:"success"`
Replacements int `json:"replacements"`
}
// Tool handlers
func (s *Service) readFile(ctx context.Context, req *mcp.CallToolRequest, input ReadFileInput) (*mcp.CallToolResult, ReadFileOutput, error) {
content, err := os.ReadFile(input.Path)
if err != nil {
return nil, ReadFileOutput{}, fmt.Errorf("failed to read file: %w", err)
}
return nil, ReadFileOutput{
Content: string(content),
Language: detectLanguageFromPath(input.Path),
Path: input.Path,
}, nil
}
func (s *Service) writeFile(ctx context.Context, req *mcp.CallToolRequest, input WriteFileInput) (*mcp.CallToolResult, WriteFileOutput, error) {
dir := filepath.Dir(input.Path)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, WriteFileOutput{}, fmt.Errorf("failed to create directory: %w", err)
}
err := os.WriteFile(input.Path, []byte(input.Content), 0644)
if err != nil {
return nil, WriteFileOutput{}, fmt.Errorf("failed to write file: %w", err)
}
return nil, WriteFileOutput{Success: true, Path: input.Path}, nil
}
func (s *Service) listDirectory(ctx context.Context, req *mcp.CallToolRequest, input ListDirectoryInput) (*mcp.CallToolResult, ListDirectoryOutput, error) {
entries, err := os.ReadDir(input.Path)
if err != nil {
return nil, ListDirectoryOutput{}, fmt.Errorf("failed to list directory: %w", err)
}
result := make([]DirectoryEntry, 0, len(entries))
for _, e := range entries {
info, _ := e.Info()
var size int64
if info != nil {
size = info.Size()
}
result = append(result, DirectoryEntry{
Name: e.Name(),
Path: filepath.Join(input.Path, e.Name()),
IsDir: e.IsDir(),
Size: size,
})
}
return nil, ListDirectoryOutput{Entries: result, Path: input.Path}, nil
}
func (s *Service) createDirectory(ctx context.Context, req *mcp.CallToolRequest, input CreateDirectoryInput) (*mcp.CallToolResult, CreateDirectoryOutput, error) {
err := os.MkdirAll(input.Path, 0755)
if err != nil {
return nil, CreateDirectoryOutput{}, fmt.Errorf("failed to create directory: %w", err)
}
return nil, CreateDirectoryOutput{Success: true, Path: input.Path}, nil
}
func (s *Service) deleteFile(ctx context.Context, req *mcp.CallToolRequest, input DeleteFileInput) (*mcp.CallToolResult, DeleteFileOutput, error) {
err := os.Remove(input.Path)
if err != nil {
return nil, DeleteFileOutput{}, fmt.Errorf("failed to delete file: %w", err)
}
return nil, DeleteFileOutput{Success: true, Path: input.Path}, nil
}
func (s *Service) renameFile(ctx context.Context, req *mcp.CallToolRequest, input RenameFileInput) (*mcp.CallToolResult, RenameFileOutput, error) {
err := os.Rename(input.OldPath, input.NewPath)
if err != nil {
return nil, RenameFileOutput{}, fmt.Errorf("failed to rename file: %w", err)
}
return nil, RenameFileOutput{Success: true, OldPath: input.OldPath, NewPath: input.NewPath}, nil
}
func (s *Service) fileExists(ctx context.Context, req *mcp.CallToolRequest, input FileExistsInput) (*mcp.CallToolResult, FileExistsOutput, error) {
info, err := os.Stat(input.Path)
if os.IsNotExist(err) {
return nil, FileExistsOutput{Exists: false, IsDir: false, Path: input.Path}, nil
}
if err != nil {
return nil, FileExistsOutput{}, fmt.Errorf("failed to check file: %w", err)
}
return nil, FileExistsOutput{Exists: true, IsDir: info.IsDir(), Path: input.Path}, nil
}
func (s *Service) detectLanguage(ctx context.Context, req *mcp.CallToolRequest, input DetectLanguageInput) (*mcp.CallToolResult, DetectLanguageOutput, error) {
lang := detectLanguageFromPath(input.Path)
return nil, DetectLanguageOutput{Language: lang, Path: input.Path}, nil
}
func (s *Service) getSupportedLanguages(ctx context.Context, req *mcp.CallToolRequest, input GetSupportedLanguagesInput) (*mcp.CallToolResult, GetSupportedLanguagesOutput, error) {
languages := []LanguageInfo{
{ID: "typescript", Name: "TypeScript", Extensions: []string{".ts", ".tsx"}},
{ID: "javascript", Name: "JavaScript", Extensions: []string{".js", ".jsx"}},
{ID: "go", Name: "Go", Extensions: []string{".go"}},
{ID: "python", Name: "Python", Extensions: []string{".py"}},
{ID: "rust", Name: "Rust", Extensions: []string{".rs"}},
{ID: "java", Name: "Java", Extensions: []string{".java"}},
{ID: "php", Name: "PHP", Extensions: []string{".php"}},
{ID: "ruby", Name: "Ruby", Extensions: []string{".rb"}},
{ID: "html", Name: "HTML", Extensions: []string{".html", ".htm"}},
{ID: "css", Name: "CSS", Extensions: []string{".css"}},
{ID: "json", Name: "JSON", Extensions: []string{".json"}},
{ID: "yaml", Name: "YAML", Extensions: []string{".yaml", ".yml"}},
{ID: "markdown", Name: "Markdown", Extensions: []string{".md", ".markdown"}},
{ID: "sql", Name: "SQL", Extensions: []string{".sql"}},
{ID: "shell", Name: "Shell", Extensions: []string{".sh", ".bash"}},
}
return nil, GetSupportedLanguagesOutput{Languages: languages}, nil
}
func (s *Service) editDiff(ctx context.Context, req *mcp.CallToolRequest, input EditDiffInput) (*mcp.CallToolResult, EditDiffOutput, error) {
content, err := os.ReadFile(input.Path)
if err != nil {
return nil, EditDiffOutput{}, fmt.Errorf("failed to read file: %w", err)
}
fileContent := string(content)
count := 0
if input.ReplaceAll {
count = strings.Count(fileContent, input.OldString)
if count == 0 {
return nil, EditDiffOutput{}, fmt.Errorf("old_string not found in file")
}
fileContent = strings.ReplaceAll(fileContent, input.OldString, input.NewString)
} else {
if !strings.Contains(fileContent, input.OldString) {
return nil, EditDiffOutput{}, fmt.Errorf("old_string not found in file")
}
fileContent = strings.Replace(fileContent, input.OldString, input.NewString, 1)
count = 1
}
err = os.WriteFile(input.Path, []byte(fileContent), 0644)
if err != nil {
return nil, EditDiffOutput{}, fmt.Errorf("failed to write file: %w", err)
}
return nil, EditDiffOutput{
Path: input.Path,
Success: true,
Replacements: count,
}, nil
}
// detectLanguageFromPath maps file extensions to language IDs.
func detectLanguageFromPath(path string) string {
ext := filepath.Ext(path)
switch ext {
case ".ts", ".tsx":
return "typescript"
case ".js", ".jsx":
return "javascript"
case ".go":
return "go"
case ".py":
return "python"
case ".rs":
return "rust"
case ".rb":
return "ruby"
case ".java":
return "java"
case ".php":
return "php"
case ".c", ".h":
return "c"
case ".cpp", ".hpp", ".cc", ".cxx":
return "cpp"
case ".cs":
return "csharp"
case ".html", ".htm":
return "html"
case ".css":
return "css"
case ".scss":
return "scss"
case ".json":
return "json"
case ".yaml", ".yml":
return "yaml"
case ".xml":
return "xml"
case ".md", ".markdown":
return "markdown"
case ".sql":
return "sql"
case ".sh", ".bash":
return "shell"
case ".swift":
return "swift"
case ".kt", ".kts":
return "kotlin"
default:
if filepath.Base(path) == "Dockerfile" {
return "dockerfile"
}
return "plaintext"
}
}
// Run starts the MCP server on stdio.
func (s *Service) Run(ctx context.Context) error {
return s.server.Run(ctx, &mcp.StdioTransport{})
}
// Server returns the underlying MCP server for advanced configuration.
func (s *Service) Server() *mcp.Server {
return s.server
}