fetch.go 5.8 KB

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