Skip to content

The headless browser for AI agents and web scraping

feat(render): ship capture surfaces

SGavrl084789a2d7fd
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 4a4af7c7..76353312 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -74,8 +74,11 @@ jobs:
run: |
"LIBCLANG_PATH=C:\Program Files\LLVM\bin" | Out-File -FilePath $env:GITHUB_ENV -Append
- - name: Build default release binary
- run: cargo build --release --target ${{ matrix.target }}
+ # Rendering is part of the shipped browser. Keep the Cargo feature
+ # opt-in for embedders that only need DOM extraction, but every official
+ # binary must support screenshots, screencasting, and PDF export.
+ - name: Build render-enabled release binary
+ run: cargo build --release --target ${{ matrix.target }} --features render
- name: Stage default release binary
shell: bash
@@ -88,11 +91,11 @@ jobs:
cp "$BIN_DIR/obscura" "$BIN_DIR/obscura-worker" dist/default/
fi
- # Build and package stealth separately so the default download keeps its
- # lower RSS while the advertised wreq/BoringSSL variant cannot silently
- # fall back to a non-stealth binary.
- - name: Build stealth release binary
- run: cargo build --release --target ${{ matrix.target }} --features stealth
+ # Build and package stealth separately so the advertised wreq/BoringSSL
+ # variant cannot silently fall back to a non-stealth transport. It still
+ # includes the same rendering surface as the standard archive.
+ - name: Build render-enabled stealth release binary
+ run: cargo build --release --target ${{ matrix.target }} --features render,stealth
- name: Stage stealth release binary
shell: bash
@@ -116,6 +119,9 @@ jobs:
BIN=dist/$VARIANT/obscura
[ -f "$BIN.exe" ] && BIN="$BIN.exe"
"$BIN" fetch "data:text/html,<title>ok</title>" --eval "1+1"
+ "$BIN" fetch "data:text/html,<style>body{margin:0;background:%23123456}</style>" --screenshot smoke.png
+ test -s smoke.png
+ rm smoke.png
done
- name: Package (Unix)
diff --git a/Cargo.lock b/Cargo.lock
index 67eb0a7d..7decb18a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1976,6 +1976,7 @@ name = "obscura-mcp"
version = "0.1.0"
dependencies = [
"anyhow",
+ "base64",
"obscura-browser",
"obscura-dom",
"obscura-net",
diff --git a/Dockerfile b/Dockerfile
index cbb8ca35..687e88f6 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -17,24 +17,25 @@ COPY crates/obscura-browser/Cargo.toml crates/obscura-browser/Cargo.toml
COPY crates/obscura-cdp/Cargo.toml crates/obscura-cdp/Cargo.toml
COPY crates/obscura-js/Cargo.toml crates/obscura-js/Cargo.toml
COPY crates/obscura-mcp/Cargo.toml crates/obscura-mcp/Cargo.toml
+COPY crates/obscura-render/Cargo.toml crates/obscura-render/Cargo.toml
COPY crates/obscura-cli/Cargo.toml crates/obscura-cli/Cargo.toml
# Create stub src files so cargo can resolve the dependency graph
-RUN for crate in obscura-dom obscura-net obscura-browser obscura-cdp obscura-js obscura-mcp; do \
+RUN for crate in obscura-dom obscura-net obscura-browser obscura-cdp obscura-js obscura-mcp obscura-render; do \
mkdir -p crates/$crate/src && echo "// stub" > crates/$crate/src/lib.rs; \
done && \
mkdir -p crates/obscura-cli/src && \
echo "fn main() {}" > crates/obscura-cli/src/main.rs && \
echo "fn main() {}" > crates/obscura-cli/src/worker.rs
-RUN cargo build --release --bin obscura --bin obscura-worker 2>/dev/null || true
+RUN cargo build --release --features render --bin obscura --bin obscura-worker 2>/dev/null || true
ARG OBSCURA_VERSION
# Copy real sources and build
COPY crates/ crates/
RUN echo "Building Obscura version ${OBSCURA_VERSION:-from Cargo.toml}" && \
- touch crates/*/src/*.rs && cargo build --release --bin obscura --bin obscura-worker
+ touch crates/*/src/*.rs && cargo build --release --features render --bin obscura --bin obscura-worker
# ---
diff --git a/crates/obscura-cli/Cargo.toml b/crates/obscura-cli/Cargo.toml
index 2d24cc8c..5bcd6a4d 100644
--- a/crates/obscura-cli/Cargo.toml
+++ b/crates/obscura-cli/Cargo.toml
@@ -14,7 +14,7 @@ path = "src/worker.rs"
[features]
default = []
stealth = ["obscura-browser/stealth", "obscura-net/stealth", "obscura-mcp/stealth"]
-render = ["obscura-browser/render", "obscura-cdp/render"]
+render = ["obscura-browser/render", "obscura-cdp/render", "obscura-mcp/render"]
[dependencies]
obscura-browser = { workspace = true }
diff --git a/crates/obscura-mcp/Cargo.toml b/crates/obscura-mcp/Cargo.toml
index 2cc7f978..87c3aa9a 100644
--- a/crates/obscura-mcp/Cargo.toml
+++ b/crates/obscura-mcp/Cargo.toml
@@ -6,6 +6,7 @@ edition.workspace = true
[features]
default = []
stealth = ["obscura-browser/stealth", "obscura-net/stealth"]
+render = ["obscura-browser/render", "dep:base64"]
[dependencies]
obscura-browser = { workspace = true }
@@ -17,3 +18,4 @@ serde = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
+base64 = { workspace = true, optional = true }
diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rs
index 4cf09ca8..e45e1a2d 100644
--- a/crates/obscura-mcp/src/lib.rs
+++ b/crates/obscura-mcp/src/lib.rs
@@ -9,6 +9,8 @@ use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
+#[cfg(feature = "render")]
+use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use obscura_browser::{BrowserContext, Page};
use obscura_dom::NodeId;
use serde::{Deserialize, Serialize};
@@ -226,8 +228,8 @@ fn handle_initialize(id: Value, params: &Value) -> RpcResponse {
}
fn handle_tools_list(id: Value) -> RpcResponse {
- RpcResponse::ok(id, json!({
- "tools": [
+ #[allow(unused_mut)]
+ let mut tools = json!([
{
"name": "browser_navigate",
"description": "Navigate to a URL and wait for the page to load",
@@ -249,7 +251,10 @@ fn handle_tools_list(id: Value) -> RpcResponse {
"description": "Get the current page content as text (title, URL, and readable body text)",
"inputSchema": {
"type": "object",
- "properties": {}
+ "properties": {
+ "max_chars": { "type": "number", "minimum": 0, "description": "Truncate readable body text to this many characters (default: 4000)" }
+ },
+ "additionalProperties": false
}
},
{
@@ -598,8 +603,46 @@ fn handle_tools_list(id: Value) -> RpcResponse {
"required": ["state"]
}
}
- ]
- }))
+ ]).as_array().cloned().expect("MCP tool list must be an array");
+
+ #[cfg(feature = "render")]
+ {
+ tools.extend([
+ json!({
+ "name": "browser_screenshot",
+ "description": "Capture the current rendered viewport as a PNG image. Width and height default to the page's current CSS viewport.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "width": { "type": "number", "exclusiveMinimum": 0, "maximum": 32768, "description": "Optional CSS-pixel capture width" },
+ "height": { "type": "number", "exclusiveMinimum": 0, "maximum": 32768, "description": "Optional CSS-pixel capture height" }
+ },
+ "additionalProperties": false
+ }
+ }),
+ json!({
+ "name": "browser_pdf",
+ "description": "Export the current rendered document as a paginated raster PDF using print media and bounded PDF defaults.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "landscape": { "type": "boolean" },
+ "print_background": { "type": "boolean" },
+ "scale": { "type": "number", "minimum": 0.1, "maximum": 2.0 },
+ "paper_width": { "type": "number", "exclusiveMinimum": 0, "maximum": 200, "description": "Paper width in inches" },
+ "paper_height": { "type": "number", "exclusiveMinimum": 0, "maximum": 200, "description": "Paper height in inches" },
+ "margin_top": { "type": "number", "minimum": 0, "description": "Top margin in inches" },
+ "margin_bottom": { "type": "number", "minimum": 0, "description": "Bottom margin in inches" },
+ "margin_left": { "type": "number", "minimum": 0, "description": "Left margin in inches" },
+ "margin_right": { "type": "number", "minimum": 0, "description": "Right margin in inches" }
+ },
+ "additionalProperties": false
+ }
+ }),
+ ]);
+ }
+
+ RpcResponse::ok(id, json!({ "tools": tools }))
}
async fn handle_tool_call(id: Value, params: &Value, state: &mut BrowserState) -> RpcResponse {
@@ -609,6 +652,24 @@ async fn handle_tool_call(id: Value, params: &Value, state: &mut BrowserState) -
};
let args = params.get("arguments").unwrap_or(&Value::Null);
+ #[cfg(feature = "render")]
+ {
+ let media_result = match name {
+ "browser_screenshot" => Some(tool_screenshot(args, state).await),
+ "browser_pdf" => Some(tool_pdf(args, state).await),
+ _ => None,
+ };
+ if let Some(result) = media_result {
+ return match result {
+ Ok(content) => RpcResponse::ok(id, json!({ "content": [content] })),
+ Err(error) => RpcResponse::ok(id, json!({
+ "content": [{ "type": "text", "text": format!("Error: {error}") }],
+ "isError": true
+ })),
+ };
+ }
+ }
+
let result = match name {
"browser_navigate" => tool_navigate(args, state).await,
"browser_snapshot" => tool_snapshot(args, state),
@@ -661,6 +722,104 @@ async fn handle_tool_call(id: Value, params: &Value, state: &mut BrowserState) -
}
}
+#[cfg(feature = "render")]
+fn validate_tool_options(args: &Value, allowed: &[&str]) -> Result<(), String> {
+ if args.is_null() {
+ return Ok(());
+ }
+ let object = args.as_object().ok_or("tool arguments must be an object")?;
+ if let Some(name) = object.keys().find(|name| !allowed.contains(&name.as_str())) {
+ return Err(format!("unsupported option '{name}'"));
+ }
+ Ok(())
+}
+
+#[cfg(feature = "render")]
+fn optional_number(args: &Value, name: &str) -> Result<Option<f32>, String> {
+ let Some(value) = args.get(name) else {
+ return Ok(None);
+ };
+ let value = value.as_f64().ok_or_else(|| format!("'{name}' must be a number"))?;
+ if !value.is_finite() || value < f64::from(f32::MIN) || value > f64::from(f32::MAX) {
+ return Err(format!("'{name}' must be a finite number"));
+ }
+ Ok(Some(value as f32))
+}
+
+#[cfg(feature = "render")]
+fn optional_bool(args: &Value, name: &str) -> Result<Option<bool>, String> {
+ let Some(value) = args.get(name) else {
+ return Ok(None);
+ };
+ value.as_bool().map(Some).ok_or_else(|| format!("'{name}' must be a boolean"))
+}
+
+#[cfg(feature = "render")]
+fn validate_screenshot_viewport(viewport: (f32, f32)) -> Result<(), String> {
+ const MAX_DIMENSION: f32 = 32_768.0;
+ const MAX_PIXELS: f64 = (16 * 1024 * 1024) as f64;
+ let (width, height) = viewport;
+ if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0
+ || width > MAX_DIMENSION || height > MAX_DIMENSION
+ {
+ return Err("screenshot dimensions must be finite, positive, and at most 32768 CSS pixels".into());
+ }
+ if f64::from(width.ceil()) * f64::from(height.ceil()) > MAX_PIXELS {
+ return Err("screenshot dimensions exceed the 16-megapixel capture limit".into());
+ }
+ Ok(())
+}
+
+#[cfg(feature = "render")]
+async fn tool_screenshot(args: &Value, state: &mut BrowserState) -> Result<Value, String> {
+ validate_tool_options(args, &["width", "height"])?;
+ let current = state.page_mut().viewport;
+ let viewport = (
+ optional_number(args, "width")?.unwrap_or(current.0),
+ optional_number(args, "height")?.unwrap_or(current.1),
+ );
+ validate_screenshot_viewport(viewport)?;
+
+ let page = state.page_mut();
+ let _ = page.prepare_screenshot_resources(1_000).await;
+ let png = page.screenshot(viewport).ok_or("the current page has no renderable viewport")?;
+ Ok(json!({
+ "type": "image",
+ "data": BASE64.encode(png),
+ "mimeType": "image/png"
+ }))
+}
+
+#[cfg(feature = "render")]
+async fn tool_pdf(args: &Value, state: &mut BrowserState) -> Result<Value, String> {
+ validate_tool_options(args, &[
+ "landscape", "print_background", "scale", "paper_width", "paper_height",
+ "margin_top", "margin_bottom", "margin_left", "margin_right",
+ ])?;
+ let mut options = obscura_browser::RasterPdfOptions::default();
+ if let Some(value) = optional_bool(args, "landscape")? { options.landscape = value; }
+ if let Some(value) = optional_bool(args, "print_background")? { options.print_background = value; }
+ if let Some(value) = optional_number(args, "scale")? { options.scale = value; }
+ if let Some(value) = optional_number(args, "paper_width")? { options.paper_width_in = value; }
+ if let Some(value) = optional_number(args, "paper_height")? { options.paper_height_in = value; }
+ if let Some(value) = optional_number(args, "margin_top")? { options.margin_top_in = value; }
+ if let Some(value) = optional_number(args, "margin_bottom")? { options.margin_bottom_in = value; }
+ if let Some(value) = optional_number(args, "margin_left")? { options.margin_left_in = value; }
+ if let Some(value) = optional_number(args, "margin_right")? { options.margin_right_in = value; }
+
+ let page = state.page_mut();
+ let _ = page.prepare_screenshot_resources(1_000).await;
+ let pdf = page.raster_pdf(options).map_err(|error| error.to_string())?;
+ Ok(json!({
+ "type": "resource",
+ "resource": {
+ "uri": "obscura://capture/current-page.pdf",
+ "mimeType": "application/pdf",
+ "blob": BASE64.encode(pdf)
+ }
+ }))
+}
+
/// Resolve a tool call's element target from either `ref` (preferred) or
/// `selector` (fallback). Agents that called `browser_snapshot` /
/// `browser_interactive_elements` get a ref table they can refer to;
@@ -1777,6 +1936,94 @@ fn tool_set_storage_state(args: &Value, state: &mut BrowserState) -> Result<Stri
mod tests {
use super::*;
+ fn listed_tools() -> Vec<Value> {
+ handle_tools_list(json!(1)).result.expect("tools/list result")
+ .get("tools").and_then(Value::as_array).cloned().expect("tools array")
+ }
+
+ #[test]
+ fn tool_schemas_expose_snapshot_limit_without_nested_properties() {
+ let tools = listed_tools();
+ let snapshot = tools.iter().find(|tool| tool["name"] == "browser_snapshot")
+ .expect("browser_snapshot tool");
+ assert_eq!(snapshot["inputSchema"]["properties"]["max_chars"]["type"], "number");
+ for tool in tools {
+ assert!(
+ tool["inputSchema"]["properties"].get("properties").is_none(),
+ "{} has a nested duplicate properties object", tool["name"]
+ );
+ }
+ }
+
+ #[cfg(not(feature = "render"))]
+ #[test]
+ fn render_tools_are_not_advertised_without_render_feature() {
+ let tools = listed_tools();
+ assert!(tools.iter().all(|tool| {
+ tool["name"] != "browser_screenshot" && tool["name"] != "browser_pdf"
+ }));
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn render_tools_are_advertised_with_flat_schemas() {
+ let tools = listed_tools();
+ for name in ["browser_screenshot", "browser_pdf"] {
+ let tool = tools.iter().find(|tool| tool["name"] == name)
+ .unwrap_or_else(|| panic!("missing {name}"));
+ assert_eq!(tool["inputSchema"]["type"], "object");
+ assert_eq!(tool["inputSchema"]["additionalProperties"], false);
+ assert!(tool["inputSchema"]["properties"].is_object());
+ assert!(tool["inputSchema"]["properties"].get("properties").is_none());
+ }
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn render_tool_calls_return_mcp_binary_content_and_reject_bad_options() {
+ let mut state = BrowserState::new(None, None, false);
+ state.page_mut().navigate(
+ "data:text/html,<html style='margin:0'><body style='margin:0;background:red'><div style='width:64px;height:48px'></div></body></html>",
+ ).await.expect("render test page should navigate");
+ state.page_mut().set_viewport((64.0, 48.0));
+
+ let screenshot = handle_tool_call(
+ json!(1), &json!({ "name": "browser_screenshot", "arguments": {} }), &mut state,
+ ).await.result.expect("screenshot response");
+ let image = &screenshot["content"][0];
+ assert_eq!(image["type"], "image");
+ assert_eq!(image["mimeType"], "image/png");
+ let png = BASE64.decode(image["data"].as_str().expect("PNG base64"))
+ .expect("valid PNG base64");
+ assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
+
+ let pdf = handle_tool_call(
+ json!(2),
+ &json!({ "name": "browser_pdf", "arguments": { "print_background": true } }),
+ &mut state,
+ ).await.result.expect("PDF response");
+ let resource = &pdf["content"][0];
+ assert_eq!(resource["type"], "resource");
+ assert_eq!(resource["resource"]["mimeType"], "application/pdf");
+ let bytes = BASE64.decode(resource["resource"]["blob"].as_str().expect("PDF base64"))
+ .expect("valid PDF base64");
+ assert!(bytes.starts_with(b"%PDF-"));
+
+ let invalid_screenshot = handle_tool_call(
+ json!(3),
+ &json!({ "name": "browser_screenshot", "arguments": { "width": 0 } }),
+ &mut state,
+ ).await.result.expect("invalid screenshot response");
+ assert_eq!(invalid_screenshot["isError"], true);
+
+ let invalid_pdf = handle_tool_call(
+ json!(4),
+ &json!({ "name": "browser_pdf", "arguments": { "scale": 3 } }),
+ &mut state,
+ ).await.result.expect("invalid PDF response");
+ assert_eq!(invalid_pdf["isError"], true);
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn fill_tools_notify_controlled_input_tracker() {
let mut state = BrowserState::new(None, None, false);