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 ¶
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.
const DefaultMaxPDFBytes = 50 << 20
DefaultMaxPDFBytes is the body cap for PDF responses handed to Options.PDFHandler when Options.MaxPDFBytes is zero.
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 ¶
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 ¶
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 ¶
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 (­, ́) 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 ­, 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. |