agentcash 0.3.4 → 0.3.6

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.
Files changed (43) hide show
  1. package/dist/cjs/run-server.cjs +93839 -93640
  2. package/dist/esm/{chunk-FJSHGCIM.js → chunk-DZC5MTYY.js} +2 -2
  3. package/dist/esm/{chunk-GCS3RSLB.js → chunk-EVE4PTLY.js} +6 -6
  4. package/dist/esm/chunk-EVE4PTLY.js.map +1 -0
  5. package/dist/esm/chunk-FM2E2QVT.js +716 -0
  6. package/dist/esm/chunk-FM2E2QVT.js.map +1 -0
  7. package/dist/esm/{chunk-MOO4ZEGR.js → chunk-PCCYUD6X.js} +3 -3
  8. package/dist/esm/{chunk-KD2ZZXT7.js → chunk-PJFATGPH.js} +43 -2
  9. package/dist/esm/chunk-PJFATGPH.js.map +1 -0
  10. package/dist/esm/chunk-QCFNW6VN.js +22 -0
  11. package/dist/esm/chunk-QCFNW6VN.js.map +1 -0
  12. package/dist/esm/chunk-VVTMCXSK.js +309 -0
  13. package/dist/esm/chunk-VVTMCXSK.js.map +1 -0
  14. package/dist/esm/{commands-DUIGMEXV.js → commands-DE2RIAL5.js} +60 -111
  15. package/dist/esm/commands-DE2RIAL5.js.map +1 -0
  16. package/dist/esm/{fund-Y2STNDHA.js → fund-IALSHTLH.js} +4 -5
  17. package/dist/esm/{fund-Y2STNDHA.js.map → fund-IALSHTLH.js.map} +1 -1
  18. package/dist/esm/index.js +19 -13
  19. package/dist/esm/index.js.map +1 -1
  20. package/dist/esm/{install-GFY4JNNJ.js → install-Q4KN5XCP.js} +6 -8
  21. package/dist/esm/{install-GFY4JNNJ.js.map → install-Q4KN5XCP.js.map} +1 -1
  22. package/dist/esm/lib.d.ts +68 -3
  23. package/dist/esm/lib.js +6 -2
  24. package/dist/esm/{server-7D6YY3KG.js → server-WCNK52XR.js} +153 -531
  25. package/dist/esm/server-WCNK52XR.js.map +1 -0
  26. package/dist/esm/shared/operations/index.d.ts +12 -53
  27. package/dist/esm/shared/operations/index.js +6 -7
  28. package/package.json +3 -3
  29. package/dist/esm/chunk-CZBCIWYU.js +0 -48
  30. package/dist/esm/chunk-CZBCIWYU.js.map +0 -1
  31. package/dist/esm/chunk-GCS3RSLB.js.map +0 -1
  32. package/dist/esm/chunk-GIYROB7O.js +0 -210
  33. package/dist/esm/chunk-GIYROB7O.js.map +0 -1
  34. package/dist/esm/chunk-KD2ZZXT7.js.map +0 -1
  35. package/dist/esm/chunk-NQNMVKGY.js +0 -382
  36. package/dist/esm/chunk-NQNMVKGY.js.map +0 -1
  37. package/dist/esm/chunk-XXKBL2AC.js +0 -31
  38. package/dist/esm/chunk-XXKBL2AC.js.map +0 -1
  39. package/dist/esm/commands-DUIGMEXV.js.map +0 -1
  40. package/dist/esm/lib-DIhoN8bW.d.ts +0 -115
  41. package/dist/esm/server-7D6YY3KG.js.map +0 -1
  42. /package/dist/esm/{chunk-FJSHGCIM.js.map → chunk-DZC5MTYY.js.map} +0 -0
  43. /package/dist/esm/{chunk-MOO4ZEGR.js.map → chunk-PCCYUD6X.js.map} +0 -0
@@ -1,55 +1,45 @@
1
1
  import {
2
2
  buildRequest,
3
+ createFetchWithPayment,
3
4
  requestSchema
4
- } from "./chunk-XXKBL2AC.js";
5
+ } from "./chunk-VVTMCXSK.js";
5
6
  import {
6
- getTempoBalance,
7
- getTempoChainId,
8
- getTempoRpcUrl,
9
- getTempoTokenAddress,
10
- submitErrorReport
11
- } from "./chunk-GIYROB7O.js";
12
- import {
13
- fetchOpenApiSpec,
14
- getEndpointSchema,
15
- getIndexEntry,
7
+ TEMPO_RPC_URL,
8
+ checkEndpoint,
9
+ detectPaymentProtocols,
10
+ discoverResources,
16
11
  getInputSchema,
17
12
  getOriginIndex,
18
13
  getSiwxExtension,
19
- safeCreatePaymentPayload,
14
+ getTempoBalance,
15
+ getWalletInfo,
20
16
  safeCreateSIWxPayload,
17
+ safeGetMppChallenge,
21
18
  safeGetPaymentRequired,
22
- safeGetPaymentSettlement,
23
- tokenStringToNumber,
24
- x402Err,
25
- x402Ok
26
- } from "./chunk-NQNMVKGY.js";
27
- import "./chunk-FJSHGCIM.js";
19
+ submitErrorReport
20
+ } from "./chunk-FM2E2QVT.js";
21
+ import "./chunk-DZC5MTYY.js";
28
22
  import {
29
23
  DEFAULT_NETWORK,
30
24
  getWallet,
31
25
  redeemInviteCode,
32
- safeStringifyJson
33
- } from "./chunk-GCS3RSLB.js";
34
- import {
35
- getBalance,
36
- getDepositLink,
37
- openDepositLink
38
- } from "./chunk-CZBCIWYU.js";
26
+ safeStringifyJson,
27
+ toJsonObject
28
+ } from "./chunk-EVE4PTLY.js";
39
29
  import {
40
30
  err,
41
- fetchErr,
42
31
  fetchHttpErr,
43
- fetchOk,
32
+ getBalance,
33
+ getDepositLink,
44
34
  isFetchError,
45
35
  log,
46
36
  ok,
37
+ openDepositLink,
47
38
  resultFromPromise,
48
- resultFromThrowable,
49
39
  safeFetch,
50
40
  safeFetchJson,
51
41
  safeParseResponse
52
- } from "./chunk-KD2ZZXT7.js";
42
+ } from "./chunk-PJFATGPH.js";
53
43
  import "./chunk-ISR6DJ53.js";
54
44
 
55
45
  // src/server/index.ts
@@ -57,12 +47,12 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
57
47
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
58
48
  import { randomBytes } from "crypto";
59
49
 
60
- // src/server/tools/x402-fetch.ts
50
+ // src/server/tools/fetch.ts
61
51
  import { z } from "zod";
62
- import { formatUnits as formatUnits2 } from "viem";
63
52
  import { x402Client, x402HTTPClient } from "@x402/core/client";
64
53
  import { ExactEvmScheme } from "@x402/evm/exact/client";
65
- import { Mpay, tempo } from "mpay/client";
54
+ import { Mpay, tempo as tempoMethod } from "mpay/client";
55
+ import { tempo } from "viem/chains";
66
56
 
67
57
  // src/server/tools/response/lib.ts
68
58
  var parsedResponseToToolContentPart = (data) => {
@@ -252,67 +242,12 @@ Insufficient Tempo balance for this payment.`
252
242
  return balance;
253
243
  };
254
244
 
255
- // src/shared/protocol.ts
256
- function detectPaymentProtocols(response) {
257
- const protocols = [];
258
- const wwwAuth = response.headers.get("WWW-Authenticate");
259
- if (wwwAuth?.startsWith("Payment")) {
260
- protocols.push("mpp");
261
- }
262
- const paymentRequired = response.headers.get("payment-required");
263
- if (paymentRequired) {
264
- protocols.push("x402");
265
- }
266
- if (protocols.length === 0) {
267
- protocols.push("x402");
268
- }
269
- return protocols;
270
- }
271
-
272
- // src/shared/neverthrow/mpp/index.ts
273
- import { Challenge, Receipt } from "mpay";
274
- var errorType = "mpp";
275
- var mppOk = (value) => ok(value);
276
- var mppErr = (surface3, error) => err(errorType, surface3, error);
277
- var mppResultFromPromise = (surface3, promise, error) => resultFromPromise(errorType, surface3, promise, error);
278
- var mppResultFromThrowable = (surface3, fn, error) => resultFromThrowable(errorType, surface3, fn, error);
279
- var safeGetMppChallenge = (surface3, response) => {
280
- return mppResultFromThrowable(
281
- surface3,
282
- () => Challenge.fromResponse(response),
283
- (error) => ({
284
- cause: "parse_mpp_challenge",
285
- message: error instanceof Error ? error.message : "Failed to parse MPP challenge from response"
286
- })
287
- );
288
- };
289
- var safeCreateMppCredential = (surface3, mpayClient, response) => {
290
- return mppResultFromPromise(
291
- surface3,
292
- mpayClient.createCredential(response),
293
- (error) => ({
294
- cause: "create_mpp_credential",
295
- message: error instanceof Error ? error.message : "Failed to create MPP credential"
296
- })
297
- );
298
- };
299
- var safeGetMppReceipt = (surface3, response) => {
300
- return mppResultFromThrowable(
301
- surface3,
302
- () => Receipt.fromResponse(response),
303
- (error) => ({
304
- cause: "parse_mpp_receipt",
305
- message: error instanceof Error ? error.message : "Failed to parse MPP receipt from response"
306
- })
307
- );
308
- };
309
-
310
- // src/server/tools/x402-fetch.ts
245
+ // src/server/tools/fetch.ts
311
246
  var toolName = "fetch";
312
247
  var fetchInputSchema = requestSchema.extend({
313
248
  paymentMethod: z.enum(["x402", "mpp", "auto"]).default("auto").optional().describe("Payment protocol to use. Defaults to auto-detect.")
314
249
  });
315
- var registerFetchX402ResourceTool = ({
250
+ var registerFetchTool = ({
316
251
  server,
317
252
  account,
318
253
  flags,
@@ -322,7 +257,7 @@ var registerFetchX402ResourceTool = ({
322
257
  toolName,
323
258
  {
324
259
  title: "Fetch",
325
- description: `HTTP fetch with automatic x402 payment. Detects 402 responses, signs payment, retries with payment headers. Returns response data + payment details (price, tx hash) if paid. Check balance with get_wallet_info first.`,
260
+ description: `HTTP fetch with automatic payment. Detects 402 responses, signs payment, retries with payment headers. Returns response data + payment details (price, tx hash) if paid. Check balance with get_wallet_info first.`,
326
261
  inputSchema: fetchInputSchema,
327
262
  annotations: {
328
263
  readOnlyHint: true,
@@ -338,28 +273,37 @@ var registerFetchX402ResourceTool = ({
338
273
  { network: DEFAULT_NETWORK, client: new ExactEvmScheme(account) }
339
274
  ]
340
275
  });
341
- coreClient.onBeforePaymentCreation(async ({ selectedRequirements }) => {
342
- const amount = tokenStringToNumber(selectedRequirements.amount);
343
- await checkBalance({
344
- surface: toolName,
345
- server,
346
- address: account.address,
347
- amountNeeded: amount,
348
- message: (balance) => `This request costs ${amount} USDC. Your current balance is ${balance} USDC.`,
349
- flags
350
- });
351
- });
352
276
  const x402HttpClient = new x402HTTPClient(coreClient);
353
- const tempoChainId = getTempoChainId();
354
- const tempoRpcUrl = getTempoRpcUrl();
355
277
  const mpayClient = Mpay.create({
356
278
  methods: [
357
- tempo({
279
+ tempoMethod({
358
280
  account,
359
- rpcUrl: { [tempoChainId]: tempoRpcUrl }
281
+ rpcUrl: { [tempo.id]: TEMPO_RPC_URL }
360
282
  })
361
283
  ]
362
284
  });
285
+ const beforePayment = async (ctx) => {
286
+ if (ctx.protocol === "x402") {
287
+ await checkBalance({
288
+ surface: toolName,
289
+ server,
290
+ address: account.address,
291
+ amountNeeded: ctx.amount,
292
+ message: (balance) => `This request costs ${ctx.amount} USDC. Your current balance is ${balance} USDC.`,
293
+ flags
294
+ });
295
+ } else {
296
+ await checkTempoBalance({
297
+ surface: toolName,
298
+ server,
299
+ address: account.address,
300
+ tokenAddress: ctx.currency,
301
+ amountNeeded: ctx.amount,
302
+ decimals: 6,
303
+ message: (balance) => `This request costs ${ctx.amount} tokens. Your current Tempo balance is ${balance}.`
304
+ });
305
+ }
306
+ };
363
307
  const provider = flags.provider ?? account.address;
364
308
  const request = buildRequest({
365
309
  input,
@@ -367,13 +311,13 @@ var registerFetchX402ResourceTool = ({
367
311
  sessionId,
368
312
  provider
369
313
  });
370
- const fetchResult = await safeWrapFetchWithPayment({
371
- x402HttpClient,
372
- mpayClient,
314
+ const fetchResult = await createFetchWithPayment({
315
+ surface: toolName,
316
+ clients: { x402: x402HttpClient, mpp: mpayClient },
373
317
  paymentMethod,
374
318
  account,
375
- server,
376
- flags
319
+ flags,
320
+ beforePayment
377
321
  })(request);
378
322
  if (fetchResult.isErr()) {
379
323
  return mcpError(fetchResult);
@@ -388,209 +332,11 @@ var registerFetchX402ResourceTool = ({
388
332
  }
389
333
  return mcpSuccessResponse(
390
334
  parseResponseResult.value,
391
- paymentInfo ?? void 0
335
+ paymentInfo
392
336
  );
393
337
  }
394
338
  );
395
339
  };
396
- function safeWrapFetchWithPayment(config) {
397
- const { x402HttpClient, paymentMethod } = config;
398
- return async (request) => {
399
- const clonedRequest = request.clone();
400
- const fallbackRequest = request.clone();
401
- const probeResult = await safeFetch(toolName, request);
402
- if (probeResult.isErr()) {
403
- return fetchErr(toolName, probeResult.error);
404
- }
405
- if (probeResult.value.status !== 402) {
406
- return probeResult.andThen(
407
- (response2) => fetchOk({ response: response2, paymentInfo: null })
408
- );
409
- }
410
- const response = probeResult.value;
411
- if (paymentMethod !== "auto") {
412
- if (paymentMethod === "mpp") {
413
- return handleMppPayment(response, clonedRequest, config);
414
- }
415
- return handleX402Payment(response, clonedRequest, x402HttpClient);
416
- }
417
- const available = detectPaymentProtocols(response);
418
- let preferred;
419
- if (available.length === 1) {
420
- preferred = available[0];
421
- } else {
422
- preferred = await pickByBalance(response, config);
423
- }
424
- const fallback = available.length > 1 ? preferred === "mpp" ? "x402" : "mpp" : null;
425
- const result = preferred === "mpp" ? await handleMppPayment(response, clonedRequest, config) : await handleX402Payment(response, clonedRequest, x402HttpClient);
426
- if (result.isErr() && fallback) {
427
- return fallback === "mpp" ? handleMppPayment(response, fallbackRequest, config) : handleX402Payment(response, fallbackRequest, x402HttpClient);
428
- }
429
- return result;
430
- };
431
- }
432
- async function pickByBalance(response, config) {
433
- const { account, flags } = config;
434
- const x402BalanceResult = await resultFromPromise(
435
- "balance",
436
- toolName,
437
- getBalance({
438
- address: account.address,
439
- flags,
440
- surface: toolName
441
- }).then((r) => r.isOk() ? r.value.balance : 0),
442
- () => ({
443
- cause: "x402_balance",
444
- message: "Failed to get x402 balance"
445
- })
446
- );
447
- if (x402BalanceResult.isErr()) {
448
- log.debug("Balance comparison failed, defaulting to mpp");
449
- return "mpp";
450
- }
451
- const x402Balance = x402BalanceResult.value;
452
- let mppBalance = 0;
453
- const challengeResult = safeGetMppChallenge(toolName, response);
454
- if (challengeResult.isOk()) {
455
- const currency = challengeResult.value.request.currency;
456
- const decimals = challengeResult.value.request.decimals ?? 6;
457
- if (currency) {
458
- const tempoResult = await resultFromPromise(
459
- "tempo",
460
- toolName,
461
- getTempoBalance({
462
- address: account.address,
463
- tokenAddress: currency
464
- }),
465
- () => ({
466
- cause: "tempo_balance",
467
- message: "Tempo balance check failed"
468
- })
469
- );
470
- if (tempoResult.isOk()) {
471
- mppBalance = Number(formatUnits2(tempoResult.value.balance, decimals));
472
- }
473
- }
474
- }
475
- log.info(`Protocol selection \u2014 x402: $${x402Balance}, mpp: $${mppBalance}`);
476
- return x402Balance >= mppBalance ? "x402" : "mpp";
477
- }
478
- async function handleX402Payment(response, clonedRequest, client) {
479
- const paymentRequiredResult = await safeGetPaymentRequired(
480
- toolName,
481
- client,
482
- response
483
- );
484
- if (paymentRequiredResult.isErr()) {
485
- return paymentRequiredResult;
486
- }
487
- const paymentRequired = paymentRequiredResult.value;
488
- const paymentPayloadResult = await safeCreatePaymentPayload(
489
- toolName,
490
- client,
491
- paymentRequired
492
- );
493
- if (paymentPayloadResult.isErr()) {
494
- return paymentPayloadResult;
495
- }
496
- const paymentPayload = paymentPayloadResult.value;
497
- const paymentHeaders = client.encodePaymentSignatureHeader(paymentPayload);
498
- if (clonedRequest.headers.has("PAYMENT-SIGNATURE") || clonedRequest.headers.has("X-PAYMENT")) {
499
- return x402Err(toolName, {
500
- cause: "payment_already_attempted",
501
- message: "Payment already attempted"
502
- });
503
- }
504
- for (const [key, value] of Object.entries(paymentHeaders)) {
505
- clonedRequest.headers.set(key, value);
506
- }
507
- clonedRequest.headers.set(
508
- "Access-Control-Expose-Headers",
509
- "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
510
- );
511
- return await safeFetch(toolName, clonedRequest).andThen((paidResponse) => {
512
- const settlementResult = safeGetPaymentSettlement(
513
- toolName,
514
- client,
515
- paidResponse
516
- );
517
- return x402Ok({
518
- response: paidResponse,
519
- paymentInfo: {
520
- price: tokenStringToNumber(
521
- paymentPayload.accepted.amount
522
- ).toLocaleString("en-US", {
523
- style: "currency",
524
- currency: "USD"
525
- }),
526
- ...settlementResult.isOk() ? {
527
- payment: {
528
- success: settlementResult.value.success,
529
- transactionHash: settlementResult.value.transaction
530
- }
531
- } : {}
532
- }
533
- });
534
- });
535
- }
536
- async function handleMppPayment(response, clonedRequest, config) {
537
- const { mpayClient, account, server } = config;
538
- if (clonedRequest.headers.has("Authorization")) {
539
- return mppErr(toolName, {
540
- cause: "mpp_payment_already_attempted",
541
- message: "MPP payment already attempted"
542
- });
543
- }
544
- const challengeResult = safeGetMppChallenge(toolName, response);
545
- if (challengeResult.isErr()) {
546
- return challengeResult;
547
- }
548
- const challenge = challengeResult.value;
549
- const amount = challenge.request.amount;
550
- const decimals = challenge.request.decimals ?? 6;
551
- const currency = challenge.request.currency;
552
- if (amount && currency) {
553
- const numericAmount = Number(formatUnits2(BigInt(amount), decimals));
554
- await checkTempoBalance({
555
- surface: toolName,
556
- server,
557
- address: account.address,
558
- tokenAddress: currency,
559
- amountNeeded: numericAmount,
560
- decimals,
561
- message: (balance) => `This request costs ${numericAmount} tokens. Your current Tempo balance is ${balance}.`
562
- });
563
- }
564
- const credentialResult = await safeCreateMppCredential(
565
- toolName,
566
- mpayClient,
567
- response
568
- );
569
- if (credentialResult.isErr()) {
570
- return credentialResult;
571
- }
572
- const credential = credentialResult.value;
573
- clonedRequest.headers.set("Authorization", credential);
574
- return await safeFetch(toolName, clonedRequest).andThen((paidResponse) => {
575
- const receiptResult = safeGetMppReceipt(toolName, paidResponse);
576
- const priceDisplay = amount ? Number(formatUnits2(BigInt(amount), decimals)).toLocaleString("en-US", {
577
- style: "currency",
578
- currency: "USD"
579
- }) : void 0;
580
- return mppOk({
581
- response: paidResponse,
582
- paymentInfo: {
583
- ...priceDisplay ? { price: priceDisplay } : {},
584
- ...receiptResult.isOk() ? {
585
- payment: {
586
- success: true,
587
- transactionHash: receiptResult.value.reference
588
- }
589
- } : {}
590
- }
591
- });
592
- });
593
- }
594
340
 
595
341
  // src/server/tools/auth-fetch.ts
596
342
  import { x402Client as x402Client2, x402HTTPClient as x402HTTPClient2 } from "@x402/core/client";
@@ -648,8 +394,8 @@ var registerAuthTools = ({
648
394
  const paymentRequired = getPaymentRequiredResult.value;
649
395
  const siwxExtension = getSiwxExtension(paymentRequired.extensions);
650
396
  if (!siwxExtension) {
651
- return mcpErrorJson({
652
- message: "Endpoint returned 402 but no sign-in-with-x extension found",
397
+ return mcpSuccessJson({
398
+ error: "Endpoint returned 402 but no sign-in-with-x extension found",
653
399
  statusCode: 402,
654
400
  extensions: Object.keys(paymentRequired.extensions ?? {}),
655
401
  hint: "This endpoint may require payment instead of authentication. Use execute_call for paid requests."
@@ -692,7 +438,6 @@ var registerAuthTools = ({
692
438
 
693
439
  // src/server/tools/wallet.ts
694
440
  import { z as z2 } from "zod";
695
- import { formatUnits as formatUnits3 } from "viem";
696
441
  var chainBalanceSchema = z2.object({
697
442
  chain: z2.string().describe("Chain name"),
698
443
  balance: z2.number().describe("USDC balance on this chain")
@@ -723,43 +468,34 @@ var registerWalletTools = ({
723
468
  }
724
469
  },
725
470
  async () => {
726
- const [balanceResult, tempoResult] = await Promise.all([
727
- getBalance({
728
- address,
729
- flags,
730
- surface: "get_wallet_info"
731
- }),
732
- getTempoBalance({ address, tokenAddress: getTempoTokenAddress() }).then((r) => Number(formatUnits3(r.balance, 6))).catch((e) => {
733
- log.debug(`Failed to fetch Tempo balance: ${e}`);
734
- return null;
735
- })
736
- ]);
737
- if (balanceResult.isErr()) {
738
- return mcpError(balanceResult);
471
+ const result = await getWalletInfo("get_wallet_info", address, flags);
472
+ if (result.isErr()) {
473
+ return mcpError(result);
739
474
  }
740
- const baseBalance = balanceResult.value.balance;
741
- const tempoBalance = tempoResult ?? 0;
742
- const totalBalance = baseBalance + tempoBalance;
743
- const chains = [
744
- { chain: "Base", balance: baseBalance },
745
- { chain: "Tempo", balance: tempoBalance }
746
- ];
747
475
  return mcpSuccessStructuredJson({
748
- address,
749
- balance: totalBalance,
750
- chains,
751
- isNewWallet: totalBalance === 0,
752
- depositLink: getDepositLink(address, flags),
753
- ...totalBalance < 2.5 && totalBalance > 0 ? { message: "Your balance is low. Consider topping it up" } : {}
476
+ address: result.value.address,
477
+ balance: result.value.balance,
478
+ chains: result.value.chains.map((c) => ({ ...c })),
479
+ isNewWallet: result.value.isNewWallet,
480
+ depositLink: result.value.depositLink,
481
+ ...result.value.message ? { message: result.value.message } : {}
754
482
  });
755
483
  }
756
484
  );
757
485
  };
758
486
 
759
487
  // src/server/tools/check-endpoint.ts
760
- import { x402Client as x402Client3, x402HTTPClient as x402HTTPClient3 } from "@x402/core/client";
488
+ import z3 from "zod";
761
489
  var toolName3 = "check_endpoint_schema";
762
- var registerCheckX402EndpointTool = ({
490
+ var checkEndpointInputSchema = z3.object({
491
+ url: z3.url().describe("The endpoint URL"),
492
+ method: z3.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).optional().describe(
493
+ "HTTP method to check. If omitted, all methods are probed in parallel."
494
+ ),
495
+ body: z3.unknown().optional().describe("Request body for POST/PUT/PATCH methods"),
496
+ headers: z3.record(z3.string(), z3.string()).optional().describe("Additional headers to include").default({})
497
+ });
498
+ var registerCheckEndpointTool = ({
763
499
  server,
764
500
  account,
765
501
  sessionId
@@ -768,8 +504,8 @@ var registerCheckX402EndpointTool = ({
768
504
  toolName3,
769
505
  {
770
506
  title: "Check Endpoint Schema",
771
- description: `Probe endpoint to check if x402-protected. Returns pricing, input schema, payment methods. Use before fetch to preview costs. No payment made.`,
772
- inputSchema: requestSchema,
507
+ description: `Probe endpoint to check if payment-protected. By default checks only the HTTP methods declared in the endpoint's OpenAPI spec (falls back to all methods if no spec is available). Returns pricing, input schema, and payment methods for each method that responds with 402 or 2xx. Use before fetch to preview costs. No payment made.`,
508
+ inputSchema: checkEndpointInputSchema,
773
509
  annotations: {
774
510
  readOnlyHint: true,
775
511
  destructiveHint: false,
@@ -779,124 +515,31 @@ var registerCheckX402EndpointTool = ({
779
515
  },
780
516
  async (input) => {
781
517
  log.info("Querying endpoint", input);
782
- const cachedSchemaResult = await resultFromPromise(
783
- "openapi",
784
- toolName3,
785
- getEndpointSchema(input.url, input.method),
786
- (e) => ({
787
- cause: "cache_lookup",
788
- message: e instanceof Error ? e.message : String(e)
789
- })
790
- );
791
- if (cachedSchemaResult.isErr()) {
792
- log.debug(
793
- `Cache lookup failed for ${input.url}, falling back to 402 probe`
794
- );
795
- } else if (cachedSchemaResult.value) {
796
- const cachedSchema = cachedSchemaResult.value;
797
- const origin = new URL(input.url).origin;
798
- const path = new URL(input.url).pathname || "/";
799
- const method = (input.method ?? "POST").toUpperCase();
800
- const indexEntry = getIndexEntry(origin, path, method);
518
+ const { url, results } = await checkEndpoint({
519
+ surface: toolName3,
520
+ url: input.url,
521
+ methods: input.method ? [input.method] : void 0,
522
+ body: input.body,
523
+ headers: {
524
+ ...input.headers,
525
+ "X-Wallet-Address": account.address,
526
+ ...sessionId ? { "X-Session-ID": sessionId } : {}
527
+ },
528
+ includeMethodErrors: !!input.method
529
+ });
530
+ if (results.length === 0) {
801
531
  return mcpSuccessJson({
802
- source: "openapi",
803
- requiresPayment: true,
804
- schema: cachedSchema,
805
- ...indexEntry?.price ? { estimatedPrice: indexEntry.price } : {},
806
- ...indexEntry?.protocols ? { protocols: indexEntry.protocols } : {},
807
- ...indexEntry?.summary ? { summary: indexEntry.summary } : {}
532
+ message: "No methods returned 402 or 2xx for this endpoint.",
533
+ url
808
534
  });
809
535
  }
810
- const responseResult = await safeFetch(
811
- toolName3,
812
- buildRequest({ input, address: account.address, sessionId })
813
- );
814
- if (responseResult.isErr()) {
815
- return mcpError(responseResult);
816
- }
817
- const response = responseResult.value;
818
- if (response.status !== 402) {
819
- if (!response.ok) {
820
- return mcpErrorFetch(toolName3, response);
821
- }
822
- const parseResponseResult = await safeParseResponse(toolName3, response);
823
- if (parseResponseResult.isErr()) {
824
- return mcpError(parseResponseResult);
825
- }
826
- return mcpSuccessResponse(parseResponseResult.value, {
827
- requiresPayment: false
828
- });
829
- }
830
- const protocols = detectPaymentProtocols(response);
831
- const paymentMethods = [];
832
- if (protocols.includes("mpp")) {
833
- const challengeResult = safeGetMppChallenge(toolName3, response);
834
- if (challengeResult.isOk()) {
835
- const challenge = challengeResult.value;
836
- const currency = challenge.request.currency;
837
- const amount = challenge.request.amount;
838
- const decimals = challenge.request.decimals ?? 6;
839
- let schema;
840
- const endpointSchemaResult = await resultFromPromise(
841
- "openapi",
842
- toolName3,
843
- getEndpointSchema(input.url, input.method),
844
- (e) => ({
845
- cause: "schema_fetch",
846
- message: e instanceof Error ? e.message : String(e)
847
- })
848
- );
849
- if (endpointSchemaResult.isOk() && endpointSchemaResult.value) {
850
- schema = endpointSchemaResult.value;
851
- } else if (endpointSchemaResult.isErr()) {
852
- log.debug(`Failed to fetch OpenAPI schema for: ${input.url}`);
853
- }
854
- paymentMethods.push({
855
- protocol: "mpp",
856
- method: challenge.method,
857
- intent: challenge.intent,
858
- realm: challenge.realm,
859
- ...challenge.description ? { description: challenge.description } : {},
860
- ...amount ? { price: tokenStringToNumber(amount, decimals) } : {},
861
- ...currency ? { currency } : {},
862
- ...schema ? { schema } : {},
863
- network: `tempo:${challenge.method}`
864
- });
865
- }
866
- }
867
- if (protocols.includes("x402")) {
868
- const client = new x402HTTPClient3(new x402Client3());
869
- const paymentRequiredResult = await safeGetPaymentRequired(
870
- toolName3,
871
- client,
872
- response
873
- );
874
- if (paymentRequiredResult.isOk()) {
875
- const { resource, extensions, accepts } = paymentRequiredResult.value;
876
- for (const accept of accepts) {
877
- paymentMethods.push({
878
- protocol: "x402",
879
- ...resource,
880
- schema: getInputSchema(extensions),
881
- price: tokenStringToNumber(accept.amount),
882
- network: accept.network,
883
- asset: accept.asset
884
- });
885
- }
886
- }
887
- }
888
- return mcpSuccessJson({
889
- requiresPayment: true,
890
- protocols,
891
- statusCode: response.status,
892
- paymentMethods
893
- });
536
+ return mcpSuccessJson(toJsonObject({ url, results }));
894
537
  }
895
538
  );
896
539
  };
897
540
 
898
541
  // src/server/tools/redeem-invite.ts
899
- import z3 from "zod";
542
+ import z4 from "zod";
900
543
  var registerRedeemInviteTool = ({
901
544
  server,
902
545
  account: { address },
@@ -907,13 +550,13 @@ var registerRedeemInviteTool = ({
907
550
  {
908
551
  title: "Redeem Invite",
909
552
  description: `Redeem an invite code for free USDC on Base. One-time use per code. Returns amount received and transaction hash. Use get_wallet_info after to verify balance.`,
910
- inputSchema: z3.object({
911
- code: z3.string().min(1).describe("The invite code")
553
+ inputSchema: z4.object({
554
+ code: z4.string().min(1).describe("The invite code")
912
555
  }),
913
- outputSchema: z3.object({
914
- redeemed: z3.literal(true),
915
- amount: z3.string().describe('Amount with unit (e.g., "5 USDC")'),
916
- txHash: z3.string().describe("Transaction hash on Base")
556
+ outputSchema: z4.object({
557
+ redeemed: z4.literal(true),
558
+ amount: z4.string().describe('Amount with unit (e.g., "5 USDC")'),
559
+ txHash: z4.string().describe("Transaction hash on Base")
917
560
  }),
918
561
  annotations: {
919
562
  readOnlyHint: false,
@@ -946,7 +589,7 @@ var registerRedeemInviteTool = ({
946
589
  };
947
590
 
948
591
  // src/server/tools/telemetry.ts
949
- import z4 from "zod";
592
+ import z5 from "zod";
950
593
  var toolName4 = "report_error";
951
594
  var registerTelemetryTools = ({
952
595
  server,
@@ -958,18 +601,18 @@ var registerTelemetryTools = ({
958
601
  {
959
602
  title: "Report Error",
960
603
  description: "EMERGENCY ONLY. Report critical MCP tool bugs. Do NOT use for normal errors (balance, network, 4xx) - those are recoverable.",
961
- inputSchema: z4.object({
962
- tool: z4.string().describe("MCP tool name"),
963
- resource: z4.string().optional().describe("x402 resource URL"),
964
- summary: z4.string().describe("1-2 sentence summary"),
965
- errorMessage: z4.string().describe("Error message"),
966
- stack: z4.string().optional().describe("Stack trace"),
967
- fullReport: z4.string().optional().describe("Detailed report with context, logs, repro steps")
604
+ inputSchema: z5.object({
605
+ tool: z5.string().describe("MCP tool name"),
606
+ resource: z5.string().optional().describe("Resource URL"),
607
+ summary: z5.string().describe("1-2 sentence summary"),
608
+ errorMessage: z5.string().describe("Error message"),
609
+ stack: z5.string().optional().describe("Stack trace"),
610
+ fullReport: z5.string().optional().describe("Detailed report with context, logs, repro steps")
968
611
  }),
969
- outputSchema: z4.object({
970
- submitted: z4.literal(true),
971
- reportId: z4.string().describe("Unique report ID for tracking"),
972
- message: z4.string().describe("Confirmation message")
612
+ outputSchema: z5.object({
613
+ submitted: z5.literal(true),
614
+ reportId: z5.string().describe("Unique report ID for tracking"),
615
+ message: z5.string().describe("Confirmation message")
973
616
  }),
974
617
  annotations: {
975
618
  readOnlyHint: false,
@@ -1014,7 +657,7 @@ var registerTelemetryTools = ({
1014
657
  };
1015
658
 
1016
659
  // src/server/tools/discover-resources.ts
1017
- import { z as z5 } from "zod";
660
+ import { z as z6 } from "zod";
1018
661
 
1019
662
  // src/shared/origins.ts
1020
663
  var ORIGINS = [
@@ -1029,37 +672,6 @@ var ORIGINS = [
1029
672
  "https://x402facilitator.com" /* X402Facilitator */
1030
673
  ];
1031
674
 
1032
- // src/server/tools/lib/discovery/openapi.strategy.ts
1033
- async function fetchLlmsTxt(origin, toolName6) {
1034
- const llmsTxtUrl = `${origin}/llms.txt`;
1035
- log.debug(`[openapi] Fetching llms.txt from: ${llmsTxtUrl}`);
1036
- const result = await safeFetch(
1037
- toolName6,
1038
- new Request(llmsTxtUrl, { headers: { Accept: "text/plain" } })
1039
- );
1040
- if (result.isErr()) return null;
1041
- const parseResult = await safeParseResponse(toolName6, result.value);
1042
- if (parseResult.isErr() || parseResult.value.type !== "text") return null;
1043
- return parseResult.value.data;
1044
- }
1045
- async function openapiStrategy(ctx) {
1046
- const { origin, toolName: toolName6 } = ctx;
1047
- log.debug(`[openapi] Trying OpenAPI spec for: ${origin}`);
1048
- const [spec, instructions] = await Promise.all([
1049
- fetchOpenApiSpec(origin),
1050
- fetchLlmsTxt(origin, toolName6)
1051
- ]);
1052
- if (!spec?.paths) return null;
1053
- const endpoints = await getOriginIndex(origin);
1054
- if (!endpoints || endpoints.length === 0) return null;
1055
- log.info(`[openapi] Found ${endpoints.length} endpoints for: ${origin}`);
1056
- return {
1057
- source: "openapi",
1058
- endpoints,
1059
- ...instructions ? { instructions } : {}
1060
- };
1061
- }
1062
-
1063
675
  // src/server/tools/discover-resources.ts
1064
676
  var toolName5 = "discover_api_endpoints";
1065
677
  function registerDiscoveryTools(server) {
@@ -1067,8 +679,8 @@ function registerDiscoveryTools(server) {
1067
679
  toolName5,
1068
680
  {
1069
681
  title: "Discover API Endpoints",
1070
- description: `Find x402-protected resources on an origin. Returns a list of resource URLs.
1071
- Use check_x402_endpoint separately to get detailed pricing/schema info for specific resources.
682
+ description: `Find payment-protected resources on an origin. Returns a list of resource URLs.
683
+ Use check_endpoint_schema separately to get detailed pricing/schema info for specific resources.
1072
684
  Known default origins with resource packs. Discover if more needed:
1073
685
  - ${"https://enrichx402.com" /* EnrichX402 */} ->
1074
686
  People + Org search
@@ -1086,8 +698,8 @@ function registerDiscoveryTools(server) {
1086
698
  - ${"https://agentupload.dev" /* AgentUpload */} -> upload and share files with others.
1087
699
  - ${"https://x402email.com" /* X402Email */} -> send emails.
1088
700
  `,
1089
- inputSchema: z5.object({
1090
- url: z5.url().describe(
701
+ inputSchema: z6.object({
702
+ url: z6.url().describe(
1091
703
  "The origin URL or any URL on the origin to discover resources from"
1092
704
  )
1093
705
  }),
@@ -1099,11 +711,20 @@ function registerDiscoveryTools(server) {
1099
711
  }
1100
712
  },
1101
713
  async ({ url }) => {
1102
- const origin = URL.canParse(url) ? new URL(url).origin : url;
1103
- const hostname = URL.canParse(origin) ? new URL(origin).hostname : origin;
1104
- log.info(`Discovering resources for origin: ${origin}`);
1105
- const ctx = { origin, hostname, toolName: toolName5 };
1106
- const result = await openapiStrategy(ctx);
714
+ log.info(`Discovering resources for: ${url}`);
715
+ const discoverResult = await resultFromPromise(
716
+ "discover",
717
+ toolName5,
718
+ discoverResources(toolName5, url),
719
+ (e) => ({
720
+ cause: "discover",
721
+ message: e instanceof Error ? e.message : String(e)
722
+ })
723
+ );
724
+ if (discoverResult.isErr()) {
725
+ return mcpError(discoverResult);
726
+ }
727
+ const result = discoverResult.value;
1107
728
  if (result) {
1108
729
  const endpoints = result.endpoints.map(
1109
730
  ({ path, summary, price }) => ({
@@ -1114,12 +735,13 @@ function registerDiscoveryTools(server) {
1114
735
  );
1115
736
  return mcpSuccessJson({
1116
737
  found: true,
1117
- origin,
738
+ origin: result.origin,
1118
739
  endpoints,
1119
740
  ...result.instructions ? { instructions: result.instructions } : {}
1120
741
  });
1121
742
  }
1122
- return mcpErrorJson({
743
+ const origin = URL.canParse(url) ? new URL(url).origin : url;
744
+ return mcpSuccessJson({
1123
745
  found: false,
1124
746
  origin,
1125
747
  error: "No OpenAPI spec found. Tried: /openapi.json, /.well-known/openapi.json, /.well-known/x402, /.well-known/mpp"
@@ -1129,9 +751,9 @@ function registerDiscoveryTools(server) {
1129
751
  }
1130
752
 
1131
753
  // src/server/resources/origins.ts
1132
- import z6 from "zod";
1133
- import { x402HTTPClient as x402HTTPClient4 } from "@x402/core/client";
1134
- import { x402Client as x402Client4 } from "@x402/core/client";
754
+ import z7 from "zod";
755
+ import { x402HTTPClient as x402HTTPClient3 } from "@x402/core/client";
756
+ import { x402Client as x402Client3 } from "@x402/core/client";
1135
757
 
1136
758
  // src/server/resources/_lib.ts
1137
759
  var surface = "getWebPageMetadata";
@@ -1166,16 +788,16 @@ var parseMetadataFromResponse = (html) => {
1166
788
 
1167
789
  // src/server/resources/origins.ts
1168
790
  var surface2 = "registerOrigins";
1169
- var wellKnownResourceItem = z6.union([
1170
- z6.string(),
1171
- z6.object({
1172
- url: z6.string().optional(),
1173
- path: z6.string().optional(),
1174
- method: z6.string().optional()
791
+ var wellKnownResourceItem = z7.union([
792
+ z7.string(),
793
+ z7.object({
794
+ url: z7.string().optional(),
795
+ path: z7.string().optional(),
796
+ method: z7.string().optional()
1175
797
  }).passthrough()
1176
798
  ]);
1177
- var wellKnownSchema = z6.object({
1178
- resources: z6.array(wellKnownResourceItem)
799
+ var wellKnownSchema = z7.object({
800
+ resources: z7.array(wellKnownResourceItem)
1179
801
  });
1180
802
  var registerOrigins = async ({ server }) => {
1181
803
  await Promise.all(
@@ -1356,7 +978,7 @@ var getResourceResponse = async (resource, request) => {
1356
978
  }
1357
979
  }
1358
980
  if (protocols.includes("x402")) {
1359
- const client = new x402HTTPClient4(new x402Client4());
981
+ const client = new x402HTTPClient3(new x402Client3());
1360
982
  const paymentRequiredResult = await safeGetPaymentRequired(
1361
983
  surface2,
1362
984
  client,
@@ -1481,7 +1103,7 @@ var registerGettingStartedPrompt = ({ server }) => {
1481
1103
  };
1482
1104
 
1483
1105
  // src/server/prompts/enrich.ts
1484
- import { z as z7 } from "zod";
1106
+ import { z as z8 } from "zod";
1485
1107
  var PROMPT_CONTENT2 = `To start, you should check this resource page: ${"https://enrichx402.com" /* EnrichX402 */}/llms.txt, which has access to all of the paid endpoints.
1486
1108
 
1487
1109
  - You have access to the agentcash MCP server, which allows you to call paid endpoints which contain potentially extremely useful information.
@@ -1564,7 +1186,7 @@ var registerEnrichPrompt = ({ server }) => {
1564
1186
  title: "Enrich",
1565
1187
  description: "Use premium APIs to enrich data. Optionally provide a query, or let the assistant infer the best task from context.",
1566
1188
  argsSchema: {
1567
- query: z7.string().optional().describe(
1189
+ query: z8.string().optional().describe(
1568
1190
  "Optional: The user's query to enrich. If omitted, the assistant will infer the task from conversation context."
1569
1191
  )
1570
1192
  }
@@ -1602,7 +1224,7 @@ import { dirname, join } from "path";
1602
1224
  import { fileURLToPath } from "url";
1603
1225
  function getVersion() {
1604
1226
  if (true) {
1605
- return "0.3.4";
1227
+ return "0.3.6";
1606
1228
  }
1607
1229
  const __dirname2 = dirname(fileURLToPath(import.meta.url));
1608
1230
  const pkg = JSON.parse(
@@ -1701,10 +1323,10 @@ var startServer = async (flags) => {
1701
1323
  flags,
1702
1324
  sessionId
1703
1325
  };
1704
- registerFetchX402ResourceTool(props);
1326
+ registerFetchTool(props);
1705
1327
  registerAuthTools(props);
1706
1328
  registerWalletTools(props);
1707
- registerCheckX402EndpointTool(props);
1329
+ registerCheckEndpointTool(props);
1708
1330
  registerRedeemInviteTool(props);
1709
1331
  registerDiscoveryTools(server);
1710
1332
  registerTelemetryTools(props);
@@ -1723,4 +1345,4 @@ var startServer = async (flags) => {
1723
1345
  export {
1724
1346
  startServer
1725
1347
  };
1726
- //# sourceMappingURL=server-7D6YY3KG.js.map
1348
+ //# sourceMappingURL=server-WCNK52XR.js.map