xonecas.io
62159
Sy

symb / files

symb / internal / mcptools / helpers.go

1.4 KB
1package mcptools
2
3import (
4	"fmt"
5	"os"
6	"path/filepath"
7	"strings"
8
9	"github.com/xonecas/symb/internal/mcp"
10)
11
12// validatePath resolves a file path, ensuring it's within the working directory.
13func validatePath(file string) (string, error) {
14	workingDir, err := os.Getwd()
15	if err != nil {
16		return "", fmt.Errorf("failed to get working directory: %w", err)
17	}
18	return validatePathWithRoot(file, workingDir)
19}
20
21func validatePathWithRoot(file, root string) (string, error) {
22	rootAbs, err := filepath.Abs(root)
23	if err != nil {
24		return "", fmt.Errorf("invalid root path: %w", err)
25	}
26	var absPath string
27	if filepath.IsAbs(file) {
28		absPath = file
29	} else {
30		absPath = filepath.Join(rootAbs, file)
31	}
32	absPath, err = filepath.Abs(absPath)
33	if err != nil {
34		return "", fmt.Errorf("invalid file path: %w", err)
35	}
36	relPath, err := filepath.Rel(rootAbs, absPath)
37	if err != nil || strings.HasPrefix(relPath, "..") || filepath.IsAbs(relPath) {
38		return "", fmt.Errorf("access denied: path outside working directory")
39	}
40	return absPath, nil
41}
42
43// toolError returns an error ToolResult.
44func toolError(format string, args ...interface{}) *mcp.ToolResult {
45	return &mcp.ToolResult{
46		Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf(format, args...)}},
47		IsError: true,
48	}
49}
50
51// toolText returns a text ToolResult.
52func toolText(text string) *mcp.ToolResult {
53	return &mcp.ToolResult{
54		Content: []mcp.ContentBlock{{Type: "text", Text: text}},
55		IsError: false,
56	}
57}