mppx 0.21.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # mppx
2
2
 
3
+ ## 0.21.1
4
+
5
+ ### Patch Changes
6
+
7
+ - c5bbb31: Added `tempoX402()` at `mppx/x402/tempo`, which wires the official x402 SDK to the Tempo x402 facilitator: `tempo.route({ price })` fills `payTo` with the facilitator's deposit address (from `GET /supported`) and `extra.tempoSettlement` with the payout address, and a route can pay out to its own `payoutAddress`. It throws at startup on a missing API key or a missing or malformed payout address.
8
+
3
9
  ## 0.21.0
4
10
 
5
11
  ### Minor Changes
package/dist/cli/cli.js CHANGED
@@ -263,7 +263,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
263
263
  `))a.push(o.join(``)+i.slice(0,e)),o=[],s=0,i=i.slice(e+2);i&&(o.push(i),s+=i.length),n&&(a.push(o.join(``)),o=[],s=0),l&&a.length>0&&(a.shift(),l=!1),s>1048576&&(o=o.at(-1)?.endsWith(`
264
264
  `)?[`
265
265
  `]:[],s=o.length,l=!0);for(let e of a){let n=_O(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}async function*rB(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await cB(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=dz(e.body,i.path),!a&&r.doc&&(a=gz(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await Tz(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(sB),h=p.some(e=>!sB(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await Fz(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await Yz(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function iB(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of rB(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=aB(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function aB(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(Lz);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const oB=Object.values(Ze);function sB(e){return oB.find(t=>t.id===e)?.testnet===!0}async function cB(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await mz(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await pz(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=hD(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=uz(t.endpoint);e&&r.push(e)}else if(i){r=hz(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=lz(t.amount)?BigInt(t.amount):e,i=lz(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}Lx(),IA();const lB=_b(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||_A()){let t=await iB({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of rB({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>iz(e,n)}))switch(t.phase){case`discovery`:if(rz(`Discovery (/openapi.json)`),iz(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=Lz.split(`
266
- `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,rz(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),iz(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),iz(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}uB(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function uB(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function dB(e){return pB(e)?e.offers:[e]}function fB(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=mB(t.amount)??mB(i.amount)??null,o=mB(t.currency)??mB(i.currency),s=mB(e.description)??mB(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function pB(e){return`offers`in e&&!(`_canonicalRequest`in e)}function mB(e){return typeof e==`string`?e:void 0}var hB=z((()=>{})),gB=rt({generate:()=>_B,generateProxy:()=>vB});function _B(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>bB(e,r));return yB({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function vB(e){let t=e.routes.map(t=>({...t,path:xB(e.basePath,t.path)}));return yB({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function yB(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=cD.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function bB(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:dB(t).map(fB)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Kx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:fB(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function xB(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var SB=z((()=>{Jx(),mD(),hB()}));Lx(),RS(),NE(),NT(),Ww(),rT(),oT(),Wx(),eA(),tT(),OC(),Tw(),XA(),IA();const CB=`0.21.0`,wB=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),TB=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),EB=p.object({message:p.string(),path:p.string(),severity:p.string()}),DB=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),OB=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function kB(e){return e.format===`json`&&e.formatExplicit}function AB(e,t,n){if(kB(e))return e.ok(t);n()}async function jB(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function MB(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function NB(e){return typeof e==`string`?e:void 0}function PB(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function FB(e){let t=PB(e);return{...NB(e.description)?{description:NB(e.description)}:{},id:NB(e.id)??NB(e.name)??`unknown`,...NB(e.name)?{name:NB(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...NB(e.status)?{status:NB(e.status)}:{},...NB(e.serviceUrl)||NB(e.url)?{url:NB(e.serviceUrl)??NB(e.url)}:{}}}function IB(e){return{...NB(e.description)?{description:NB(e.description)}:{},method:NB(e.method)??`GET`,path:NB(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function LB(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=NB(t.amount),r=NB(t.currency),i=NB(t.method),a=NB(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function RB(e){return e.request.currency??e.request.asset}function zB(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=RB(e);return typeof t==`string`&&t.toLowerCase()===n})}async function BB(e,t,n={}){let r=()=>Uw().getChallenges(e),i=()=>nT().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}async function VB(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function HB(e){if(!EC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${cS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function UB(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function WB(e,t){return gL(zB(await BB(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function GB(e){return iT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function KB(e,t){if(!EC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:cS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[ow]:Qw({accepts:[tw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function qB(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function JB(e,t,n,r){let i=!1,a=t,o=qB(a),s={...n,redirect:`manual`,headers:zT(n.headers)};o.host&&QB(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=zT(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=qB(a),o.host&&QB(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function YB(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&ZB(i),qB(i.href)}function XB(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(qB(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&ZB(r),qB(r.href)}function ZB(e){throw new B({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function QB(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function $B(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function eV(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new B({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new B({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function tV(e,t){let n=t.toLowerCase();return e.find(e=>{let t=NB(e.id)?.toLowerCase(),r=NB(e.name)?.toLowerCase();return t===n||r===n})}const nV=_b(`mppx`,{mcp:{tools:{discovery:`direct`}},version:CB,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await bL(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=QA(),i={"User-Agent":e.options.userAgent??`mppx/${CB}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=_L(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=qB(o),f=d.url;d.host&&(i.Host=d.host);try{let r=gA(e.options.methodOpt),a=RL(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&lA(o,s,t);let p=await JB(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});uA(m,c),await jB(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await BB(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=zB(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(RB).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=vL(n?.config)?.length?v:await jI(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>HB(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=gL(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=EC(S),ee=T?XB(p.logicalUrl,($B(S)??m.url)||p.logicalUrl):YB(o,d,p.logicalUrl);if(!T)try{kT(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let te=KB(S,m),E=S.request.currency??``,D=S.request.decimals??6,O,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),E=A.tokenSymbol,D=A.tokenDecimals,O=A.explorerUrl);let ne=!e.options.silent&&e.options.confirm,j=new Set;{uA(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,pA(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:E,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,dA(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=fA(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,dA(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)j.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||ne){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
266
+ `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,rz(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),iz(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),iz(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}uB(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function uB(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function dB(e){return pB(e)?e.offers:[e]}function fB(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=mB(t.amount)??mB(i.amount)??null,o=mB(t.currency)??mB(i.currency),s=mB(e.description)??mB(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function pB(e){return`offers`in e&&!(`_canonicalRequest`in e)}function mB(e){return typeof e==`string`?e:void 0}var hB=z((()=>{})),gB=rt({generate:()=>_B,generateProxy:()=>vB});function _B(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>bB(e,r));return yB({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function vB(e){let t=e.routes.map(t=>({...t,path:xB(e.basePath,t.path)}));return yB({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function yB(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=cD.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function bB(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:dB(t).map(fB)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Kx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:fB(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function xB(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var SB=z((()=>{Jx(),mD(),hB()}));Lx(),RS(),NE(),NT(),Ww(),rT(),oT(),Wx(),eA(),tT(),OC(),Tw(),XA(),IA();const CB=`0.21.1`,wB=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),TB=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),EB=p.object({message:p.string(),path:p.string(),severity:p.string()}),DB=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),OB=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function kB(e){return e.format===`json`&&e.formatExplicit}function AB(e,t,n){if(kB(e))return e.ok(t);n()}async function jB(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function MB(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function NB(e){return typeof e==`string`?e:void 0}function PB(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function FB(e){let t=PB(e);return{...NB(e.description)?{description:NB(e.description)}:{},id:NB(e.id)??NB(e.name)??`unknown`,...NB(e.name)?{name:NB(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...NB(e.status)?{status:NB(e.status)}:{},...NB(e.serviceUrl)||NB(e.url)?{url:NB(e.serviceUrl)??NB(e.url)}:{}}}function IB(e){return{...NB(e.description)?{description:NB(e.description)}:{},method:NB(e.method)??`GET`,path:NB(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function LB(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=NB(t.amount),r=NB(t.currency),i=NB(t.method),a=NB(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function RB(e){return e.request.currency??e.request.asset}function zB(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=RB(e);return typeof t==`string`&&t.toLowerCase()===n})}async function BB(e,t,n={}){let r=()=>Uw().getChallenges(e),i=()=>nT().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}async function VB(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function HB(e){if(!EC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${cS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function UB(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function WB(e,t){return gL(zB(await BB(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function GB(e){return iT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function KB(e,t){if(!EC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:cS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[ow]:Qw({accepts:[tw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function qB(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function JB(e,t,n,r){let i=!1,a=t,o=qB(a),s={...n,redirect:`manual`,headers:zT(n.headers)};o.host&&QB(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=zT(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=qB(a),o.host&&QB(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function YB(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&ZB(i),qB(i.href)}function XB(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(qB(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&ZB(r),qB(r.href)}function ZB(e){throw new B({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function QB(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function $B(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function eV(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new B({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new B({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function tV(e,t){let n=t.toLowerCase();return e.find(e=>{let t=NB(e.id)?.toLowerCase(),r=NB(e.name)?.toLowerCase();return t===n||r===n})}const nV=_b(`mppx`,{mcp:{tools:{discovery:`direct`}},version:CB,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await bL(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=QA(),i={"User-Agent":e.options.userAgent??`mppx/${CB}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=_L(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=qB(o),f=d.url;d.host&&(i.Host=d.host);try{let r=gA(e.options.methodOpt),a=RL(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&lA(o,s,t);let p=await JB(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});uA(m,c),await jB(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await BB(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=zB(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(RB).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=vL(n?.config)?.length?v:await jI(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>HB(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=gL(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=EC(S),ee=T?XB(p.logicalUrl,($B(S)??m.url)||p.logicalUrl):YB(o,d,p.logicalUrl);if(!T)try{kT(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let te=KB(S,m),E=S.request.currency??``,D=S.request.decimals??6,O,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),E=A.tokenSymbol,D=A.tokenDecimals,O=A.explorerUrl);let ne=!e.options.silent&&e.options.confirm,j=new Set;{uA(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,pA(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:E,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,dA(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=fA(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,dA(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)j.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||ne){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
267
267
  `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(ne&&(t(`
268
268
  `),!await bA(`Proceed with ${S.intent}?`,!0))){t(`Aborted.
269
269
  `);return}}let re=process.env.MPPX_PRIVATE_KEY?.trim()||!vA(UA(e.options.account));if(gk(S)&&re&&!w){try{await zR({challenge:S,challengeResponse:te,credentialContext:await mL(S,n?.config.extensions,A?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:ee.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return OR(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:w&&gk(S)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let M=w&&gk(S)?void 0:await mL(S,n?.config.extensions,A?.credentialContext),N,ie;if(w&&gk(S)){let e=te;N=await IE({methods:[w],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await mL(e,n?.config.extensions,A?.credentialContext);return SL(S,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(ee.url,{...p.init,context:M,redirect:`manual`})}else{if(h?.key===HB(S))ie=h.credential;else if(A?.createCredential)ie=await A.createCredential(te,M);else if(A)ie=await IE({methods:A.methods,polyfill:!1,transport:GB(S)}).createCredential(te,M);else if(w)ie=await IE({methods:[w],polyfill:!1,transport:GB(S)}).createCredential(te,M);else throw Error(`unreachable`);let n=T?sw:DS(S),r={...zT(p.init.headers),[n]:ie};T&&QB(r,ee.host),C?.prepareCredentialRequest?.({challenge:S,credential:ie,headers:r});let i={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&lA(ee.url,i,t),N=await u(ee.url,i)}if(h=ie===void 0?void 0:{credential:ie,key:HB(S)},N.status===402&&!(w&&gk(S))&&i+1<3&&UB(N.url,p.response.url)){let t=t=>WB(t,{config:n?.config,currency:e.options.currency,ignoreX402ResponseUrl:g,protocol:e.options.protocol}),r=new Response(null,{headers:N.headers,status:N.status,statusText:N.statusText});if(Object.defineProperty(r,"url",{value:N.url}),await t(r.clone())){await N.body?.cancel().catch(()=>{}),m=r;continue}if(e.options.protocol!==`mpp`&&!g){let e=await VB(N,1048576);if(e.complete&&await t(e.response.clone())){m=e.response;continue}N=e.response}}if(e.options.fail&&N.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${N.status}`,exitCode:22});if(N.status===402){let n=await N.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,mA(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(uA(N,c),!(ie&&await C?.handleResponse?.({challenge:S,credential:ie,response:N,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:ne,confirm:bA,tokenSymbol:E,tokenDecimals:D,explorerUrl:O,shownKeys:j}))){let n=N.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(k.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||j.has(t)||t===`reference`&&o)continue;let e=C?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${xA(BigInt(n),E,D)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&O?r.push([t,hA(`${O}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
@@ -1,5 +1,5 @@
1
1
  /** Current mppx package version. */
2
- export declare const version = "0.21.0";
2
+ export declare const version = "0.21.1";
3
3
  /** Canonical SDK identifier for this mppx release. */
4
- export declare const sdkIdentifier = "mppx/0.21.0";
4
+ export declare const sdkIdentifier = "mppx/0.21.1";
5
5
  //# sourceMappingURL=version.d.ts.map
@@ -1,6 +1,6 @@
1
1
  // Generated by scripts/sync-version.ts.
2
2
  /** Current mppx package version. */
3
- export const version = '0.21.0';
3
+ export const version = '0.21.1';
4
4
  /** Canonical SDK identifier for this mppx release. */
5
5
  export const sdkIdentifier = `mppx/${version}`;
6
6
  //# sourceMappingURL=version.js.map
@@ -0,0 +1,48 @@
1
+ import type { RouteConfig } from '@x402/core/server';
2
+ import { x402ResourceServer } from '@x402/core/server';
3
+ /** The Tempo x402 facilitator. Fixed, so the API key only ever goes to Tempo over HTTPS. */
4
+ export declare const url = "https://api.tempo.xyz/v1/x402";
5
+ /** Base mainnet, the network the Tempo x402 facilitator settles USDC on. */
6
+ export declare const network = "eip155:8453";
7
+ /** Options for {@link tempoX402}. */
8
+ export type Options = {
9
+ /** Tempo API key with the `mpp:write` scope. @default process.env.TEMPO_API_KEY */
10
+ apiKey?: string | undefined;
11
+ /**
12
+ * Tempo address that receives each payment, as `extra.tempoSettlement`. A route can override it.
13
+ * @default process.env.TEMPO_PAYOUT_ADDRESS
14
+ */
15
+ payoutAddress?: string | undefined;
16
+ };
17
+ /** Options for one route, passed to `route()`. */
18
+ export type RouteOptions = Omit<RouteConfig, 'accepts'> & {
19
+ /** Price per request in USD, such as `'$0.01'`. */
20
+ price: string;
21
+ /** Tempo address that receives this route's payments, such as a platform's seller. */
22
+ payoutAddress?: string | undefined;
23
+ };
24
+ /**
25
+ * Wires the official x402 SDK to the Tempo x402 facilitator: buyers pay in USDC on Base and the
26
+ * seller is paid out on Tempo.
27
+ *
28
+ * Returns an `x402ResourceServer` with the exact EVM scheme registered and the API key on every
29
+ * facilitator request, and `route()`, which builds a route's config: it sets `payTo` to the
30
+ * facilitator's deposit address and `extra.tempoSettlement` to the payout address. The deposit
31
+ * address comes from the facilitator's `GET /supported`, which the x402 SDK reads when the
32
+ * middleware starts.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { paymentMiddleware } from '@x402/hono'
37
+ * import { tempoX402 } from 'mppx/x402/tempo'
38
+ *
39
+ * const tempo = tempoX402() // reads TEMPO_API_KEY and TEMPO_PAYOUT_ADDRESS
40
+ * app.use(paymentMiddleware({ 'GET /weather': tempo.route({ price: '$0.01' }) }, tempo.server))
41
+ * ```
42
+ */
43
+ export declare function tempoX402(options?: Options): {
44
+ payTo: () => string;
45
+ route: (parameters: RouteOptions) => RouteConfig;
46
+ server: x402ResourceServer;
47
+ };
48
+ //# sourceMappingURL=tempo.d.ts.map
@@ -0,0 +1,68 @@
1
+ import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server';
2
+ import { ExactEvmScheme } from '@x402/evm/exact/server';
3
+ import { isAddress } from 'viem';
4
+ /** The Tempo x402 facilitator. Fixed, so the API key only ever goes to Tempo over HTTPS. */
5
+ export const url = 'https://api.tempo.xyz/v1/x402';
6
+ /** Base mainnet, the network the Tempo x402 facilitator settles USDC on. */
7
+ export const network = 'eip155:8453';
8
+ /**
9
+ * Wires the official x402 SDK to the Tempo x402 facilitator: buyers pay in USDC on Base and the
10
+ * seller is paid out on Tempo.
11
+ *
12
+ * Returns an `x402ResourceServer` with the exact EVM scheme registered and the API key on every
13
+ * facilitator request, and `route()`, which builds a route's config: it sets `payTo` to the
14
+ * facilitator's deposit address and `extra.tempoSettlement` to the payout address. The deposit
15
+ * address comes from the facilitator's `GET /supported`, which the x402 SDK reads when the
16
+ * middleware starts.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { paymentMiddleware } from '@x402/hono'
21
+ * import { tempoX402 } from 'mppx/x402/tempo'
22
+ *
23
+ * const tempo = tempoX402() // reads TEMPO_API_KEY and TEMPO_PAYOUT_ADDRESS
24
+ * app.use(paymentMiddleware({ 'GET /weather': tempo.route({ price: '$0.01' }) }, tempo.server))
25
+ * ```
26
+ */
27
+ export function tempoX402(options = {}) {
28
+ const env = globalThis.process
29
+ ?.env;
30
+ const apiKey = options.apiKey || env?.TEMPO_API_KEY;
31
+ if (!apiKey)
32
+ throw new Error('tempoX402 requires `apiKey` or TEMPO_API_KEY.');
33
+ const payoutAddress = options.payoutAddress || env?.TEMPO_PAYOUT_ADDRESS;
34
+ const headers = { 'tempo-api-key': apiKey };
35
+ const server = new x402ResourceServer(new HTTPFacilitatorClient({
36
+ // GET /supported is public: the key goes only with verify and settle.
37
+ createAuthHeaders: async () => ({ settle: headers, supported: {}, verify: headers }),
38
+ url,
39
+ })).register(network, new ExactEvmScheme());
40
+ /** Tempo's deposit address for this network, from the SDK's `GET /supported` read. */
41
+ function payTo() {
42
+ const address = server.getSupportedKind(2, network, 'exact')?.extra?.payTo;
43
+ if (typeof address !== 'string')
44
+ throw new Error(`Tempo x402 facilitator publishes no payTo for exact on ${network}.`);
45
+ return address;
46
+ }
47
+ /** Builds a paid route's config. Throws when neither the route nor {@link tempoX402} names a payout address. */
48
+ function route(parameters) {
49
+ const { payoutAddress: routePayoutAddress, price, ...rest } = parameters;
50
+ const tempoSettlement = routePayoutAddress ?? payoutAddress;
51
+ if (!tempoSettlement)
52
+ throw new Error('tempoX402 requires a payout address: pass `payoutAddress` or set TEMPO_PAYOUT_ADDRESS.');
53
+ if (!isAddress(tempoSettlement, { strict: false }))
54
+ throw new Error(`tempoX402 payout address is not an address: ${tempoSettlement}`);
55
+ return {
56
+ ...rest,
57
+ accepts: {
58
+ extra: { tempoSettlement },
59
+ network,
60
+ payTo: () => payTo(),
61
+ price,
62
+ scheme: 'exact',
63
+ },
64
+ };
65
+ }
66
+ return { payTo, route, server };
67
+ }
68
+ //# sourceMappingURL=tempo.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mppx",
3
3
  "type": "module",
4
- "version": "0.21.0",
4
+ "version": "0.21.1",
5
5
  "main": "./dist/index.js",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/wevm/mppx#readme",
@@ -123,6 +123,10 @@
123
123
  "types": "./dist/x402/mcp.d.ts",
124
124
  "default": "./dist/x402/mcp.js"
125
125
  },
126
+ "./x402/tempo": {
127
+ "types": "./dist/x402/tempo.d.ts",
128
+ "default": "./dist/x402/tempo.js"
129
+ },
126
130
  "./tempo": {
127
131
  "types": "./dist/tempo/index.d.ts",
128
132
  "default": "./dist/tempo/index.js"
@@ -200,6 +204,7 @@
200
204
  "@modelcontextprotocol/sdk": ">=1.25.0",
201
205
  "@stripe/agent-identity": ">=0.3.0",
202
206
  "@x402/core": ">=2.22.0",
207
+ "@x402/evm": ">=2.22.0",
203
208
  "@x402/express": ">=2.22.0",
204
209
  "@x402/hono": ">=2.22.0",
205
210
  "@x402/mcp": ">=2.22.0",
@@ -220,6 +225,9 @@
220
225
  "@x402/core": {
221
226
  "optional": true
222
227
  },
228
+ "@x402/evm": {
229
+ "optional": true
230
+ },
223
231
  "@x402/express": {
224
232
  "optional": true
225
233
  },