use super::http::{build_client, get};
use super::{Tool, ToolDefinition, FunctionDefinition, arg_str, arg_usize};
use std::io;
use serde_json::Value;
use atlas_http::HttpResponse;
use std::net::{IpAddr, ToSocketAddrs};
use url::Url;
const DEFAULT_MAX_BYTES: usize = 30_000;
const HARD_MAX_BYTES: usize = 100_000;
const MAX_REDIRECTS: usize = 5;
pub struct WebFetchTool;
impl WebFetchTool {
pub fn new() -> Self {
Self
}
pub fn get_definition(&self) -> ToolDefinition {
ToolDefinition {
tool_type: "function".to_string(),
function: FunctionDefinition {
name: self.name().to_string(),
description: self.description().to_string(),
parameters: serde_json::json!({
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "URL to fetch (http or https)."
},
"offset": {
"type": "integer",
"description": "Byte offset to start reading from (default 0)."
},
"max_bytes": {
"type": "integer",
"description": "Maximum number of bytes to return (default 30000, max 100000)."
}
},
"required": ["url"]
}),
},
}
}
}
impl Tool for WebFetchTool {
fn name(&self) -> &str {
"web_fetch"
}
fn description(&self) -> &str {
"Fetch the contents of a URL and return them as markdown or plain text."
}
fn execute(&self, arguments: &str) -> Result<String, io::Error> {
let data: Value = serde_json::from_str(arguments).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("Invalid arguments: {}", e)))?;
let url = arg_str(&data, "url")?;
let offset = arg_usize(&data, "offset", 0);
let max_bytes = arg_usize(&data, "max_bytes", DEFAULT_MAX_BYTES).min(HARD_MAX_BYTES);
Ok(fetch(url, offset, max_bytes))
}
}
fn fetch(url_str: &str, offset: usize, max_bytes: usize) -> String {
let mut current = match Url::parse(url_str) {
Ok(u) => u,
Err(e) => return format!("fetch failed: invalid url '{}': {}", url_str, e),
};
let mut client = build_client();
let mut hops = 0;
loop {
if let Err(reason) = check_url(¤t) {
return format!("blocked: {}", reason);
}
let res = match get(&mut client, current.as_str()) {
Ok(r) => r,
Err(e) => return format!("fetch failed: {}", e),
};
let status = res.status_code();
if (300..400).contains(&status) {
if hops >= MAX_REDIRECTS {
return format!("fetch failed: too many redirects (more than {} hops)", MAX_REDIRECTS);
}
match res.headers().get_lower("location") {
Some(location) => match current.join(&location) {
Ok(next) => {
current = next;
hops += 1;
}
Err(e) => return format!("fetch failed: invalid redirect location '{}': {}", location, e),
},
None => return format!("fetch failed: HTTP {} redirect without a Location header", status),
}
continue;
}
return handle_response(¤t, status, &res, offset, max_bytes);
}
}
fn check_url(url: &Url) -> Result<(), String> {
check_scheme(url)?;
let host = match url.host_str() {
Some(h) => h,
None => return Err("url has no host".to_string()),
};
let port = match url.port_or_known_default() {
Some(p) => p,
None => return Err(format!("unknown port for '{}'", url)),
};
let addrs = match (host, port).to_socket_addrs() {
Ok(a) => a,
Err(e) => return Err(format!("could not resolve host '{}': {}", host, e)),
};
for addr in addrs {
if let Some(reason) = block_reason(addr.ip()) {
return Err(format!("'{}' resolves to a {} ({}); request blocked", host, reason, addr.ip()));
}
}
Ok(())
}
fn check_scheme(url: &Url) -> Result<(), String> {
if url.scheme() != "http" && url.scheme() != "https" {
return Err(format!("unsupported scheme '{}' (only http and https are allowed)", url.scheme()));
}
Ok(())
}
fn block_reason(ip: IpAddr) -> Option<&'static str> {
match ip {
IpAddr::V4(v4) => {
if v4.is_loopback() {
Some("loopback address")
} else if v4.is_private() {
Some("private (RFC1918) address")
} else if v4.is_link_local() {
Some("link-local address")
} else if v4.is_unspecified() {
Some("unspecified address")
} else {
None
}
}
IpAddr::V6(v6) => {
if v6.is_loopback() {
Some("loopback address")
} else if v6.is_unique_local() {
Some("IPv6 unique-local address")
} else if v6.is_unicast_link_local() {
Some("IPv6 link-local address")
} else if v6.is_unspecified() {
Some("unspecified address")
} else {
None
}
}
}
}
fn is_blocked_ip(ip: IpAddr) -> bool {
block_reason(ip).is_some()
}
fn handle_response(url: &Url, status: u16, res: &HttpResponse, offset: usize, max_bytes: usize) -> String {
let content_type = res.headers().get_lower("content-type").unwrap_or_default();
let body = res.body();
if !(200..300).contains(&status) {
return format!("fetch failed: HTTP {}\n\n{}", status, excerpt(&body, 500));
}
if is_binary_content_type(&content_type) {
let size = res.headers().get_lower("content-length").and_then(|s| s.trim().parse::<usize>().ok()).unwrap_or_else(|| body.len());
return format!("not fetched: binary content ({}), {} bytes", content_type, size);
}
let (full, extraction, title) = if is_html_content_type(&content_type) {
let (content, extraction, title) = html_to_content(&body, url.as_str());
(content, Some(extraction), title)
} else {
(body, None, None)
};
let total = full.len();
let shown = truncate(&full, offset, max_bytes);
build_output(url.as_str(), status, &content_type, title.as_deref(), extraction, total, &shown)
}
fn html_to_content(html: &str, final_url: &str) -> (String, &'static str, Option<String>) {
let fallback = match convert_html_fallback(html) {
Ok(md) => md,
Err(_) => String::new(),
};
let fallback_len = fallback.len();
match lectito::extract(html, Some(final_url), &lectito::ReadabilityOptions::default()) {
Ok(Some(article)) => {
let text_len = article.text_content.len();
let too_short = fallback_len > 0 && (text_len as f64) < (fallback_len as f64) * 0.2;
let title = article.title.clone().or_else(|| html_title(html));
if too_short {
(fallback, "fallback", title)
} else {
(article.markdown, "readability", title)
}
}
_ => (fallback, "fallback", html_title(html)),
}
}
fn convert_html_fallback(html: &str) -> Result<String, String> {
let converter = htmd::HtmlToMarkdown::builder().skip_tags(vec!["script", "style", "nav", "header", "footer", "aside", "noscript"]).build();
converter.convert(html).map_err(|e| e.to_string())
}
fn html_title(html: &str) -> Option<String> {
let document = scraper::Html::parse_document(html);
let sel = scraper::Selector::parse("title").ok()?;
document.select(&sel).next().map(|el| el.text().collect::<String>().trim().to_string())
}
fn is_html_content_type(content_type: &str) -> bool {
let ct = content_type.to_ascii_lowercase();
ct.contains("text/html") || ct.contains("application/xhtml+xml")
}
fn is_binary_content_type(content_type: &str) -> bool {
let ct = content_type.to_ascii_lowercase();
[
"image/",
"audio/",
"video/",
"font/",
"application/pdf",
"application/zip",
"application/gzip",
"application/x-gzip",
"application/x-tar",
"application/x-compressed",
"application/x-7z-compressed",
"application/x-rar-compressed",
"application/octet-stream",
"application/vnd.",
"application/wasm",
]
.iter()
.any(|p| ct.contains(p))
|| ct.contains("binary")
}
fn floor_char_boundary(s: &str, mut byte: usize) -> usize {
if byte >= s.len() {
return s.len();
}
while !s.is_char_boundary(byte) {
byte -= 1;
}
byte
}
fn truncate(full: &str, offset: usize, max_bytes: usize) -> String {
let total = full.len();
let start = floor_char_boundary(full, offset);
let rest = &full[start..];
let end = floor_char_boundary(rest, max_bytes);
let shown = &rest[..end];
let truncated = (start + end) < total;
if truncated {
let next_offset = start + end;
format!("{}\n[truncated: showing bytes {}-{} of {}. Call again with offset={} for more.]", shown, start, next_offset, total, next_offset)
} else {
shown.to_string()
}
}
fn excerpt(body: &str, max: usize) -> String {
let body = body.trim();
let end = floor_char_boundary(body, max);
if end < body.len() {
format!("{}...", &body[..end])
} else {
body.to_string()
}
}
fn build_output(final_url: &str, status: u16, content_type: &str, title: Option<&str>, extraction: Option<&str>, total: usize, shown: &str) -> String {
let mut header = String::new();
header.push_str(&format!("url: {}\n", final_url));
header.push_str(&format!("status: {}\n", status));
header.push_str(&format!("content-type: {}\n", content_type));
if let Some(t) = title {
if !t.is_empty() {
header.push_str(&format!("title: {}\n", t));
}
}
if let Some(e) = extraction {
header.push_str(&format!("extraction: {}\n", e));
}
header.push_str(&format!("size: {} bytes\n", total));
let safe_url = final_url.replace('"', "%22");
let neutralized = shown.replace("</web_content>", "<\\/web_content>");
format!("{}\n<web_content url=\"{}\" untrusted=\"true\">\n{}\n</web_content>", header, safe_url, neutralized)
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{Ipv4Addr, Ipv6Addr};
#[test]
fn truncate_does_not_split_multibyte_chars() {
let s = "aébc";
assert_eq!(floor_char_boundary(s, 3), 3);
let out = truncate(s, 0, 3);
assert!(out.starts_with("aé"));
}
#[test]
fn truncate_reports_remaining_bytes() {
let s = "hello world";
let out = truncate(s, 0, 5);
assert_eq!(out, "hello\n[truncated: showing bytes 0-5 of 11. Call again with offset=5 for more.]");
}
#[test]
fn truncate_applies_offset_on_char_boundary() {
let s = "aébcdef";
let out = truncate(s, 2, 5);
assert!(out.starts_with("ébc"));
}
#[test]
fn truncate_no_truncation_when_short() {
let out = truncate("short", 0, 100);
assert_eq!(out, "short");
}
#[test]
fn ipv4_blocklist() {
assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))));
assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))));
assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1))));
assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))));
assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))));
assert!(!is_blocked_ip(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))));
}
#[test]
fn ipv6_blocklist() {
assert!(is_blocked_ip(IpAddr::V6(Ipv6Addr::LOCALHOST)));
assert!(is_blocked_ip(IpAddr::V6(Ipv6Addr::UNSPECIFIED)));
assert!(is_blocked_ip("fc00::1".parse().unwrap()));
assert!(is_blocked_ip("fe80::1".parse().unwrap()));
assert!(!is_blocked_ip("2606:4700:4700::1111".parse().unwrap()));
}
#[test]
fn scheme_rejection() {
let ftp = Url::parse("ftp://example.com/file").unwrap();
assert!(check_scheme(&ftp).is_err());
let http = Url::parse("http://example.com/").unwrap();
assert!(check_scheme(&http).is_ok());
let https = Url::parse("https://example.com/").unwrap();
assert!(check_scheme(&https).is_ok());
}
#[test]
fn excerpt_respects_char_boundary() {
let out = excerpt("éééé", 3);
assert_eq!(out, "é...");
}
}