webfetch

package
v0.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

webfetch

A dependency-light Go port of the reference Python mcp-server-fetch tool.

It fetches a URL, extracts the main content as Markdown (or returns raw HTML), and returns text ready to hand to an LLM — all in-process, with no Node subprocess and no sidecar container.

out, err := webfetch.Fetch(ctx, "https://example.com/article", webfetch.Options{
    MaxLength:  5000, // default when 0
    StartIndex: 0,
    Raw:        false,
})

What's different from upstream mcp-server-fetch

Same tool contract — identical fetch schema, the Contents of <url>: wrapper, and the truncation / error strings — but:

  • In-process, no sidecar. Runs directly inside your Go process: no Node subprocess, no Python runtime, no separate container to deploy or network-isolate.
  • Strict SSRF guard. Reaches only globally-routable public IPs, enforced after DNS resolution in the dialer. Upstream explicitly warns it can reach local/internal addresses; here it cannot. → SSRF protection
  • PDF hand-off (opt-in PDFHandler). Upstream returns PDFs as unusable raw bytes; webfetch can hand the bytes to your own extractor and return its text. → Extension: PDFHandler
  • Content metadata (opt-in IncludeMetadata). Optional title/author/date/site/language frontmatter — not offered upstream. → Extension: IncludeMetadata
  • Full-page & selector escape hatch (opt-in FullPage / Selector / ExcludeSelectors). Steer or bypass Readability when it over-strips — upstream is main-content-or-raw only. → Extension: escape hatch
  • Pure-Go extraction pipeline. go-readability + html-to-markdown in place of upstream's Node readabilipy + markdownify; output is byte-identical on typical pages. → Fidelity
  • Response body cap (MaxBodyBytes, default 10 MiB). Upstream buffers bodies of any size; webfetch fails a fetch whose body is over the cap so a model-chosen URL cannot exhaust memory. → Body cap
  • No proxy support. Upstream's --proxy-url is intentionally unsupported: a proxy would move egress outside the guarded dialer, which is exactly where the SSRF check lives.

The opt-in extensions default to off, so unless you enable them the output stays byte-identical to upstream. The body cap is the one default that is not upstream's, and it only changes the outcome for bodies larger than the cap.

Tool

The module exposes a single tool, equivalent to upstream mcp-server-fetch:

fetch — Fetches a URL from the internet and extracts its contents as markdown.

Parameter Type Required Default Description
url string yes — URL to fetch
max_length integer no 5000 Maximum number of characters to return
start_index integer no 0 Start content from this character index
raw boolean no false Get raw content without markdown conversion

(webfetch.Fetch maps these to the Options fields MaxLength, StartIndex, and Raw.)

Extension: IncludeMetadata (off by default)

With Options.IncludeMetadata: true, the extracted Markdown is prefixed with a small YAML frontmatter block built from metadata Readability already parses — title, author, published, site, language (non-empty fields only):

---
title: "The Article Title"
author: "Jane Doe"
published: "2024-01-02T15:04:05Z"
site: "Example Blog"
language: "en"
---

It applies only to the HTML-simplification path (not Raw, not non-HTML content), and the frontmatter counts as part of the returned content, so StartIndex / MaxLength page over it too. Left false (the default), output is byte-identical to upstream — see Fidelity.

Extension: PDFHandler (off by default)

Upstream returns PDF responses as raw bytes behind a "cannot be simplified" note, which is unusable as LLM context. webfetch does not parse PDFs itself; set Options.PDFHandler and a PDF response (detected by the %PDF- magic bytes, whatever its Content-Type) is handed to it as bytes, downloaded through the same SSRF guard. The text it returns is the content, paged by StartIndex / MaxLength like any other:

// Illustrative: extractor stands for your own client, e.g. for a Tika sidecar.
out, err := webfetch.Fetch(ctx, url, webfetch.Options{
    PDFHandler: func(ctx context.Context, body []byte) (string, error) {
        ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
        defer cancel()
        return extractor.Extract(ctx, bytes.NewReader(body))
    },
})

The bytes are untrusted: run the parser where a malicious PDF cannot take your process down (e.g. a Tika sidecar). The handler must bound its own run time; webfetch's 30 s timeout covers only the download. With a handler set, PDF bodies use their own cap, MaxPDFBytes (default webfetch.DefaultMaxPDFBytes, 50 MiB; negative disables it), independent of MaxBodyBytes. A handler error or panic, or empty text (a scan without OCR), returns a Failed to extract PDF error, so a caller's fallback can take over. Raw takes precedence. Nil (the default) keeps the upstream raw-bytes behaviour.

Extension: full-page & selector escape hatch (off by default)

When Readability over-strips (docs pages, tables, sidebars you actually want), three opt-in Options let you bypass or steer it:

  • FullPage: true — convert the entire page to Markdown, skipping the Readability main-content extraction.
  • Selector: "<css>" — convert only the element(s) matching a CSS selector (takes precedence over FullPage). No match yields the content <error>No content matched the selector.</error> (with a nil error).
  • ExcludeSelectors: []string{"<css>", …} — remove matching element(s) before conversion. Unlike the other two it composes with every mode, including the default Readability path (e.g. strip a cookie banner, then simplify).

Raw still takes precedence over all three, and IncludeMetadata is not applied on the FullPage / Selector paths. Relative links are resolved against the final URL (after redirects), keeping the page's scheme and directory, as on the Readability path. Text is normalized as on the Readability path (NFC, soft hyphens removed) and selectors with it; text the page writes as a reference (&shy;, &#x301;) stays as written. A blank (whitespace only once normalized) Selector or ExcludeSelectors entry counts as unset; others go to the CSS parser as given. On an HTML page (where selectors apply) one it rejects (any member of a group) returns, with a nil error, only <error>Unsupported or invalid selector "<sel>": <reason>.</error> or <error>Unsupported or invalid exclude selector "<sel>": <reason>.</error>, no page content (<sel> and <reason> with control characters as spaces, < > as ‹ ›, cut to 200 runes). With all of them unset (the default), output is byte-identical to upstream.

Body cap: MaxBodyBytes (10 MiB by default)

Options.MaxBodyBytes caps the size of the response body. A body larger than the cap fails the fetch with a Failed to fetch <url>: response body exceeds N bytes error before any decoding, so a model-chosen (or prompt-injected) URL to a huge file cannot exhaust memory. 0 (the default) applies webfetch.DefaultMaxBodyBytes (10 MiB); a negative value disables the cap, which is upstream's unbounded behaviour. This is the only default that differs from upstream, and it only matters for bodies over the cap: anything smaller is processed identically.

Fidelity

The observable contract of the upstream tool is reproduced closely: the autonomous User-Agent, the HTML/raw content-type heuristic, the Contents of <url>: wrapper, and the truncation / error strings.

Content extraction is the one place byte-for-byte parity is impossible: upstream runs Mozilla Readability.js in a Node subprocess (readabilipy) plus markdownify. This module uses a trimmed copy of codeberg.org/readeck/go-readability v2.1.3 (a maintained Go port of the same Readability.js, vendored as internal/readability to drop its weakly maintained transitive deps) and html-to-markdown configured to match markdownify's defaults (ATX headings, * bullets, * emphasis). On typical pages the output is byte-identical; the only observed difference is readability's URL normalization (e.g. a trailing slash added to bare links).

SSRF protection: only public IPs are reachable

By default the fetcher can reach only globally-routable public unicast addresses. This directly addresses the standard fetch-server caveat that such a tool "can access local/internal IP addresses and may represent a security risk": here it cannot.

Enforcement is in the dialer (net.Dialer.Control), so it runs after DNS resolution against the concrete IP the socket will connect to — which also covers HTTP redirects (every hop is re-dialed and re-checked) and DNS-rebinding (the resolved IP is what's validated, not the hostname). It is a strict default-deny allowlist; the following are refused:

  • loopback (127.0.0.0/8, ::1) and unspecified (0.0.0.0, ::)
  • private (10/8, 172.16/12, 192.168/16) and IPv6 ULA (fc00::/7)
  • carrier-grade NAT (100.64.0.0/10)
  • link-local, including the cloud metadata endpoint 169.254.169.254
  • broadcast, multicast, and IANA special-use / documentation / benchmarking ranges
  • IPv4-mapped IPv6 forms of any of the above (normalized before checking)

Code that makes its own requests can reuse the guard: set webfetch.GuardedControl as the Control of the net.Dialer its transport dials through. webfetch.IsPublicIP answers the same question for a single IP; use it only on an IP, never to vet a hostname before dialing it (DNS rebinding). The rejected set may grow in any release.

Documentation

Overview

Package webfetch is a dependency-light Go port of the reference Python "mcp-server-fetch" tool (github.com/modelcontextprotocol/servers, src/fetch). It fetches a URL, optionally extracts the page's main content as Markdown, and returns text ready to hand to an LLM.

The observable contract of the upstream tool is reproduced closely: the autonomous User-Agent string, the HTML/raw content-type heuristic, the "Contents of <url>:" wrapper, and the truncation / error strings.

The one unavoidable deviation is content extraction: upstream runs Mozilla Readability.js in a Node subprocess (readabilipy use_readability=True) plus Python markdownify. That JS pipeline cannot be reproduced byte-for-byte in pure Go, so we use a trimmed copy of codeberg.org/readeck/go-readability (a maintained Go port of the same Readability.js, in internal/readability) followed by JohannesKaufmann/html-to-markdown configured to match markdownify's defaults (ATX headings, "*" bullets, "*" emphasis). On typical pages this is byte-identical to the Python output; the only observed difference is readability's URL normalization (e.g. a trailing slash added to bare links). Staying in-process (no Node, no subprocess) is also what makes the sidecar container removable, which is the point of this package.

Beyond upstream, Options offers opt-in extensions (IncludeMetadata, PDFHandler, FullPage / Selector / ExcludeSelectors) that default to off, and one deliberate default: MaxBodyBytes caps response bodies at 10 MiB so a model-chosen URL cannot exhaust memory. Only bodies over the cap behave differently from upstream (they fail instead of being read whole).

Index

Constants

View Source
const DefaultMaxBodyBytes = 10 << 20

DefaultMaxBodyBytes is the response-body cap applied when Options.MaxBodyBytes is zero. Upstream reads bodies unbounded; the cap is a deliberate divergence that only affects bodies larger than this.

View Source
const DefaultMaxPDFBytes = 50 << 20

DefaultMaxPDFBytes is the body cap for PDF responses handed to Options.PDFHandler when Options.MaxPDFBytes is zero.

View Source
const DefaultUserAgentAutonomous = "ModelContextProtocol/1.0 (Autonomous; +https://github.com/modelcontextprotocol/servers)"

DefaultUserAgentAutonomous is the User-Agent sent for autonomous (tool-driven) fetches. It is copied verbatim from upstream mcp-server-fetch; the reference server presents this generic identity rather than the real client, and we preserve that behaviour intentionally.

Variables

This section is empty.

Functions

func Fetch

func Fetch(ctx context.Context, rawURL string, opts Options) (string, error)

Fetch fetches the URL, extracts/keeps the content, applies start_index/max_length paging, and returns the text wrapped as "<prefix>Contents of <url>:\n<content>". Outbound connections are restricted to public IPs by the SSRF guard in the dialer.

It returns a non-nil error on connection failure, HTTP status >= 400, a response body over MaxBodyBytes (or MaxPDFBytes), or (with PDFHandler) a PDF the handler fails on or that yields no text. Callers that have an alternate reader (e.g. a headless-browser fallback) should treat a non-nil error as "try the fallback".

func GuardedControl

func GuardedControl(network, address string, _ syscall.RawConn) error

GuardedControl is a net.Dialer Control hook that rejects connections to non-public IP addresses. It runs after DNS resolution with the concrete IP the socket is about to connect to, so it also blocks DNS-rebinding to a private target.

It is exported so a caller that makes its own requests gets the same guard: set it as the Control of the net.Dialer its transport dials through.

This replaces the SSRF protection that the deployment previously got for free by isolating the fetch sidecar on its own Docker network: with fetch now running in-process on the app network, a model-chosen (or prompt- injected) URL could otherwise reach loopback, RFC1918 hosts, or the cloud metadata endpoint (169.254.169.254). Blocking is done here, in the dialer, because that is the only place the real destination IP is known.

func IsPublicIP

func IsPublicIP(ip net.IP) bool

IsPublicIP reports whether ip is a globally-routable public unicast address the fetcher is allowed to reach. It is a strict allowlist: loopback, private (RFC1918 + ULA fc00::/7), link-local (incl. the 169.254.169.254 metadata endpoint), unspecified, broadcast, multicast, IPv6 outside 2000::/3, and the special-use ranges listed above are rejected — only public unicast passes. A nil or malformed ip is not public.

It judges an IP, never a hostname: checking a resolved name and then dialing it is open to DNS rebinding, so a guard for outbound connections belongs in GuardedControl. The rejected set may grow in any release.

Types

type Options

type Options struct {
	// MaxLength is the maximum number of characters to return. Zero means the
	// upstream default (5000).
	MaxLength int
	// StartIndex returns output starting at this character index, for paging a
	// previously truncated fetch.
	StartIndex int
	// Raw returns the actual HTML without Markdown simplification.
	Raw bool
	// UserAgent overrides the autonomous User-Agent. Empty uses the default.
	UserAgent string
	// MaxBodyBytes caps the size of the response body. A body larger than the
	// cap is rejected with a "Failed to fetch" error before any decoding, so a
	// model-chosen URL cannot exhaust memory. Zero (the default) applies
	// DefaultMaxBodyBytes (10 MiB); a negative value disables the cap, which is
	// upstream's unbounded behaviour. Bodies under the cap are unaffected.
	MaxBodyBytes int64
	// IncludeMetadata, when true, prepends a small YAML frontmatter block
	// (title, author, published, site, language — non-empty fields only) ahead
	// of the extracted Markdown. It applies only to the HTML-simplification path
	// (not Raw and not non-HTML content). Default false, which keeps the output
	// byte-identical to upstream mcp-server-fetch.
	//
	// The frontmatter counts as part of the returned content, so StartIndex /
	// MaxLength page over it too; hold IncludeMetadata constant across paged
	// calls so a page-2 StartIndex stays aligned.
	IncludeMetadata bool
	// PDFHandler, when set, receives the body of a PDF response (detected by
	// the "%PDF-" magic bytes, whatever the Content-Type) and returns its text,
	// which is then returned like any other content instead of the raw bytes
	// behind the "cannot be simplified" note. webfetch does not parse PDFs
	// itself: the bytes are untrusted, so run the parser somewhere a malformed
	// or malicious PDF cannot take the caller down (e.g. a Tika sidecar). The
	// handler must bound its own run time; webfetch's fetch timeout covers only
	// the download. A handler error or panic, or text that is empty after
	// trimming (e.g. a scan without OCR), fails the fetch with a "Failed to
	// extract PDF" error. Raw takes precedence. Nil (the default) keeps the
	// upstream raw-bytes behaviour.
	PDFHandler func(ctx context.Context, body []byte) (string, error)
	// MaxPDFBytes caps PDF bodies in place of MaxBodyBytes while PDFHandler is
	// set; the two caps are independent. Zero applies DefaultMaxPDFBytes
	// (50 MiB); a negative value disables the cap.
	MaxPDFBytes int64
	// FullPage converts the entire page to Markdown, skipping the Readability
	// main-content extraction. Use it when Readability over-strips (docs pages,
	// tables, sidebars you actually want). Ignored when Selector is set, and when
	// Raw is set. IncludeMetadata is not applied on this path. The text is
	// normalized as on the Readability path (NFC, soft hyphens removed), and
	// Selector / ExcludeSelectors are normalized to match it; text the page
	// writes as a reference (&shy;, &#x301;) stays as written, so a selector
	// with NFD / soft-hyphen text does not match it. Default false.
	FullPage bool
	// Selector, when set, converts only the element(s) matching this CSS selector
	// to Markdown, skipping Readability (an escape hatch for targeting a specific
	// region). Takes precedence over FullPage. Ignored when Raw is set.
	// IncludeMetadata is not applied on this path; text is normalized as with
	// FullPage. If nothing matches, the content is the
	// "<error>No content matched the selector.</error>" sentinel (with a nil
	// error). A blank Selector (whitespace only once normalized) counts as
	// unset; others go to the CSS parser as given. On an HTML page, one the
	// parser rejects (any member of a group) yields
	// "<error>Unsupported or invalid selector "<sel>": <reason>.</error>"
	// instead, also with a nil error; <sel> and <reason> are shown with
	// control characters as spaces, < > as ‹ ›, and cut to 200 runes.
	// Default "".
	Selector string
	// ExcludeSelectors removes element(s) matching these CSS selectors before
	// conversion. Unlike FullPage/Selector it composes with every non-raw mode,
	// including the default Readability path (e.g. strip a cookie banner, then
	// simplify). Empty (the default) leaves the input untouched, so output stays
	// byte-identical to upstream. Ignored when Raw is set. Blank entries are
	// dropped (as Selector), others used as given. On an HTML page, an entry
	// the parser rejects fails the extraction rather than keep what it should
	// drop: the content is only
	// "<error>Unsupported or invalid exclude selector "<sel>": <reason>.</error>"
	// (with a nil error), shown as for Selector. The selectors are
	// normalized (NFC, soft hyphens removed) on every mode, the Readability path
	// included. A backslash-escaped soft hyphen is not normalized like a literal
	// one: \AD matches only text the page writes as &shy;, and \ before a
	// literal one escapes the next character instead.
	ExcludeSelectors []string
}

Options mirror the upstream tool's parameters.

Directories

Path Synopsis
internal
readability
Package readability is a Go package that find the main readable content from a HTML page.
Package readability is a Go package that find the main readable content from a HTML page.
readability/dom
Package dom is the subset of github.com/go-shiori/dom (v0.0.0-20230515143342-73569d674e1c, MIT, see LICENSE) that readability uses: DOM-style helpers over golang.org/x/net/html.
Package dom is the subset of github.com/go-shiori/dom (v0.0.0-20230515143342-73569d674e1c, MIT, see LICENSE) that readability uses: DOM-style helpers over golang.org/x/net/html.
readability/re2go
Code generated by re2go 4.2, DO NOT EDIT.
Code generated by re2go 4.2, DO NOT EDIT.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL