Fetch.from
Create a payment-aware fetch wrapper
Choose a signing account
Create a server-only wallet.ts module, then import account wherever an example creates a local signing account.
import { privateKeyToAccount } from 'viem/accounts'
export const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)Creates a scoped fetch wrapper that handles 402 Payment Required responses without modifying globalThis.fetch.
The wrapper also handles MCP-over-HTTP payment required errors returned as JSON-RPC -32042 responses, including the first event in an SSE stream.
Payment retries use redirect: 'manual', even when the initial request allows redirects. A 3xx response returns without forwarding the Credential to another URL and leaves the payment attempt pending because the redirect doesn't confirm payment acceptance.
Usage
With allowed origins
Use acceptPaymentPolicy to control where the wrapper injects Accept-Payment.
Return type
type ReturnType = (
input: RequestInfo | URL,
init?: RequestInit & { context?: AnyContextFor<methods> }
) => Promise<Response>Parameters
acceptPayment (optional)
- Type:
AcceptPayment.Resolved<methods>
Resolved Accept-Payment header and preference data. Most callers use methods and paymentPreferences on Mppx.create instead.
acceptPaymentPolicy (optional)
- Type:
'always' | 'same-origin' | 'never' | { origins: readonly string[] } - Default:
'always'
Controls when Accept-Payment is injected.
Use 'same-origin' in browsers when you only want same-origin payment discovery. Use { origins } when paid APIs live on specific origins. Origin patterns support *. subdomain wildcards.
eventDispatcher (optional)
- Type:
ClientEventDispatcher<methods>
Advanced shared event dispatcher. challenge.received handlers run before onChallenge; the first non-empty Credential string skips onChallenge.
fetch (optional)
- Type:
typeof globalThis.fetch - Default:
globalThis.fetch
Custom fetch function to wrap.
methods
- Type:
readonly Method.AnyClient[]
Array of payment methods to use for 402 responses.
onChallenge (optional)
- Type:
(challenge, helpers) => Promise<string | undefined>
Called after a 402 Challenge is selected and before the wrapper retries the request. Return a Credential string to override the default Credential flow.
orderChallenges (optional)
- Type:
(challenges: readonly Challenge[]) => readonly Challenge[]
Filters or reorders supported Challenges before Credential creation.
transport (optional)
- Type:
Transport.AnyTransport - Default:
Transport.http()
Transport used to extract Challenges and attach Credentials.