When an agent needs something from the web, the first instinct is often to give it a headless browser. For most tasks that is far more than it needs. Reading an API reference, a changelog, a package’s README or a status JSON is one HTTP GET and some text extraction. A browser adds a JavaScript engine, cookies, a large dependency tree and a lot of behaviour you did not ask for, all of it driven by a model that may have read a hostile page a minute ago.
This post builds the smaller thing: a browser-free fetch tool that runs inside a sandbox, refuses any host the current task did not name, and returns plain text with clear limits. It is about the tool itself. For choosing the hosts on an allowlist and the DNS and CDN traps, see designing an egress allowlist.
What “browser-free” buys you
A fetch tool built on an HTTP client and a parser has a small, readable surface:
- No script execution. The page’s JavaScript never runs. A page cannot fingerprint, redirect through script, or open more connections on its own.
- One request per call, plus robots.txt and redirects you can see. Every network hop is a decision in your code.
- Predictable output. You decide the size cap, the content types and the text extraction, so the model gets the same shape every time.
The cost is that pages rendered entirely by client-side JavaScript come back nearly empty. That is a fair trade for docs, references, feeds and APIs, which are most of what agents read. When a task really needs a rendered page, treat it as a separate, more tightly reviewed tool.
Two allowlists, two jobs
There are two places to restrict where a fetch can go, and they do different things.
- The network allowlist is enforced outside the code: by the sandbox’s network layer, a proxy or a firewall. Code inside the sandbox cannot widen it. It is the ceiling for everything that runs there, including anything the agent writes and runs itself.
- The task allowlist is enforced by the fetch tool. It is the short list of hosts this particular task needs: “fix the failing test using the docs for this library” needs that library’s docs host and nothing else.
The task list is per task because tasks differ, and a list that covers every task is a list that is too wide for each of them. If a prompt injection in a README tells the agent to “fetch https://attacker.example/?d=…”, the task allowlist refuses it in the tool, with a clear message the model can read, before the network layer even sees the request. The network allowlist is the backstop for when the agent bypasses the tool, for example by writing its own curl command.
Keep the order of trust straight: the task allowlist is advisory to any code that does not use the tool, so the network ceiling still has to be tight on its own.
The tool
Here is a complete fetch tool in Python using only the standard library. It reads a JSON task on standard input, such as {"url": "...", "allow": ["docs.python.org"]}, and prints one JSON result.
import json, sys, urllib.parse, urllib.request, urllib.robotparser
from html.parser import HTMLParser
MAX_BYTES = 2_000_000 # stop reading after 2 MB
MAX_TEXT = 20_000 # characters handed back to the model
TEXT_TYPES = ("text/html", "text/plain", "application/json")
UA = "example-agent-fetch/1.0 (+https://example.com/bot)"
class Refused(Exception):
pass
def host_allowed(url, allow):
p = urllib.parse.urlsplit(url)
if p.scheme != "https":
raise Refused(f"scheme {p.scheme!r} not allowed")
host = (p.hostname or "").lower()
if not any(host == h or host.endswith("." + h) for h in allow):
raise Refused(f"host {host!r} is not on this task's allowlist")
return p
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None # surface 3xx to the caller so each hop is checked
opener = urllib.request.build_opener(NoRedirect)
def robots_ok(p):
rp = urllib.robotparser.RobotFileParser()
rp.set_url(f"{p.scheme}://{p.netloc}/robots.txt")
try:
rp.read()
except Exception:
return True # no readable robots.txt: treated as allowed
return rp.can_fetch(UA, p.geturl())
class Text(HTMLParser):
SKIP = {"script", "style", "noscript", "svg"}
def __init__(self):
super().__init__(); self.out = []; self.skip = 0
def handle_starttag(self, tag, attrs):
if tag in self.SKIP: self.skip += 1
def handle_endtag(self, tag):
if tag in self.SKIP and self.skip: self.skip -= 1
def handle_data(self, data):
if not self.skip and data.strip(): self.out.append(data.strip())
def fetch(url, allow, max_hops=3):
for _ in range(max_hops + 1):
p = host_allowed(url, allow)
if not robots_ok(p):
raise Refused("disallowed by robots.txt")
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": ", ".join(TEXT_TYPES)})
try:
resp = opener.open(req, timeout=20)
except urllib.error.HTTPError as e:
if e.code in (301, 302, 303, 307, 308) and e.headers.get("Location"):
url = urllib.parse.urljoin(url, e.headers["Location"])
continue
return {"url": url, "status": e.code, "error": "http_error"}
except urllib.error.URLError as e:
return {"url": url, "error": "network", "reason": str(e.reason)}
ctype = resp.headers.get_content_type()
if ctype not in TEXT_TYPES:
return {"url": url, "status": resp.status, "error": f"content type {ctype} not fetched"}
raw = resp.read(MAX_BYTES + 1)
truncated = len(raw) > MAX_BYTES
body = raw[:MAX_BYTES].decode(resp.headers.get_content_charset() or "utf-8", "replace")
if ctype == "text/html":
t = Text(); t.feed(body); body = "\n".join(t.out)
return {"url": url, "status": resp.status, "content_type": ctype,
"truncated": truncated or len(body) > MAX_TEXT, "text": body[:MAX_TEXT]}
raise Refused("too many redirects")
if __name__ == "__main__":
task = json.load(sys.stdin) # {"url": "...", "allow": ["docs.python.org"]}
try:
print(json.dumps(fetch(task["url"], [h.lower() for h in task["allow"]])))
except Refused as e:
print(json.dumps({"url": task["url"], "error": "refused", "reason": str(e)}))
Why each check is there
HTTPS only. Plain HTTP can be altered in transit, and there is rarely a reason for an agent to read it.
Host match on every hop. The check compares the hostname exactly or as a subdomain of an allowed host (docs.python.org allows docs.python.org, not docs.python.org.evil.example). Redirects are not followed automatically; each Location goes back through the same check. Open redirects on allowed hosts are a common way out of an allowlist, and this closes that path.
robots.txt. urllib.robotparser reads the site’s rules (RFC 9309) and the tool honours them. An agent is an automated client; behave like one, and send a User-Agent that says what you are and where to read about it.
Content types. Only text, HTML and JSON come back. A binary file or an archive is refused rather than decoded into noise for the model.
Byte and text caps. The tool stops reading after a fixed number of bytes and hands back at most a fixed number of characters, with a truncated flag so the model knows it did not see everything. Our post on truncating tool output for LLMs goes deeper on choosing caps.
Errors as data. A refused host, a 404 or a network failure all come back as JSON with a reason. The model can act on “host is not on this task’s allowlist” by asking for help, instead of retrying blindly.
Treat what comes back as untrusted input
The page text is the most dangerous part of the result, because it is written by someone else and read by your model. A few habits help:
- Label it. Wrap fetched text in a clearly marked block in the prompt and tell the model it is data from the web, not instructions.
- Do not let fetched text widen the allowlist. A link in a page is not a reason to fetch it. Only the task definition, set by your code or a person, adds hosts.
- Keep secrets out of the sandbox that fetches. A fetch sandbox needs no credentials. If it has none, a page that talks the model into printing its environment gets nothing worth having.
Prompt injection to code execution walks through how text in a page turns into an action, and which layer stops what.
Wiring it into a sandbox
The tool runs inside a sandbox, so even a bug in the parser or a malicious response is contained there. With the TypeScript SDK, write the file once and run it per call with the task on standard input:
import { readFileSync } from 'node:fs';
import { Sandscale } from '@sandscale/sdk';
const sandscale = new Sandscale({ apiKey: process.env.SANDSCALE_API_KEY });
const TOOL = readFileSync('fetch_tool.py', 'utf8');
export async function fetchForTask(url: string, allow: string[]) {
const box = await sandscale.sandboxes.create({
template: 'builtin:python',
timeoutSeconds: 600,
labels: { tool: 'fetch' },
});
const where = { region: box.region };
try {
await sandscale.sandboxes.writeFile(box.id, '/workspace/fetch_tool.py', TOOL, where);
const run = await sandscale.sandboxes.run(box.id, ['python3', 'fetch_tool.py'], {
...where,
stdin: JSON.stringify({ url, allow }),
timeoutSeconds: 60,
});
if (run.exitCode !== 0) return { url, error: 'tool_failed', stderr: run.stderr.slice(-2000) };
return JSON.parse(run.stdout);
} finally {
await sandscale.sandboxes.stop(box.id, where);
}
}
The allow list comes from your task definition, never from the model’s arguments. If the model may pick the URL, it may not pick the hosts.
How the network side works on Sandscale
On Sandscale each sandbox is a Firecracker microVM, and network access follows your plan and your organization’s policy: a sandbox can reach only what your organization’s egress allowlist allows (sandboxes). That organization list is the ceiling described above. Keep it to the hosts your fetch tasks really use, and let the tool narrow it to the few each task needs. Start the fetch sandbox without vaultEnv, so it carries no Vault values at all.