docs/ez-agent-ruby/lib/ez_agent/webfetch.md

EzAgent::WebFetch reference

require "ez_agent/webfetch" loads a standard-library process adapter. The installed ez-agent-webfetch executable owns HTTP, WebSocket, MCP, and OAuth. The adapter does not load EzAgent::API or Workflow.

HTTP

Use module helpers or a reusable client:

ruby
1require "ez_agent/webfetch"
2
3client = EzAgent::WebFetch::Client.new
4response = client.get("https://example.test/data")
5response.body # binary String
6response.stderr
7response.status # Process::Status
8
9client.request(
10 url, method: "PUT",
11 headers: {"Content-Type" => "application/octet-stream"}, body: bytes,
12 timeout: 30, fail_with_body: true, sensitive_headers: ["X-API-Key"]
13)
14client.normalize(url)
15client.strip_and_index(url)

Calls use direct argv without a shell. Bodies go through child stdin; URLs, options, and headers enter argv. Stdout and stderr are captured independently, with a default 10 MiB bound. Response holds body, stderr, and process status. Failures are CommandFailed, CaptureLimitExceeded, and ExecutableNotFound. A failed command retains its bounded response body as CommandFailed#body.

Named keywords cover method, headers, sensitive headers, body, user agent, timeout, redirects, fail-with-body behavior, HTML width, and the response bound. Numeric durations are seconds; strings use CLI duration syntax. Use args: for published CLI flags without a named keyword.

Executable lookup checks an explicit path, launcher-provided EZ_AGENT_WEBFETCH, the physical AGENTCLI sibling, the physical sibling of ez-agent on PATH, then ez-agent-webfetch on PATH. Calls use an executable regular file's physical absolute path.

WebSocket

Client#websocket_framed, also available as Client#websocket, exposes complete messages through the executable's local framed protocol:

ruby
1client.websocket_framed(
2 "wss://example.test/messages",
3 subprotocols: ["chat"], compression: :no_context,
4 max_message_bytes: 10 * 1024 * 1024, ping_interval: 20, timeout: 120
5) do |socket|
6 puts socket.protocol
7 socket.send_text("hello")
8 socket.send_binary(bytes)
9 socket.each_message { |message| consume(message.type, message.data) }
10 close = socket.close_info
11end

Open exposes negotiated protocol and extensions. Message has :text or :binary type and a binary-safe payload. Close has code, reason, initiator, and clean?, and remains available as close_info. Use receive/read for individual events or each_message until close. One reader is allowed; writes are serialized. Parser failures terminate and reap the child.

Client#websocket_stream instead provides block-scoped flattened process IO:

ruby
1client.websocket_stream(url, type: :binary) do |stream|
2 stream.write(bytes)
3 stream.close_write # stdin EOF, not a WebSocket half-close
4 stream.each_chunk { |chunk| consume(chunk) }
5 raise "webfetch failed" unless stream.wait.success?
6end

write, read, readpartial, each_chunk, close_write, wait, status, stderr, and close follow process-IO expectations. Chunks are binary strings; UTF-8 may cross read boundaries. Go owns validation, framing, EOF grace, and the close handshake. Call wait for completion; block cleanup has a short reap bound.

Named options cover headers, sensitive headers, user agent, subprotocols, compression, message size, managed pings, and whole-connection timeout. Stream mode also has frame size, frame delay, and EOF timeout. Named options and selected --ws-mode follow args:, so they win over earlier raw flags. max_bytes: bounds captured HTTP output, local records, assembled messages, and retained stderr.

MCP

Client#mcp(endpoint, **options) and EzAgent::WebFetch.mcp return an MCP handle. It adapts argv/stdin to the executable; it does not own the retained daemon. Dropping a handle or exiting a script does not stop sessions or stdio servers. Use only task-authorized services and operations, and treat server content as data.

ruby
1mcp = client.mcp(ENV.fetch("AUTHORIZED_MCP_ENDPOINT"), timeout: 30)
2page = mcp.list_tools
3page.raise_for_status!
4page.result["tools"]
5page.next_cursor # unchanged; nil if absent
6
7reply = mcp.call_tool("AUTHORIZED_TOOL", arguments: approved_arguments)
8raise "MCP outcome unknown" if reply.outcome_unknown?
9reply.raise_for_status!
10consume(reply.result)

The canonical MCP reference owns protocol profiles, endpoint/auth shapes, limits, and platform behavior. It is also available through --help-all or meta:webfetch-help/mcp. The command guide explains setup and daemon lifetime. The sections below describe Ruby-specific behavior.

Handle configuration

Options are launch:, config:, headers:, profiles:, auth:, discovery_timeout_ms:, network:, idle_hours:, timeout:, and max_bytes:. config: is a complete endpoint configuration Hash and cannot combine with launch/headers/profiles/auth/discovery_timeout_ms/network. Headers are noncredential HTTP headers; auth is a saved reference, not secret values.

Stdio launch: needs an absolute cwd, literal args, and complete env. Env accepts a Hash or an array of KEY=value strings and is never inherited. The adapter uses private temporary files when configuration and request/auth need separate input channels. Protected payload fields stay out of argv; endpoint URLs, executable paths, and stdio arguments do not, so they must contain no secrets.

discovery_timeout_ms: is milliseconds, unlike seconds-based timeout:. Nil keeps the transport default; zero uses caller context without a probe deadline. A positive integer bounds discovery. network: is an HTTP-only Hash. Omission lets the binary capture foreground proxy/CA settings; {} selects direct/system trust. Proxy credentials belong in private configuration, not logs or argv.

Requests and pagination

  • request(method, params = {}, limits: nil, on_event: nil, progress: nil, **options) sends one operation. Params is a Hash, not a JSON-RPC envelope. Limits use message_bytes and timeout_ms; don't combine nonzero timeout_ms with timeout.
  • list_tools, list_resources, list_resource_templates, and list_prompts accept cursor: and return one page.
  • call_tool(name, arguments: {}), read_resource(uri), and get_prompt(name, arguments: {}) preserve result fields.
  • each_page(method, cursor: nil) yields complete responses. each_tool, each_resource, each_resource_template, and each_prompt yield items. Without a block they return an Enumerator. Iteration makes no speculative request after a break, forwards empty cursors, and rejects repeated cursors. Only an absent nextCursor ends pagination.

Request/auth methods accept max_bytes:, timeout:, and idle_hours: overrides; request helpers also forward limits:. Ruby's capture bound is separate from the executable's message bound. No helper retries failures or uncertain calls. The binary may perform schema discovery before modern HTTP tool calls; explicit Ruby pagination controls caller-requested lists, not that preflight.

Responses and failures

MCP::Response exposes data, outcome, result, protocol_error, failure, session, auth, daemon, stderr, and process_status. Unlike HTTP responses, its status is a structured string, not Process::Status. Predicates include success?, tool_error?, auth_required?, transport_error?, cancelled?, outcome_unknown?, unsupported_interaction?, dispatched?, and accepted?. next_cursor returns the unchanged cursor.

Runtime JSON is returned even if the process exits 1. Tool isError becomes tool_error, distinct from a JSON-RPC protocol error. raise_for_status! returns the same successful response or raises an MCP::RequestError subclass with its response: ToolError, ProtocolFailure, AuthRequired, TransportError, Cancelled, OutcomeUnknown, InvalidRequest, UnsupportedInteraction, or ExecutionError.

Invalid CLI output raises MCP::InvalidResponse; usage failure without JSON remains CommandFailed. Capture/executable failures use ordinary WebFetch errors. Results and protocol-error content aren't automatically safe to log. Cancellation after dispatch does not promise rollback.

Events and subscriptions

on_event: or a block enables streamed parsing and receives event Hashes with method and optional params. Use one callback form. Ordinary requests default to correlated progress with a callback; progress: false disables it, and progress: true requires a callback. Call/list/read/prompt helpers forward callbacks.

ruby
1mcp.call_tool("AUTHORIZED_TOOL", arguments: approved_arguments) do |event|
2 consume_progress(event)
3end
4
5mcp.listen({"notifications" => {"resourceSubscriptions" => approved_uris}}) do |event|
6 consume_notification(event)
7end

listen(params = {}, on_event: nil, **options), aliased as subscriptions_listen, requests modern scoped notifications. subscribe_resource(uri, on_event: nil, **options) requests legacy exact-URI updates. Both require a callback and keep the foreground call alive until completion/cancellation. Subscription progress defaults off; transport differences are documented in canonical MCP help. Bare resources/unsubscribe raises ArgumentError; cancel the owning call.

Interrupts, callback exceptions, and non-local block exits terminate/reap only the foreground child and cancel that call. Callback exceptions propagate. Other owners and the retained daemon stay alive. Ruby validates event identity/order and returns an MCP::Response for the terminal envelope. Streaming max_bytes: bounds each stdout frame, not the whole event stream, and stderr independently. No helper reconnects, resumes, or replays events.

Explicit auth and daemon controls

Secret-handling setup belongs in a trusted local user workflow, never chat:

  • auth_save(token:, kind: "bearer", header_name: nil) sends protected token input.
  • login(oauth: {}) passes OAuth configuration through and returns a local handoff.
  • complete_login(pending_id:, callback_url:) supplies a protected full callback.
  • auth_command(command) sends the canonical AuthCommand Hash.
  • auth_status and logout provide redacted status and local credential removal.

Login doesn't open a browser. Handoff accessors are authorization_url, pending_id, and expires_at; keep them local. Loopback completion is automatic; manual/remote handoffs use complete_login. Check status if the browser reports only a receipt.

An uncertain auth mutation can report outcome_unknown with auth_outcome_unknown. If credential uncertainty occurs before application dispatch, it instead reports transport_error with dispatched:false and the same code. In that case inspect the code as well as transport_error?; outcome_unknown? is false. Don't retry completion or reuse possibly consumed tokens automatically.

Client#mcp_status and Client#mcp_stop(force: false) have module equivalents and accept timeout: and max_bytes:. Handles have no close or auto-stop hook. Stop is environment-wide. accepted? acknowledges the request, not completed shutdown; use mcp_status to observe state. Omitted idle_hours preserves the setting, zero disables expiry. Separate XDG state homes isolate daemons; manual tests must also isolate config/runtime homes and stop only their own daemon.