use crate::session::BrowserSession;
use adk_core::egress::{ContextUrls, UrlSources, is_non_public};
use adk_core::{Result, Tool, ToolContext};
use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;
pub const URL_NOT_IN_CONTEXT_CODE: &str = "browser.url_not_in_context";
pub const DEFAULT_ALLOWED_SCHEMES: &[&str] = &["http", "https"];
pub(crate) fn default_allowed_schemes() -> Vec<String> {
DEFAULT_ALLOWED_SCHEMES.iter().map(|scheme| (*scheme).to_string()).collect()
}
const PRIVATE_HOST_NAMES: &[&str] = &["localhost", "metadata.google.internal"];
const RESOLVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
#[derive(Debug, Clone)]
pub(crate) struct UrlPolicy {
pub(crate) allowed_schemes: Vec<String>,
pub(crate) allow_private_network: bool,
pub(crate) allow_unresolved_hosts: bool,
pub(crate) url_sources: Option<UrlSources>,
}
impl Default for UrlPolicy {
fn default() -> Self {
Self {
allowed_schemes: default_allowed_schemes(),
allow_private_network: false,
allow_unresolved_hosts: false,
url_sources: None,
}
}
}
enum HostRefusal {
Private,
Unresolved(String),
}
impl UrlPolicy {
pub(crate) fn check_in_context(&self, url: &str, ctx: &dyn ToolContext) -> Result<()> {
let Some(sources) = &self.url_sources else { return Ok(()) };
if ContextUrls::from_tool_context(ctx, sources).contains(url) {
return Ok(());
}
Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Tool,
adk_core::ErrorCategory::Forbidden,
URL_NOT_IN_CONTEXT_CODE,
"The URL did not appear earlier in the conversation, so the browser does not open \
it: only a URL a user message or a tool result already holds is opened, exactly as \
written there (query string included). Open a URL exactly as it appeared, or ask \
the user for the URL.",
))
}
pub(crate) async fn check(&self, url: &str) -> Result<()> {
let parsed = url::Url::parse(url)
.map_err(|e| adk_core::AdkError::tool(format!("Invalid URL '{url}': {e}")))?;
let scheme = parsed.scheme();
if !self.allowed_schemes.iter().any(|candidate| candidate.eq_ignore_ascii_case(scheme)) {
return Err(adk_core::AdkError::tool(format!(
"URL scheme '{scheme}' is not allowed; allowed schemes: {}. Configure \
BrowserToolset::with_allowed_schemes to permit others.",
self.allowed_schemes.join(", ")
)));
}
match self.host_refusal(&parsed).await {
None => Ok(()),
Some(refusal) => Err(adk_core::AdkError::tool(refusal_message(url, &refusal))),
}
}
pub(crate) async fn check_landing(&self, browser: &BrowserSession) -> Result<String> {
let current = browser.current_url().await?;
if self.allow_private_network {
return Ok(current);
}
let refusal = match url::Url::parse(¤t) {
Ok(parsed) => match self.host_refusal(&parsed).await {
None => return Ok(current),
Some(refusal) => refusal_message(¤t, &refusal),
},
Err(e) => format!("The browser reported a URL that does not parse: {e}."),
};
let cleared = match browser.navigate("about:blank").await {
Ok(()) => "The page was replaced with about:blank.".to_string(),
Err(e) => format!("Replacing the page with about:blank failed: {e}"),
};
Err(adk_core::AdkError::tool(format!(
"The browser ended on '{current}' after the navigation. {refusal} {cleared}"
)))
}
async fn host_refusal(&self, parsed: &url::Url) -> Option<HostRefusal> {
if self.allow_private_network {
return None;
}
let private = match parsed.host()? {
url::Host::Ipv4(ip) => is_non_public(ip.into()),
url::Host::Ipv6(ip) => is_non_public(ip.into()),
url::Host::Domain(domain) => {
let domain = domain.trim_end_matches('.').to_ascii_lowercase();
if PRIVATE_HOST_NAMES.contains(&domain.as_str()) || domain.ends_with(".localhost") {
true
} else {
match resolve(&domain, parsed.port_or_known_default()).await {
Some(addresses) => addresses.iter().any(|address| is_non_public(*address)),
None if self.allow_unresolved_hosts => false,
None => return Some(HostRefusal::Unresolved(domain)),
}
}
}
};
private.then_some(HostRefusal::Private)
}
}
fn refusal_message(url: &str, refusal: &HostRefusal) -> String {
match refusal {
HostRefusal::Private => format!(
"URL '{url}' points at a private network address (loopback, private, \
link-local, or cloud metadata) and is not allowed. Configure \
BrowserToolset::with_private_network_access to permit it."
),
HostRefusal::Unresolved(host) => format!(
"URL '{url}' was refused: its host '{host}' does not resolve on the agent host, \
so it cannot be checked against the private network policy. Configure \
BrowserToolset::with_unresolved_hosts to let the browser resolve it."
),
}
}
async fn resolve(domain: &str, port: Option<u16>) -> Option<Vec<std::net::IpAddr>> {
let lookup = tokio::net::lookup_host((domain, port.unwrap_or(80)));
match tokio::time::timeout(RESOLVE_TIMEOUT, lookup).await {
Ok(Ok(addresses)) => {
let addresses: Vec<_> = addresses.map(|address| address.ip()).collect();
(!addresses.is_empty()).then_some(addresses)
}
Ok(Err(_)) | Err(_) => None,
}
}
pub struct NavigateTool {
browser: Arc<BrowserSession>,
policy: UrlPolicy,
}
impl NavigateTool {
pub fn new(browser: Arc<BrowserSession>) -> Self {
Self { browser, policy: UrlPolicy::default() }
}
#[must_use]
pub fn with_private_network_access(mut self, enabled: bool) -> Self {
self.policy.allow_private_network = enabled;
self
}
#[must_use]
pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
self.policy.allow_unresolved_hosts = enabled;
self
}
#[must_use]
pub fn with_allowed_schemes<I, S>(mut self, schemes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.policy.allowed_schemes = schemes.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_url_provenance(mut self, sources: Option<UrlSources>) -> Self {
self.policy.url_sources = sources;
self
}
}
#[async_trait]
impl Tool for NavigateTool {
fn name(&self) -> &str {
"browser_navigate"
}
fn description(&self) -> &str {
"Navigate the browser to a specified URL. Use this to open web pages \
(http and https URLs by default)."
}
fn parameters_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL to navigate to (e.g., 'https://example.com')"
}
},
"required": ["url"]
}))
}
fn response_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {
"success": { "type": "boolean" },
"url": { "type": "string" },
"title": { "type": "string" }
}
}))
}
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
let url = args
.get("url")
.and_then(|v| v.as_str())
.ok_or_else(|| adk_core::AdkError::tool("Missing 'url' parameter"))?;
self.policy.check_in_context(url, ctx.as_ref())?;
self.policy.check(url).await?;
self.browser.navigate(url).await?;
let current_url = self.policy.check_landing(&self.browser).await?;
let title = self.browser.title().await.unwrap_or_default();
match self.browser.page_context().await {
Ok(page) => Ok(json!({
"success": true,
"url": current_url,
"title": title,
"page": page
})),
Err(e) => Ok(json!({
"success": true,
"url": current_url,
"title": title,
"page_context_error": e.to_string()
})),
}
}
}
pub struct BackTool {
browser: Arc<BrowserSession>,
policy: UrlPolicy,
}
impl BackTool {
pub fn new(browser: Arc<BrowserSession>) -> Self {
Self { browser, policy: UrlPolicy::default() }
}
#[must_use]
pub fn with_private_network_access(mut self, enabled: bool) -> Self {
self.policy.allow_private_network = enabled;
self
}
#[must_use]
pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
self.policy.allow_unresolved_hosts = enabled;
self
}
}
#[async_trait]
impl Tool for BackTool {
fn name(&self) -> &str {
"browser_back"
}
fn description(&self) -> &str {
"Go back to the previous page in browser history."
}
fn parameters_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {}
}))
}
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
self.browser.back().await?;
let url = self.policy.check_landing(&self.browser).await?;
let title = self.browser.title().await.unwrap_or_default();
match self.browser.page_context().await {
Ok(page) => Ok(json!({
"success": true,
"url": url,
"title": title,
"page": page
})),
Err(e) => Ok(json!({
"success": true,
"url": url,
"title": title,
"page_context_error": e.to_string()
})),
}
}
}
pub struct ForwardTool {
browser: Arc<BrowserSession>,
policy: UrlPolicy,
}
impl ForwardTool {
pub fn new(browser: Arc<BrowserSession>) -> Self {
Self { browser, policy: UrlPolicy::default() }
}
#[must_use]
pub fn with_private_network_access(mut self, enabled: bool) -> Self {
self.policy.allow_private_network = enabled;
self
}
#[must_use]
pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
self.policy.allow_unresolved_hosts = enabled;
self
}
}
#[async_trait]
impl Tool for ForwardTool {
fn name(&self) -> &str {
"browser_forward"
}
fn description(&self) -> &str {
"Go forward to the next page in browser history."
}
fn parameters_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {}
}))
}
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
self.browser.forward().await?;
let url = self.policy.check_landing(&self.browser).await?;
let title = self.browser.title().await.unwrap_or_default();
match self.browser.page_context().await {
Ok(page) => Ok(json!({
"success": true,
"url": url,
"title": title,
"page": page
})),
Err(e) => Ok(json!({
"success": true,
"url": url,
"title": title,
"page_context_error": e.to_string()
})),
}
}
}
pub struct RefreshTool {
browser: Arc<BrowserSession>,
policy: UrlPolicy,
}
impl RefreshTool {
pub fn new(browser: Arc<BrowserSession>) -> Self {
Self { browser, policy: UrlPolicy::default() }
}
#[must_use]
pub fn with_private_network_access(mut self, enabled: bool) -> Self {
self.policy.allow_private_network = enabled;
self
}
#[must_use]
pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
self.policy.allow_unresolved_hosts = enabled;
self
}
}
#[async_trait]
impl Tool for RefreshTool {
fn name(&self) -> &str {
"browser_refresh"
}
fn description(&self) -> &str {
"Refresh the current page."
}
fn parameters_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {}
}))
}
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
self.browser.refresh().await?;
let url = self.policy.check_landing(&self.browser).await?;
let title = self.browser.title().await.unwrap_or_default();
match self.browser.page_context().await {
Ok(page) => Ok(json!({
"success": true,
"url": url,
"title": title,
"page": page
})),
Err(e) => Ok(json!({
"success": true,
"url": url,
"title": title,
"page_context_error": e.to_string()
})),
}
}
}