use crate::ssrf::{check_ssrf_url, check_ssrf_url_static, is_explicit_local_host, strip_brackets};
use merry_core::{ErrorInfo, PendingToolCall};
use merry_runtime::{
LivePolicyHandle, NetworkAccessDecision, PermissionedAction, RegisteredTool,
RequestedCapability, ToolActionKind, ToolBuildError, ToolExecutionContext, ToolExecutionError,
ToolExecutionOutcome, ToolExecutor, ToolExecutorFuture, ToolPermissionRequirement,
normalize_network_domain,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use std::{net::SocketAddr, sync::Arc, time::Duration};
use url::Url;
mod html;
pub const WEB_FETCH_TOOL: &str = "web_fetch";
const DEFAULT_TIMEOUT_SECS: u64 = 20;
const DEFAULT_MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
const DEFAULT_MAX_OUTPUT_CHARS: usize = 32_000;
const MAX_REDIRECTS: usize = 10;
#[derive(Debug, Clone)]
pub struct WebFetchConfig {
allow_local: bool,
timeout: Duration,
max_response_bytes: usize,
max_output_chars: usize,
live_network_policy: Option<LivePolicyHandle>,
}
impl Default for WebFetchConfig {
fn default() -> Self {
Self {
allow_local: true,
timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
live_network_policy: None,
}
}
}
impl WebFetchConfig {
#[must_use]
pub fn with_allow_local(mut self, allow_local: bool) -> Self {
self.allow_local = allow_local;
self
}
#[must_use]
pub fn with_live_network_policy(mut self, policy: LivePolicyHandle) -> Self {
self.live_network_policy = Some(policy);
self
}
#[must_use]
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn with_max_response_bytes(mut self, max_response_bytes: usize) -> Self {
self.max_response_bytes = max_response_bytes;
self
}
#[must_use]
pub fn with_max_output_chars(mut self, max_output_chars: usize) -> Self {
self.max_output_chars = max_output_chars;
self
}
}
#[merry_tools_macros::tool(
crate = "crate",
name = "web_fetch",
description = "Fetch a static web page, API JSON endpoint, or plain text document over HTTP/HTTPS and return clean extracted Markdown or text. Use this instead of browser tools when reading documentation or non-interactive URLs. Authenticated or private URLs fail. An SSRF refusal is final for that URL. Cross-host redirects stop and return the redirect URL instead of following automatically."
)]
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct WebFetchInput {
#[schemars(
description = "Target http:// or https:// URL to fetch.",
length(min = 1)
)]
url: String,
#[serde(default)]
#[schemars(
description = "Optional maximum character length for returned extracted content.",
range(min = 100)
)]
max_chars: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct WebFetchTool {
config: Arc<WebFetchConfig>,
}
impl WebFetchTool {
#[must_use]
pub fn new(config: WebFetchConfig) -> Self {
Self {
config: Arc::new(config),
}
}
pub fn into_registered_tool(self) -> Result<RegisteredTool, ToolBuildError> {
let spec = WebFetchInput::tool_spec()?;
Ok(
RegisteredTool::new(spec, Arc::new(self), ToolActionKind::Network)
.with_permissioned_network_lane()
.with_parallel_safe_execution(),
)
}
}
impl Default for WebFetchTool {
fn default() -> Self {
Self::new(WebFetchConfig::default())
}
}
impl ToolExecutor for WebFetchTool {
fn execute<'a>(
&'a self,
call: PendingToolCall,
context: ToolExecutionContext,
) -> ToolExecutorFuture<'a> {
Box::pin(async move {
if context.cancellation_token().is_cancelled() {
return Err(ToolExecutionError::Cancelled);
}
let input: WebFetchInput = match call.arguments().deserialize_as() {
Ok(input) => input,
Err(error) => {
return Ok(web_fetch_failed(
"web_fetch_invalid_arguments",
format!("invalid web_fetch arguments: {error}"),
None,
));
}
};
tokio::select! {
biased;
() = context.cancellation_token().cancelled() => Err(ToolExecutionError::Cancelled),
result = execute_fetch(&self.config, input, context.approved_network_domains()) => result,
}
})
}
}
async fn execute_fetch(
config: &WebFetchConfig,
input: WebFetchInput,
approved_once_domains: &[String],
) -> Result<ToolExecutionOutcome, ToolExecutionError> {
let mut url = match Url::parse(input.url.trim()) {
Ok(url) => url,
Err(error) => {
return Ok(web_fetch_failed(
"web_fetch_invalid_url",
format!("invalid URL {:?}: {error}", input.url),
None,
));
}
};
if url.scheme() == "http"
&& let Some(host) = url.host_str()
&& !is_explicit_local_host(host)
{
let _ = url.set_scheme("https");
}
let effective_allow_local = config.allow_local
&& config
.live_network_policy
.as_ref()
.is_none_or(LivePolicyHandle::network_allow_local);
if let Err(reason) = check_ssrf_url_static(&url, effective_allow_local) {
return Ok(web_fetch_failed(
"web_fetch_ssrf_blocked",
reason,
Some(url.as_str()),
));
}
if let Some(policy) = config.live_network_policy.as_ref()
&& let Some(raw_host) = url.host_str()
{
match policy.evaluate_network_host(raw_host, approved_once_domains) {
NetworkAccessDecision::Allow => {}
NetworkAccessDecision::Deny => {
return Ok(web_fetch_failed(
"web_fetch_network_denied",
format!(
"outbound network access to {:?} is denied by current network policy",
raw_host
),
Some(url.as_str()),
));
}
NetworkAccessDecision::RequireReview => {
let normalized_host =
normalize_network_domain(raw_host).unwrap_or_else(|| raw_host.to_owned());
return Err(ToolExecutionError::permission_required(
ToolPermissionRequirement::new(
PermissionedAction::NetworkUrl {
tool: WEB_FETCH_TOOL.to_owned(),
url: url.to_string(),
host: normalized_host.clone(),
},
vec![RequestedCapability::NetworkDomain(normalized_host)],
Some(format!("Fetch {url}")),
),
));
}
}
}
let initial_addrs = match check_ssrf_url(&url, effective_allow_local).await {
Ok(addrs) => addrs,
Err(reason) => {
return Ok(web_fetch_failed(
"web_fetch_ssrf_blocked",
reason,
Some(url.as_str()),
));
}
};
let client = match build_pinned_client(config, &url, &initial_addrs) {
Ok(client) => client,
Err(error) => {
return Ok(web_fetch_failed(
"web_fetch_client_error",
error,
Some(url.as_str()),
));
}
};
let mut current_url = url.clone();
let response = match follow_same_host_redirects(
&client,
effective_allow_local,
&mut current_url,
)
.await
{
Ok(RedirectStep::Response(resp)) => resp,
Ok(RedirectStep::CrossHostRedirect {
status_code,
redirect_url,
}) => {
let summary = format!(
"Stopped at cross-host redirect ({status_code}) from {current_url} to {redirect_url}. Inspect the destination URL and fetch it directly if intended."
);
return Ok(ToolExecutionOutcome::succeeded_text(summary));
}
Err(outcome) => return Ok(*outcome),
};
let status_code = response.status().as_u16();
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let (raw_bytes, body_truncated) =
match read_bounded_body(response, config.max_response_bytes).await {
Ok(data) => data,
Err(error) => {
return Ok(web_fetch_failed(
"web_fetch_read_failed",
error,
Some(current_url.as_str()),
));
}
};
let (title, full_extracted) = format_response_content(&raw_bytes, content_type.as_deref());
let limit = input
.max_chars
.unwrap_or(config.max_output_chars)
.min(config.max_output_chars);
let (model_body, text_truncated) = truncate_chars(&full_extracted, limit);
let truncated = body_truncated || text_truncated;
if status_code >= 400 {
let detail = format!("HTTP {status_code} fetching {current_url}\n\n{model_body}");
return Ok(web_fetch_failed(
"web_fetch_http_error",
detail,
Some(current_url.as_str()),
));
}
let mut model_summary = format!("URL: {current_url}\nStatus: {status_code}\n");
if let Some(title_text) = title.as_deref() {
model_summary.push_str(&format!("Title: {title_text}\n"));
}
model_summary.push('\n');
model_summary.push_str(&model_body);
if truncated {
model_summary.push_str("\n\n[truncated]");
}
Ok(ToolExecutionOutcome::succeeded_text(model_summary))
}
enum RedirectStep {
Response(reqwest::Response),
CrossHostRedirect {
status_code: u16,
redirect_url: String,
},
}
async fn follow_same_host_redirects(
client: &reqwest::Client,
allow_local: bool,
current_url: &mut Url,
) -> Result<RedirectStep, Box<ToolExecutionOutcome>> {
for hop in 0..=MAX_REDIRECTS {
let response = client
.get(current_url.clone())
.send()
.await
.map_err(|error| {
Box::new(web_fetch_failed(
"web_fetch_request_failed",
format!("HTTP request failed: {error}"),
Some(current_url.as_str()),
))
})?;
let status = response.status();
if !status.is_redirection() {
return Ok(RedirectStep::Response(response));
}
let Some(location) = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|value| value.to_str().ok())
else {
return Ok(RedirectStep::Response(response));
};
let next_url = current_url.join(location).map_err(|error| {
Box::new(web_fetch_failed(
"web_fetch_invalid_redirect",
format!("invalid redirect location {location:?}: {error}"),
Some(current_url.as_str()),
))
})?;
let https_downgrade = current_url.scheme() == "https"
&& next_url.scheme() == "http"
&& !next_url.host_str().is_some_and(is_explicit_local_host);
if !same_host(current_url, &next_url) || https_downgrade {
return Ok(RedirectStep::CrossHostRedirect {
status_code: status.as_u16(),
redirect_url: next_url.to_string(),
});
}
if hop == MAX_REDIRECTS {
return Err(Box::new(web_fetch_failed(
"web_fetch_too_many_redirects",
format!("exceeded {MAX_REDIRECTS} same-host redirects"),
Some(next_url.as_str()),
)));
}
if let Err(reason) = check_ssrf_url(&next_url, allow_local).await {
return Err(Box::new(web_fetch_failed(
"web_fetch_ssrf_blocked",
reason,
Some(next_url.as_str()),
)));
}
*current_url = next_url;
}
unreachable!("redirect loop returns within bounded hops")
}
fn build_pinned_client(
config: &WebFetchConfig,
url: &Url,
addrs: &[SocketAddr],
) -> Result<reqwest::Client, String> {
let mut builder = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(config.timeout)
.user_agent("MerryWebFetch/0.1");
if let Some(host) = url.host_str()
&& !addrs.is_empty()
{
builder = builder.resolve_to_addrs(strip_brackets(host), addrs);
}
builder
.build()
.map_err(|error| format!("failed to build HTTP client: {error}"))
}
fn same_host(a: &Url, b: &Url) -> bool {
let normalize = |u: &Url| u.host_str().and_then(normalize_network_domain);
matches!((normalize(a), normalize(b)), (Some(left), Some(right)) if left == right)
}
async fn read_bounded_body(
mut response: reqwest::Response,
max_bytes: usize,
) -> Result<(Vec<u8>, bool), String> {
let mut out = Vec::new();
let mut truncated = false;
while let Some(chunk) = response
.chunk()
.await
.map_err(|error| format!("error reading response body: {error}"))?
{
let remaining = max_bytes.saturating_sub(out.len());
if remaining == 0 {
truncated = true;
break;
}
if chunk.len() > remaining {
out.extend_from_slice(&chunk[..remaining]);
truncated = true;
break;
}
out.extend_from_slice(&chunk);
}
Ok((out, truncated))
}
fn format_response_content(bytes: &[u8], content_type: Option<&str>) -> (Option<String>, String) {
let mime = content_type
.unwrap_or("text/plain")
.split(';')
.next()
.unwrap_or("text/plain")
.trim()
.to_ascii_lowercase();
let text = String::from_utf8_lossy(bytes);
if mime == "text/html" || mime == "application/xhtml+xml" {
let title = html::extract_html_title(&text);
let md = html::html_to_markdown(&text);
let content = if md.trim().is_empty() {
"[HTML page had no extractable text content]".to_owned()
} else {
md
};
return (title, content);
}
if mime == "application/json" || mime.ends_with("+json") {
let formatted = serde_json::from_slice::<serde_json::Value>(bytes)
.and_then(|v| serde_json::to_string_pretty(&v))
.unwrap_or_else(|_| text.into_owned());
return (None, html::strip_base64_data_uris(&formatted));
}
if mime.starts_with("text/")
|| mime.contains("xml")
|| mime.contains("javascript")
|| mime.contains("yaml")
{
let cleaned = html::strip_base64_data_uris(&text);
let content = if cleaned.trim().is_empty() {
"[empty text response]".to_owned()
} else {
cleaned
};
return (None, content);
}
(
None,
format!("[non-text content type={mime} bytes={}]", bytes.len()),
)
}
fn truncate_chars(text: &str, max_chars: usize) -> (String, bool) {
if text.chars().count() <= max_chars {
return (text.to_owned(), false);
}
let truncated: String = text.chars().take(max_chars).collect();
(truncated, true)
}
fn web_fetch_failed(
code: &'static str,
message: String,
url: Option<&str>,
) -> ToolExecutionOutcome {
let payload = json!({
"ok": false,
"tool": WEB_FETCH_TOOL,
"url": url,
"error": {
"code": code,
"message": message,
}
});
let safe_diag_msg: String = message
.chars()
.filter(|c| !c.is_control())
.take(512)
.collect();
let diagnostic = ErrorInfo::new(
code,
if safe_diag_msg.trim().is_empty() {
"web_fetch failed"
} else {
&safe_diag_msg
},
)
.expect("sanitized web_fetch diagnostic is valid");
ToolExecutionOutcome::failed_json(payload.to_string(), diagnostic)
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
Router,
http::StatusCode,
response::{Html, IntoResponse, Redirect},
routing::get,
};
use merry_core::{
PendingToolCall, ToolCallArguments, ToolCallId, ToolCallResultStatus, ToolName,
};
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
fn test_call(args: serde_json::Value) -> PendingToolCall {
PendingToolCall::new(
ToolCallId::new("call-web-fetch").expect("valid id"),
ToolName::new(WEB_FETCH_TOOL).expect("valid name"),
ToolCallArguments::try_from(args).expect("object args"),
)
}
#[tokio::test]
async fn blocks_ssrf_targets_and_fetches_loopback_html_when_allowed() {
let blocked_tool = WebFetchTool::new(WebFetchConfig::default().with_allow_local(false));
let blocked = blocked_tool
.execute(
test_call(json!({"url": "http://127.0.0.1:8080/"})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect("returns failed outcome");
assert_eq!(blocked.status(), ToolCallResultStatus::Failed);
assert_eq!(
blocked.diagnostic().expect("diag").code(),
"web_fetch_ssrf_blocked"
);
let app = Router::new()
.route(
"/docs",
get(|| async {
Html("<html><head><title>Test Page</title></head><body><h1>Hello</h1><p>World</p><script>bad()</script></body></html>")
}),
)
.route(
"/bounce",
get(|| async { Redirect::temporary("https://other.example.com/target").into_response() }),
)
.route(
"/local-redirect",
get(|| async { (StatusCode::FOUND, [("location", "/docs")]).into_response() }),
);
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind loopback");
let addr = listener.local_addr().expect("addr");
let server = tokio::spawn(async move {
axum::serve(listener, app).await.expect("serve");
});
let local_tool = WebFetchTool::default();
let ok = local_tool
.execute(
test_call(
json!({"url": format!("http://127.0.0.1:{}/local-redirect", addr.port())}),
),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect("fetch succeeds");
assert_eq!(ok.status(), ToolCallResultStatus::Succeeded);
assert!(ok.model_content().is_none());
let text = ok.content().as_str();
assert!(text.contains("Title: Test Page"));
assert!(text.contains("# Hello"));
assert!(!text.contains("bad()"));
let cross_host = local_tool
.execute(
test_call(json!({"url": format!("http://127.0.0.1:{}/bounce", addr.port())})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect("cross-host redirect returns cleanly");
assert_eq!(cross_host.status(), ToolCallResultStatus::Succeeded);
assert!(cross_host.model_content().is_none());
assert!(
cross_host
.content()
.as_str()
.contains("https://other.example.com/target")
);
server.abort();
}
#[tokio::test]
async fn web_fetch_enforces_live_network_policy_domain_grants_and_ssrf_floor() {
use merry_core::CapabilityPolicy;
use merry_runtime::{
LivePolicyHandle, NetworkAccessPolicy, PermissionedAction, ProcessSessionPermissions,
RequestedCapability, ToolExecutionError,
};
let deny_policy =
LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Deny, true));
let deny_tool =
WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(deny_policy));
let denied = deny_tool
.execute(
test_call(json!({"url": "https://docs.rs/serde"})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect("network deny returns failed outcome without review");
assert_eq!(denied.status(), ToolCallResultStatus::Failed);
assert_eq!(
denied.diagnostic().expect("diag").code(),
"web_fetch_network_denied"
);
let session_permissions = ProcessSessionPermissions::new();
let ask_policy = LivePolicyHandle::for_network(
NetworkAccessPolicy::new(CapabilityPolicy::Ask, true)
.with_session_permissions(session_permissions.view()),
);
let ask_tool = WebFetchTool::new(
WebFetchConfig::default().with_live_network_policy(ask_policy.clone()),
);
let err = ask_tool
.execute(
test_call(json!({"url": "https://Docs.RS/serde"})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect_err("ask policy should require domain approval");
match err {
ToolExecutionError::PermissionRequired(requirement) => {
assert_eq!(
requirement.action(),
&PermissionedAction::NetworkUrl {
tool: WEB_FETCH_TOOL.to_owned(),
url: "https://docs.rs/serde".to_owned(),
host: "docs.rs".to_owned(),
}
);
assert_eq!(
requirement.requested(),
&[RequestedCapability::NetworkDomain("docs.rs".to_owned())]
);
}
other => panic!("expected PermissionRequired, got {other:?}"),
}
session_permissions
.retain_domain_grants(["docs.rs".to_owned()])
.expect("domain grant recorded");
let www_err = ask_tool
.execute(
test_call(json!({"url": "https://www.docs.rs/serde"})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect_err("www.docs.rs must not inherit docs.rs grant");
assert!(matches!(www_err, ToolExecutionError::PermissionRequired(_)));
let allow_policy =
LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Allow, true));
let allow_tool =
WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(allow_policy));
for blocked_url in [
"file:///etc/passwd",
"http://169.254.169.254/latest/meta-data",
"http://10.0.0.1/secret",
] {
let outcome = allow_tool
.execute(
test_call(json!({"url": blocked_url})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect("ssrf returns failed outcome");
assert_eq!(outcome.status(), ToolCallResultStatus::Failed);
assert!(
matches!(
outcome.diagnostic().expect("diag").code(),
"web_fetch_ssrf_blocked" | "web_fetch_invalid_url"
),
"unexpected code for {blocked_url}: {:?}",
outcome.diagnostic()
);
}
let app = Router::new().route("/ping", get(|| async { Html("<h1>pong</h1>") }));
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind loopback");
let addr = listener.local_addr().expect("addr");
let server = tokio::spawn(async move {
axum::serve(listener, app).await.expect("serve");
});
let local_ok = deny_tool
.execute(
test_call(json!({"url": format!("http://127.0.0.1:{}/ping", addr.port())})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect("loopback stays allowed when allow_local=true");
assert_eq!(local_ok.status(), ToolCallResultStatus::Succeeded);
assert!(local_ok.content().as_str().contains("pong"));
let no_local_policy =
LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Allow, false));
let no_local_tool =
WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(no_local_policy));
let local_blocked = no_local_tool
.execute(
test_call(json!({"url": format!("http://127.0.0.1:{}/ping", addr.port())})),
ToolExecutionContext::new(CancellationToken::new()),
)
.await
.expect("loopback denied when allow_local=false");
assert_eq!(local_blocked.status(), ToolCallResultStatus::Failed);
assert_eq!(
local_blocked.diagnostic().expect("diag").code(),
"web_fetch_ssrf_blocked"
);
server.abort();
}
}