1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "strings"
10 "time"
11
12 md "github.com/JohannesKaufmann/html-to-markdown"
13 "github.com/PuerkitoBio/goquery"
14 "github.com/charmbracelet/crush/internal/config"
15 "github.com/charmbracelet/crush/internal/permission"
16)
17
18type FetchParams struct {
19 URL string `json:"url"`
20 Format string `json:"format"`
21 Timeout int `json:"timeout,omitempty"`
22}
23
24type FetchPermissionsParams struct {
25 URL string `json:"url"`
26 Format string `json:"format"`
27 Timeout int `json:"timeout,omitempty"`
28}
29
30type fetchTool struct {
31 client *http.Client
32 permissions permission.Service
33}
34
35const (
36 FetchToolName = "fetch"
37 fetchToolDescription = `Fetches content from a URL and returns it in the specified format.
38
39WHEN TO USE THIS TOOL:
40- Use when you need to download content from a URL
41- Helpful for retrieving documentation, API responses, or web content
42- Useful for getting external information to assist with tasks
43
44HOW TO USE:
45- Provide the URL to fetch content from
46- Specify the desired output format (text, markdown, or html)
47- Optionally set a timeout for the request
48
49FEATURES:
50- Supports three output formats: text, markdown, and html
51- Automatically handles HTTP redirects
52- Sets reasonable timeouts to prevent hanging
53- Validates input parameters before making requests
54
55LIMITATIONS:
56- Maximum response size is 5MB
57- Only supports HTTP and HTTPS protocols
58- Cannot handle authentication or cookies
59- Some websites may block automated requests
60
61TIPS:
62- Use text format for plain text content or simple API responses
63- Use markdown format for content that should be rendered with formatting
64- Use html format when you need the raw HTML structure
65- Set appropriate timeouts for potentially slow websites`
66)
67
68func NewFetchTool(permissions permission.Service) BaseTool {
69 return &fetchTool{
70 client: &http.Client{
71 Timeout: 30 * time.Second,
72 Transport: &http.Transport{
73 MaxIdleConns: 100,
74 MaxIdleConnsPerHost: 10,
75 IdleConnTimeout: 90 * time.Second,
76 },
77 },
78 permissions: permissions,
79 }
80}
81
82func (t *fetchTool) Name() string {
83 return FetchToolName
84}
85
86func (t *fetchTool) Info() ToolInfo {
87 return ToolInfo{
88 Name: FetchToolName,
89 Description: fetchToolDescription,
90 Parameters: map[string]any{
91 "url": map[string]any{
92 "type": "string",
93 "description": "The URL to fetch content from",
94 },
95 "format": map[string]any{
96 "type": "string",
97 "description": "The format to return the content in (text, markdown, or html)",
98 "enum": []string{"text", "markdown", "html"},
99 },
100 "timeout": map[string]any{
101 "type": "number",
102 "description": "Optional timeout in seconds (max 120)",
103 },
104 },
105 Required: []string{"url", "format"},
106 }
107}
108
109func (t *fetchTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
110 var params FetchParams
111 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
112 return NewTextErrorResponse("Failed to parse fetch parameters: " + err.Error()), nil
113 }
114
115 if params.URL == "" {
116 return NewTextErrorResponse("URL parameter is required"), nil
117 }
118
119 format := strings.ToLower(params.Format)
120 if format != "text" && format != "markdown" && format != "html" {
121 return NewTextErrorResponse("Format must be one of: text, markdown, html"), nil
122 }
123
124 if !strings.HasPrefix(params.URL, "http://") && !strings.HasPrefix(params.URL, "https://") {
125 return NewTextErrorResponse("URL must start with http:// or https://"), nil
126 }
127
128 sessionID, messageID := GetContextValues(ctx)
129 if sessionID == "" || messageID == "" {
130 return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
131 }
132
133 p := t.permissions.Request(
134 permission.CreatePermissionRequest{
135 SessionID: sessionID,
136 Path: config.Get().WorkingDir(),
137 ToolName: FetchToolName,
138 Action: "fetch",
139 Description: fmt.Sprintf("Fetch content from URL: %s", params.URL),
140 Params: FetchPermissionsParams(params),
141 },
142 )
143
144 if !p {
145 return ToolResponse{}, permission.ErrorPermissionDenied
146 }
147
148 // Handle timeout with context
149 requestCtx := ctx
150 if params.Timeout > 0 {
151 maxTimeout := 120 // 2 minutes
152 if params.Timeout > maxTimeout {
153 params.Timeout = maxTimeout
154 }
155 var cancel context.CancelFunc
156 requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
157 defer cancel()
158 }
159
160 req, err := http.NewRequestWithContext(requestCtx, "GET", params.URL, nil)
161 if err != nil {
162 return ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
163 }
164
165 req.Header.Set("User-Agent", "crush/1.0")
166
167 resp, err := t.client.Do(req)
168 if err != nil {
169 return ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
170 }
171 defer resp.Body.Close()
172
173 if resp.StatusCode != http.StatusOK {
174 return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
175 }
176
177 maxSize := int64(5 * 1024 * 1024) // 5MB
178 body, err := io.ReadAll(io.LimitReader(resp.Body, maxSize))
179 if err != nil {
180 return NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
181 }
182
183 content := string(body)
184 contentType := resp.Header.Get("Content-Type")
185
186 switch format {
187 case "text":
188 if strings.Contains(contentType, "text/html") {
189 text, err := extractTextFromHTML(content)
190 if err != nil {
191 return NewTextErrorResponse("Failed to extract text from HTML: " + err.Error()), nil
192 }
193 return NewTextResponse(text), nil
194 }
195 return NewTextResponse(content), nil
196
197 case "markdown":
198 if strings.Contains(contentType, "text/html") {
199 markdown, err := convertHTMLToMarkdown(content)
200 if err != nil {
201 return NewTextErrorResponse("Failed to convert HTML to Markdown: " + err.Error()), nil
202 }
203 return NewTextResponse(markdown), nil
204 }
205
206 return NewTextResponse("```\n" + content + "\n```"), nil
207
208 case "html":
209 return NewTextResponse(content), nil
210
211 default:
212 return NewTextResponse(content), nil
213 }
214}
215
216func extractTextFromHTML(html string) (string, error) {
217 doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
218 if err != nil {
219 return "", err
220 }
221
222 text := doc.Text()
223 text = strings.Join(strings.Fields(text), " ")
224
225 return text, nil
226}
227
228func convertHTMLToMarkdown(html string) (string, error) {
229 converter := md.NewConverter("", true, nil)
230
231 markdown, err := converter.ConvertString(html)
232 if err != nil {
233 return "", err
234 }
235
236 return markdown, nil
237}