import { tool } from 'langchain'; import * as z from 'zod'; import { safeFetch } from './http_client.js'; export const httpGetTool = tool( async ({ url, headers = {}, timeout = 15000 }) => { try { // 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成 const response = await safeFetch(url, { method: 'GET', headers: { 'User-Agent': 'XAgent-Bot/1.0', ...headers }, timeout }); const contentType = response.headers['content-type'] || ''; let body; if (contentType.includes('application/json')) { try { body = JSON.parse(response.text); } catch (e) { // 服务端声明 json 但返回非法内容时退回原文,避免工具直接抛错中断对话 body = response.text; } } else if (contentType.includes('text/') || contentType.includes('application/javascript')) { body = response.text; } else { body = response.buffer.toString('base64'); } return JSON.stringify({ success: true, status: response.status, statusText: response.statusText, headers: response.headers, truncated: response.truncated, body }); } catch (error) { if (error.name === 'AbortError') { return JSON.stringify({ success: false, error: 'Request timed out' }); } return JSON.stringify({ success: false, error: error.message }); } }, { name: 'http_get', description: 'Send HTTP GET request and return response content. Response body is capped at 2MB.', schema: z.object({ url: z.string().describe('Request URL'), headers: z.record(z.string(), z.string()).optional().describe('Request headers'), timeout: z.number().optional().describe('Timeout in milliseconds, clamped to 1s-15s') }) } );