docs/internal/webfetch.md

internal/webfetch: operation engines

WebFetch is a standalone outbound HTTP, WebSocket, and MCP client. The CLI parses and dispatches locally; MCP requests pass through a separate retained-session daemon. It does not register EzAgent tools, inject server schemas, or change the agent JSONL API or session database.

Command flags and exits belong to the command guide. Exact flags, input shapes, limits, and local framing belong to the canonical webfetchhelp/text assets, shared with builtin buffers by webfetchhelp. The Ruby adapter invokes the same executable.

Structural model

text
1validated operation
2 -> HTTP request -> optional HTML/Markdown transform -> output
3 OR
4 -> WebSocket connection -> stream/framed adapter -> stdin/stdout
5 OR
6 -> retained MCP daemon -> authorized client/transport -> operation result

Option parsing selects exactly one operation. HTTP owns redirects and response metadata. Transforms consume a completed HTTP representation. WebSocket mode owns a bidirectional connection and adapts it to a local terminal protocol. Information requests do not select a runner. The CLI installs signal handling before calling Run; ordinary HTTP/WebSocket operations execute in the foreground.

Organization

ResponsibilityOwner
CLI parsing, dispatch, diagnosticsoptions.go, run.go, errors.go
HTTP and outputhttp.go, headers.go, output.go
HTML/Markdown extraction and indexeshtml*.go, markdown.go, index.go
WebSocket streams and local recordswebsocket*.go
MCP CLI input and platform wiringmcp_*.go
Foreground OAuth permission review and private callback promptmcp_login*.go
MCP operation/result types and private daemon framesmcp/contract
MCP negotiation and HTTP/stream transportsmcp/protocol, mcp/httptransport, mcp/stream
OAuth and credential persistencemcp/auth, mcp/authstore
Per-caller proxy and trust configurationmcp/netpolicy
Connected peer identity, separate from caller policymcp/peercred
Windows protected filesystem operationsmcp/winfs
Retained clients, daemon lifecycle and executable handoffmcp/daemon

MCP platform files supply filesystem, peer-identity, and process mechanisms; the protocol, pool, and server remain shared. The daemon and external Unix MCP transport share peer-identity lookup, but each caller decides which identity to accept.

Design constraints

  • HTTP and WebSocket clients retain system TLS verification and proxy behavior; there is no insecure TLS mode. Sensitive headers may not cross an origin change.
  • Diagnostics must not expose secrets or raw provider errors. Only explicitly safe errors may publish operation-specific text. MCP HTTP authentication challenges report the HTTP status and whether credentials were attached to the rejected request, without printing headers, tokens or provider prose. A configured OAuth grant is not proof that the server accepts its credentials.
  • Terminal --mcp-login reviews permissions before setup, owns a cancellable private callback reader, and waits for saved credentials. Unix callback input is noncanonical; restoration discards queued private bytes, including through the synchronous signal path. Windows consumes console input events rather than using potentially blocking line reads after readiness checks. --mcp-auth and redirected output preserve the structured machine interface. The foreground never redeems codes itself or replays an uncertain completion. Interactive failures report the failed step and the daemon's safe, client-authored error directly rather than replacing it with a request to run an auth-status command. Safe local terminal errors also remain visible; confirmation-read failures are not treated as declines, and output failures report on stderr. Callback validation rejections and drained oversized pastes return to the private prompt. Transient status transport failures keep polling with one warning per outage. Token exchange, storage and uncertain completion failures are never retried. Scope display is provider-neutral. Hidden typing gives a constant input indicator without echoing commands or callback characters. Cancellation and expiry retain auth-status recovery guidance. Raw executor errors, provider bodies and callback values are not diagnostics.
  • WebSocket EOF-idle close preserves a peer status published by the concurrent application reader, even if the local close call returns a generic transport error first. Reader settlement uses the existing bounded grace period so blocked stdout cannot hold shutdown indefinitely. Without a peer result, transport close errors remain failures.
  • Raw HTTP and file output stream directly and may leave partial output. Transforms are bounded and materialized before output; transformation failures emit no body prefix. HTML extraction is neither browser rendering nor security sanitization.
  • Framed WebSocket records and MCP control/event envelopes are local executable interfaces, not EzAgent JSONL or raw WebSocket frames. Framed grammar and close/error records belong to framed.txt and websocket_framed.go, not an RFC 6455 wire dump.
  • Unix runtime paths allow group-writable user/root-owned ancestors, matching credential storage. Other-writable ancestors are rejected except root-owned sticky system directories; symlinks are rejected. The configured runtime base must be user-owned and not group/other-writable. Managed runtime directories remain private at mode 0700. Permission diagnostics name the failing path.
  • Retained MCP clients are separated by endpoint, auth, launch, and network identity. Blocked work and caller cancellation must not affect unrelated work. Shared startup continues while another caller needs it. A session-bearing HTTP 404 clears the session ID and publishes disconnected state before returning session expiry to its caller; subsequent calls cannot reuse that session.
  • Application calls with uncertain dispatch are never replayed. Credential-commit uncertainty before application dispatch is a separate failure, not evidence that the application ran.
  • Stdio executes authorized paths with normal symlink/workspace semantics. Its executable hash is not a sandbox or an atomic snapshot. The daemon's own executable handoff has separate identity and lifetime-ownership requirements.
  • HTTP policy belongs to each foreground caller, not the first daemon launcher. Stdio receives a complete explicit environment. The daemon excludes ambient credentials and loader settings.
  • Credential encoding obscures casual viewing; it is not encryption. Protected storage, exact credential binding, and refresh serialization remain necessary. Definite pre-mutation auth rejection preserves retained clients and pending logins; consumed or uncertain completion does not. Setup/logout affects the selected credential record, not other records' logins on the same endpoint. Local operations must not depend on successful remote CA initialization.

Platform boundary and validation

Windows uses the shared transports with SID/ACL checks, native file locks, and platform-specific daemon launch and child cleanup. Absolute XDG overrides are honored; default state lives under LOCALAPPDATA. Its AF_UNIX peer check authenticates the process's primary-token user, not an impersonating thread. Numeric Unix UID overrides have no Windows mapping. Windows pins the daemon image while running, so replacing that same executable path requires stopping the daemon first. Native Windows execution and storage power-loss durability remain unvalidated.

Behavior tests live beside their owners, including option, HTTP, transform, WebSocket, output, and runner tests. CLI lifecycle coverage is in cmd/ez-agent-webfetch. Help identity and assembly are tested in webfetchhelp and the builtin buffer package. Use the test guide for commands and isolated daemon fixtures.