package handler
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/mark3labs/mcp-go/mcp"
)
func (fs *FilesystemHandler) HandleWriteFile(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
path, err := request.RequireString("path")
if err != nil {
return nil, err
}
content, err := request.RequireString("content")
if err != nil {
return nil, err
}
// Handle empty or relative paths like "." or "./" by converting to absolute path
if path == "." || path == "./" {
// Get current working directory
cwd, err := os.Getwd()
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error resolving current directory: %v", err),
},
},
IsError: true,
}, nil
}
path = cwd
}
validPath, err := fs.validatePath(path)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
// Check if it's a directory
if info, err := os.Stat(validPath); err == nil && info.IsDir() {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: "Error: Cannot write to a directory",
},
},
IsError: true,
}, nil
}
// Create parent directories if they don't exist
parentDir := filepath.Dir(validPath)
if err := os.MkdirAll(parentDir, 0755); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error creating parent directories: %v", err),
},
},
IsError: true,
}, nil
}
if err := os.WriteFile(validPath, []byte(content), 0644); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error writing file: %v", err),
},
},
IsError: true,
}, nil
}
// Get file info for the response
info, err := os.Stat(validPath)
if err != nil {
// File was written but we couldn't get info
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Successfully wrote to %s", path),
},
},
}, nil
}
resourceURI := pathToResourceURI(validPath)
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Successfully wrote %d bytes to %s", info.Size(), path),
},
mcp.EmbeddedResource{
Type: "resource",
Resource: mcp.TextResourceContents{
URI: resourceURI,
MIMEType: "text/plain",
Text: fmt.Sprintf("File: %s (%d bytes)", validPath, info.Size()),
},
},
},
}, nil
}