1package commands
2
3import (
4 "context"
5 "io/fs"
6 "os"
7 "path/filepath"
8 "regexp"
9 "strings"
10 "time"
11
12 "github.com/charmbracelet/crush/internal/agent/tools/mcp"
13 "github.com/charmbracelet/crush/internal/config"
14 "github.com/charmbracelet/crush/internal/home"
15)
16
17var namedArgPattern = regexp.MustCompile(`\$([A-Z][A-Z0-9_]*)`)
18
19const (
20 userCommandPrefix = "user:"
21 projectCommandPrefix = "project:"
22)
23
24// Argument represents a command argument with its metadata.
25type Argument struct {
26 ID string
27 Title string
28 Description string
29 Required bool
30}
31
32// MCPPrompt represents a custom command loaded from an MCP server.
33type MCPPrompt struct {
34 ID string
35 Title string
36 Description string
37 PromptID string
38 ClientID string
39 Arguments []Argument
40}
41
42// CustomCommand represents a user-defined custom command loaded from markdown files.
43type CustomCommand struct {
44 ID string
45 Name string
46 Content string
47 Arguments []Argument
48}
49
50type commandSource struct {
51 path string
52 prefix string
53}
54
55// LoadCustomCommands loads custom commands from multiple sources including
56// XDG config directory, home directory, and project directory.
57func LoadCustomCommands(cfg *config.Config) ([]CustomCommand, error) {
58 return loadAll(buildCommandSources(cfg))
59}
60
61// LoadMCPPrompts loads custom commands from available MCP servers.
62func LoadMCPPrompts() ([]MCPPrompt, error) {
63 var commands []MCPPrompt
64 for mcpName, prompts := range mcp.Prompts() {
65 for _, prompt := range prompts {
66 key := mcpName + ":" + prompt.Name
67 var args []Argument
68 for _, arg := range prompt.Arguments {
69 title := arg.Title
70 if title == "" {
71 title = arg.Name
72 }
73 args = append(args, Argument{
74 ID: arg.Name,
75 Title: title,
76 Description: arg.Description,
77 Required: arg.Required,
78 })
79 }
80 commands = append(commands, MCPPrompt{
81 ID: key,
82 Title: prompt.Title,
83 Description: prompt.Description,
84 PromptID: prompt.Name,
85 ClientID: mcpName,
86 Arguments: args,
87 })
88 }
89 }
90 return commands, nil
91}
92
93func buildCommandSources(cfg *config.Config) []commandSource {
94 return []commandSource{
95 {
96 path: filepath.Join(home.Config(), "crush", "commands"),
97 prefix: userCommandPrefix,
98 },
99 {
100 path: filepath.Join(home.Dir(), ".crush", "commands"),
101 prefix: userCommandPrefix,
102 },
103 {
104 path: filepath.Join(cfg.Options.DataDirectory, "commands"),
105 prefix: projectCommandPrefix,
106 },
107 }
108}
109
110func loadAll(sources []commandSource) ([]CustomCommand, error) {
111 var commands []CustomCommand
112
113 for _, source := range sources {
114 if cmds, err := loadFromSource(source); err == nil {
115 commands = append(commands, cmds...)
116 }
117 }
118
119 return commands, nil
120}
121
122func loadFromSource(source commandSource) ([]CustomCommand, error) {
123 if _, err := os.Stat(source.path); os.IsNotExist(err) {
124 return nil, nil
125 }
126
127 var commands []CustomCommand
128
129 err := filepath.WalkDir(source.path, func(path string, d fs.DirEntry, err error) error {
130 if err != nil || d.IsDir() || !isMarkdownFile(d.Name()) {
131 return err
132 }
133
134 cmd, err := loadCommand(path, source.path, source.prefix)
135 if err != nil {
136 return nil // Skip invalid files
137 }
138
139 commands = append(commands, cmd)
140 return nil
141 })
142
143 return commands, err
144}
145
146func loadCommand(path, baseDir, prefix string) (CustomCommand, error) {
147 content, err := os.ReadFile(path)
148 if err != nil {
149 return CustomCommand{}, err
150 }
151
152 id := buildCommandID(path, baseDir, prefix)
153
154 return CustomCommand{
155 ID: id,
156 Name: id,
157 Content: string(content),
158 Arguments: extractArgNames(string(content)),
159 }, nil
160}
161
162func extractArgNames(content string) []Argument {
163 matches := namedArgPattern.FindAllStringSubmatch(content, -1)
164 if len(matches) == 0 {
165 return nil
166 }
167
168 seen := make(map[string]bool)
169 var args []Argument
170
171 for _, match := range matches {
172 arg := match[1]
173 if !seen[arg] {
174 seen[arg] = true
175 // for normal custom commands, all args are required
176 args = append(args, Argument{ID: arg, Title: arg, Required: true})
177 }
178 }
179
180 return args
181}
182
183func buildCommandID(path, baseDir, prefix string) string {
184 relPath, _ := filepath.Rel(baseDir, path)
185 parts := strings.Split(relPath, string(filepath.Separator))
186
187 // Remove .md extension from last part
188 if len(parts) > 0 {
189 lastIdx := len(parts) - 1
190 parts[lastIdx] = strings.TrimSuffix(parts[lastIdx], filepath.Ext(parts[lastIdx]))
191 }
192
193 return prefix + strings.Join(parts, ":")
194}
195
196func isMarkdownFile(name string) bool {
197 return strings.HasSuffix(strings.ToLower(name), ".md")
198}
199
200func GetMCPPrompt(cfg *config.ConfigStore, clientID, promptID string, args map[string]string) (string, error) {
201 // Create a context with timeout since tea.Cmd doesn't support context passing.
202 // The MCP client has its own timeout, but this provides an additional safeguard.
203 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
204 defer cancel()
205
206 result, err := mcp.GetPromptMessages(ctx, cfg, clientID, promptID, args)
207 if err != nil {
208 return "", err
209 }
210 return strings.Join(result, " "), nil
211}