fetch.go

  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/opencode-ai/opencode/internal/config"
 15	"github.com/opencode-ai/opencode/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		},
 73		permissions: permissions,
 74	}
 75}
 76
 77func (t *fetchTool) Info() ToolInfo {
 78	return ToolInfo{
 79		Name:        FetchToolName,
 80		Description: fetchToolDescription,
 81		Parameters: map[string]any{
 82			"url": map[string]any{
 83				"type":        "string",
 84				"description": "The URL to fetch content from",
 85			},
 86			"format": map[string]any{
 87				"type":        "string",
 88				"description": "The format to return the content in (text, markdown, or html)",
 89				"enum":        []string{"text", "markdown", "html"},
 90			},
 91			"timeout": map[string]any{
 92				"type":        "number",
 93				"description": "Optional timeout in seconds (max 120)",
 94			},
 95		},
 96		Required: []string{"url", "format"},
 97	}
 98}
 99
100func (t *fetchTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
101	var params FetchParams
102	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
103		return NewTextErrorResponse("Failed to parse fetch parameters: " + err.Error()), nil
104	}
105
106	if params.URL == "" {
107		return NewTextErrorResponse("URL parameter is required"), nil
108	}
109
110	format := strings.ToLower(params.Format)
111	if format != "text" && format != "markdown" && format != "html" {
112		return NewTextErrorResponse("Format must be one of: text, markdown, html"), nil
113	}
114
115	if !strings.HasPrefix(params.URL, "http://") && !strings.HasPrefix(params.URL, "https://") {
116		return NewTextErrorResponse("URL must start with http:// or https://"), nil
117	}
118
119	sessionID, messageID := GetContextValues(ctx)
120	if sessionID == "" || messageID == "" {
121		return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
122	}
123
124	p := t.permissions.Request(
125		permission.CreatePermissionRequest{
126			SessionID:   sessionID,
127			Path:        config.WorkingDirectory(),
128			ToolName:    FetchToolName,
129			Action:      "fetch",
130			Description: fmt.Sprintf("Fetch content from URL: %s", params.URL),
131			Params:      FetchPermissionsParams(params),
132		},
133	)
134
135	if !p {
136		return ToolResponse{}, permission.ErrorPermissionDenied
137	}
138
139	client := t.client
140	if params.Timeout > 0 {
141		maxTimeout := 120 // 2 minutes
142		if params.Timeout > maxTimeout {
143			params.Timeout = maxTimeout
144		}
145		client = &http.Client{
146			Timeout: time.Duration(params.Timeout) * time.Second,
147		}
148	}
149
150	req, err := http.NewRequestWithContext(ctx, "GET", params.URL, nil)
151	if err != nil {
152		return ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
153	}
154
155	req.Header.Set("User-Agent", "opencode/1.0")
156
157	resp, err := client.Do(req)
158	if err != nil {
159		return ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
160	}
161	defer resp.Body.Close()
162
163	if resp.StatusCode != http.StatusOK {
164		return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
165	}
166
167	maxSize := int64(5 * 1024 * 1024) // 5MB
168	body, err := io.ReadAll(io.LimitReader(resp.Body, maxSize))
169	if err != nil {
170		return NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
171	}
172
173	content := string(body)
174	contentType := resp.Header.Get("Content-Type")
175
176	switch format {
177	case "text":
178		if strings.Contains(contentType, "text/html") {
179			text, err := extractTextFromHTML(content)
180			if err != nil {
181				return NewTextErrorResponse("Failed to extract text from HTML: " + err.Error()), nil
182			}
183			return NewTextResponse(text), nil
184		}
185		return NewTextResponse(content), nil
186
187	case "markdown":
188		if strings.Contains(contentType, "text/html") {
189			markdown, err := convertHTMLToMarkdown(content)
190			if err != nil {
191				return NewTextErrorResponse("Failed to convert HTML to Markdown: " + err.Error()), nil
192			}
193			return NewTextResponse(markdown), nil
194		}
195
196		return NewTextResponse("```\n" + content + "\n```"), nil
197
198	case "html":
199		return NewTextResponse(content), nil
200
201	default:
202		return NewTextResponse(content), nil
203	}
204}
205
206func extractTextFromHTML(html string) (string, error) {
207	doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
208	if err != nil {
209		return "", err
210	}
211
212	text := doc.Text()
213	text = strings.Join(strings.Fields(text), " ")
214
215	return text, nil
216}
217
218func convertHTMLToMarkdown(html string) (string, error) {
219	converter := md.NewConverter("", true, nil)
220
221	markdown, err := converter.ConvertString(html)
222	if err != nil {
223		return "", err
224	}
225
226	return markdown, nil
227}