| 1 | import type { ContextItem } from "core/index.js"; |
| 2 | import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js"; |
| 3 | |
| 4 | import { Tool } from "./types.js"; |
| 5 | |
| 6 | export const fetchTool: Tool = { |
| 7 | name: "Fetch", |
| 8 | displayName: "Fetch", |
| 9 | description: |
| 10 | "Fetches content from a URL, converts to markdown, and handles long content with truncation", |
| 11 | parameters: { |
| 12 | type: "object", |
| 13 | required: ["url"], |
| 14 | properties: { |
| 15 | url: { |
| 16 | type: "string", |
| 17 | description: "The URL to fetch content from", |
| 18 | }, |
| 19 | }, |
| 20 | }, |
| 21 | readonly: true, |
| 22 | isBuiltIn: true, |
| 23 | preprocess: async (args) => { |
| 24 | return { |
| 25 | preview: [ |
| 26 | { |
| 27 | type: "text", |
| 28 | content: `Will fetch: ${args.url}`, |
| 29 | }, |
| 30 | ], |
| 31 | args, |
| 32 | }; |
| 33 | }, |
| 34 | run: async (args: { url: string }): Promise<string> => { |
| 35 | const { url } = args; |
| 36 | |
| 37 | try { |
| 38 | // Suppress console errors from JSDOM CSS parsing |
| 39 | const originalConsoleError = console.error; |
| 40 | console.error = () => {}; |
| 41 | |
| 42 | // Use the core fetchUrlContent implementation |
| 43 | const contextItems = await fetchUrlContentImpl({ url }, { fetch }); |
| 44 | |
| 45 | // Restore console.error |
| 46 | console.error = originalConsoleError; |
| 47 | |
| 48 | if (contextItems.length === 0) { |
| 49 | return `Error: Could not fetch content from ${url}`; |
| 50 | } |
| 51 | |
| 52 | // Format the results for CLI display |
| 53 | return contextItems |
| 54 | .map((item: ContextItem) => { |
| 55 | if (item.name === "Truncation warning") { |
| 56 | return item.content; |
| 57 | } |
| 58 | return item.content; |
| 59 | }) |
| 60 | .join("\n\n"); |
| 61 | } catch (error) { |
| 62 | return `Error: ${error instanceof Error ? error.message : String(error)}`; |
| 63 | } |
| 64 | }, |
| 65 | }; |