@dcentralab/d402-client 0.3.4 → 0.3.7

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/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Account } from 'viem/accounts';
2
- import { PublicClient, WalletClient, Hash, Address } from 'viem';
2
+ import { WalletClient, PublicClient, Hash, Address } from 'viem';
3
3
 
4
4
  /**
5
5
  * Type definitions for D402 payment protocol
@@ -198,6 +198,11 @@ interface D402ClientConfig {
198
198
  * Typically from wagmi: `walletClient.account`
199
199
  */
200
200
  operatorAccount: Account;
201
+ /**
202
+ * Wallet client for signing (required for wagmi/browser use).
203
+ * This is needed because wagmi accounts don't have signTypedData directly.
204
+ */
205
+ walletClient?: WalletClient;
201
206
  /**
202
207
  * IATPWallet contract address.
203
208
  * Get from `createIATPWallet()` or `getWalletsByOwner()`.
@@ -267,6 +272,7 @@ interface D402ClientConfig {
267
272
  */
268
273
  declare class D402Client {
269
274
  private readonly operatorAccount;
275
+ private readonly walletClient?;
270
276
  private readonly iatpWalletAddress;
271
277
  private readonly maxValue?;
272
278
  private readonly paymentRequirementsSelector;
@@ -383,6 +389,45 @@ declare class D402Client {
383
389
  * ```
384
390
  */
385
391
  fetch(url: string, init?: RequestInit): Promise<Response>;
392
+ /**
393
+ * Call an MCP tool with automatic session initialization and payment handling.
394
+ *
395
+ * This is the simplest way to call an MCP tool. It handles:
396
+ * - MCP session initialization
397
+ * - JSON-RPC payload construction
398
+ * - HTTP 402 payment flow
399
+ * - SSE/JSON response parsing
400
+ *
401
+ * @param endpoint - MCP server endpoint URL
402
+ * @param toolName - Name of the tool to call
403
+ * @param input - Tool arguments
404
+ * @param options - Optional configuration
405
+ * @returns The tool's result data
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * const client = new D402Client({
410
+ * operatorAccount: walletClient.account,
411
+ * walletClient,
412
+ * iatpWalletAddress,
413
+ * })
414
+ *
415
+ * // Simple one-liner!
416
+ * const result = await client.mcpCall(
417
+ * 'https://my-mcp.example.com/mcp',
418
+ * 'google_search',
419
+ * { q: 'test search' }
420
+ * )
421
+ *
422
+ * console.log(result) // { searchResults: [...] }
423
+ * ```
424
+ */
425
+ mcpCall(endpoint: string, toolName: string, input: Record<string, unknown>, options?: {
426
+ /** Skip session initialization (for stateless servers) */
427
+ skipInit?: boolean;
428
+ /** Custom JSON-RPC request ID */
429
+ requestId?: string | number;
430
+ }): Promise<unknown>;
386
431
  }
387
432
 
388
433
  /**
@@ -399,6 +444,7 @@ declare class D402Client {
399
444
  *
400
445
  * @param params - Signing parameters
401
446
  * @param params.operatorAccount - User's account for signing (from wagmi walletClient)
447
+ * @param params.walletClient - Optional wallet client for signing (wagmi). If provided, uses walletClient.signTypedData
402
448
  * @param params.paymentRequirement - Payment requirements from 402 response
403
449
  * @param params.iatpWalletAddress - IATPWallet contract address (optional)
404
450
  * @param params.requestPath - API request path (optional, uses payment_requirements.resource if not provided)
@@ -412,6 +458,7 @@ declare class D402Client {
412
458
  * // User signs payment (MetaMask popup appears)
413
459
  * const signedPayment = await signD402Payment({
414
460
  * operatorAccount: walletClient.account, // User's wallet
461
+ * walletClient: walletClient, // For signing with wagmi
415
462
  * paymentRequirement: requirement,
416
463
  * iatpWalletAddress: '0xUserIATPWallet...'
417
464
  * })
@@ -422,8 +469,9 @@ declare class D402Client {
422
469
  */
423
470
  declare function signD402Payment(params: {
424
471
  operatorAccount: Account;
472
+ walletClient?: WalletClient;
425
473
  paymentRequirement: PaymentRequirement;
426
- iatpWalletAddress?: `0x${string}`;
474
+ iatpWalletAddress: `0x${string}`;
427
475
  requestPath?: string;
428
476
  d402Version?: number;
429
477
  }): Promise<SignedPayment>;
@@ -613,6 +661,7 @@ interface WithdrawalRequest {
613
661
  */
614
662
  declare function createIATPWallet(params: {
615
663
  ownerAccount: Account;
664
+ walletClient?: WalletClient;
616
665
  network?: 'sepolia';
617
666
  rpcUrl?: string;
618
667
  }): Promise<WalletCreationResult>;
@@ -821,6 +870,109 @@ declare function executeWithdrawal(params: {
821
870
  network?: 'sepolia';
822
871
  }): Promise<Hash>;
823
872
 
873
+ /**
874
+ * MCP Session Management
875
+ *
876
+ * Handles MCP protocol session initialization.
877
+ */
878
+ /**
879
+ * Initialize an MCP session with the server.
880
+ *
881
+ * Sends the `initialize` JSON-RPC method to establish a session.
882
+ * Some servers return a session ID in headers, others are stateless.
883
+ *
884
+ * @param endpoint - MCP server endpoint URL
885
+ * @returns Session ID if provided by server, null otherwise
886
+ */
887
+ declare function initMcpSession(endpoint: string): Promise<string | null>;
888
+
889
+ /**
890
+ * MCP Payload Builder
891
+ *
892
+ * Constructs JSON-RPC payloads for MCP tool calls.
893
+ */
894
+ interface JsonRpcPayload {
895
+ jsonrpc: '2.0';
896
+ id: string | number;
897
+ method: string;
898
+ params: {
899
+ name: string;
900
+ arguments: Record<string, unknown>;
901
+ };
902
+ }
903
+ /**
904
+ * Build a JSON-RPC payload for an MCP tool call.
905
+ *
906
+ * @param toolName - Name of the MCP tool to call
907
+ * @param args - Tool arguments
908
+ * @param requestId - Optional custom request ID (default: 1)
909
+ * @returns Complete JSON-RPC payload ready to send
910
+ *
911
+ * @example
912
+ * ```ts
913
+ * const payload = buildToolCallPayload('google_search', { q: 'test' })
914
+ * // { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'google_search', arguments: { q: 'test' } } }
915
+ * ```
916
+ */
917
+ declare function buildToolCallPayload(toolName: string, args: Record<string, unknown>, requestId?: string | number): JsonRpcPayload;
918
+ /**
919
+ * Build headers for an MCP request.
920
+ *
921
+ * @param sessionId - Optional MCP session ID
922
+ * @returns Headers object for fetch
923
+ */
924
+ declare function buildMcpHeaders(sessionId?: string | null): Record<string, string>;
925
+
926
+ /**
927
+ * MCP Response Parser
928
+ *
929
+ * Handles parsing of MCP responses in both JSON and SSE formats.
930
+ */
931
+ interface McpToolResult {
932
+ /** Whether the tool call was successful */
933
+ isError: boolean;
934
+ /** The tool's output content */
935
+ content: Array<{
936
+ type: string;
937
+ text?: string;
938
+ [key: string]: unknown;
939
+ }>;
940
+ /** Structured content if available */
941
+ structuredContent?: unknown;
942
+ }
943
+ interface ParsedMcpResponse {
944
+ /** JSON-RPC response ID */
945
+ id: string | number;
946
+ /** The tool result */
947
+ result: McpToolResult | unknown;
948
+ /** Error if the call failed */
949
+ error?: {
950
+ code: number;
951
+ message: string;
952
+ data?: unknown;
953
+ };
954
+ }
955
+ /**
956
+ * Parse an MCP response, handling both SSE and JSON formats.
957
+ *
958
+ * MCP servers may return responses as:
959
+ * - `application/json`: Standard JSON response
960
+ * - `text/event-stream`: Server-Sent Events with `data: {...}` format
961
+ *
962
+ * @param response - Fetch Response object
963
+ * @returns Parsed response data
964
+ */
965
+ declare function parseMcpResponse(response: Response): Promise<ParsedMcpResponse>;
966
+ /**
967
+ * Extract the tool result from an MCP response.
968
+ *
969
+ * Handles the nested structure and returns just the useful data.
970
+ *
971
+ * @param response - Parsed MCP response
972
+ * @returns The tool's result data
973
+ */
974
+ declare function extractToolResult(response: ParsedMcpResponse): unknown;
975
+
824
976
  /**
825
977
  * IATPSettlementLayer query functions
826
978
  */
@@ -1172,4 +1324,4 @@ declare class UnsupportedNetworkError extends PaymentError {
1172
1324
  constructor(network: string);
1173
1325
  }
1174
1326
 
1175
- export { ContractName, D402Client, type D402ClientConfig, type D402Response, type EIP712Domain, Invalid402ResponseError, MissingRequestConfigError, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, type WithdrawalRequest, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, executeWithdrawal, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChainId, getContractAbi, getContractAddress, getContractConfig, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, getWithdrawalRequest, isValidAddress, normalizeAddress, parseAllPaymentRequirements, parseMoney, parsePaymentRequirement, requestWithdrawal, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };
1327
+ export { ContractName, D402Client, type D402ClientConfig, type D402Response, type EIP712Domain, Invalid402ResponseError, type JsonRpcPayload, type McpToolResult, MissingRequestConfigError, type ParsedMcpResponse, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, type WithdrawalRequest, buildMcpHeaders, buildToolCallPayload, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, executeWithdrawal, extractToolResult, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChainId, getContractAbi, getContractAddress, getContractConfig, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, getWithdrawalRequest, initMcpSession, isValidAddress, normalizeAddress, parseAllPaymentRequirements, parseMcpResponse, parseMoney, parsePaymentRequirement, requestWithdrawal, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Account } from 'viem/accounts';
2
- import { PublicClient, WalletClient, Hash, Address } from 'viem';
2
+ import { WalletClient, PublicClient, Hash, Address } from 'viem';
3
3
 
4
4
  /**
5
5
  * Type definitions for D402 payment protocol
@@ -198,6 +198,11 @@ interface D402ClientConfig {
198
198
  * Typically from wagmi: `walletClient.account`
199
199
  */
200
200
  operatorAccount: Account;
201
+ /**
202
+ * Wallet client for signing (required for wagmi/browser use).
203
+ * This is needed because wagmi accounts don't have signTypedData directly.
204
+ */
205
+ walletClient?: WalletClient;
201
206
  /**
202
207
  * IATPWallet contract address.
203
208
  * Get from `createIATPWallet()` or `getWalletsByOwner()`.
@@ -267,6 +272,7 @@ interface D402ClientConfig {
267
272
  */
268
273
  declare class D402Client {
269
274
  private readonly operatorAccount;
275
+ private readonly walletClient?;
270
276
  private readonly iatpWalletAddress;
271
277
  private readonly maxValue?;
272
278
  private readonly paymentRequirementsSelector;
@@ -383,6 +389,45 @@ declare class D402Client {
383
389
  * ```
384
390
  */
385
391
  fetch(url: string, init?: RequestInit): Promise<Response>;
392
+ /**
393
+ * Call an MCP tool with automatic session initialization and payment handling.
394
+ *
395
+ * This is the simplest way to call an MCP tool. It handles:
396
+ * - MCP session initialization
397
+ * - JSON-RPC payload construction
398
+ * - HTTP 402 payment flow
399
+ * - SSE/JSON response parsing
400
+ *
401
+ * @param endpoint - MCP server endpoint URL
402
+ * @param toolName - Name of the tool to call
403
+ * @param input - Tool arguments
404
+ * @param options - Optional configuration
405
+ * @returns The tool's result data
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * const client = new D402Client({
410
+ * operatorAccount: walletClient.account,
411
+ * walletClient,
412
+ * iatpWalletAddress,
413
+ * })
414
+ *
415
+ * // Simple one-liner!
416
+ * const result = await client.mcpCall(
417
+ * 'https://my-mcp.example.com/mcp',
418
+ * 'google_search',
419
+ * { q: 'test search' }
420
+ * )
421
+ *
422
+ * console.log(result) // { searchResults: [...] }
423
+ * ```
424
+ */
425
+ mcpCall(endpoint: string, toolName: string, input: Record<string, unknown>, options?: {
426
+ /** Skip session initialization (for stateless servers) */
427
+ skipInit?: boolean;
428
+ /** Custom JSON-RPC request ID */
429
+ requestId?: string | number;
430
+ }): Promise<unknown>;
386
431
  }
387
432
 
388
433
  /**
@@ -399,6 +444,7 @@ declare class D402Client {
399
444
  *
400
445
  * @param params - Signing parameters
401
446
  * @param params.operatorAccount - User's account for signing (from wagmi walletClient)
447
+ * @param params.walletClient - Optional wallet client for signing (wagmi). If provided, uses walletClient.signTypedData
402
448
  * @param params.paymentRequirement - Payment requirements from 402 response
403
449
  * @param params.iatpWalletAddress - IATPWallet contract address (optional)
404
450
  * @param params.requestPath - API request path (optional, uses payment_requirements.resource if not provided)
@@ -412,6 +458,7 @@ declare class D402Client {
412
458
  * // User signs payment (MetaMask popup appears)
413
459
  * const signedPayment = await signD402Payment({
414
460
  * operatorAccount: walletClient.account, // User's wallet
461
+ * walletClient: walletClient, // For signing with wagmi
415
462
  * paymentRequirement: requirement,
416
463
  * iatpWalletAddress: '0xUserIATPWallet...'
417
464
  * })
@@ -422,8 +469,9 @@ declare class D402Client {
422
469
  */
423
470
  declare function signD402Payment(params: {
424
471
  operatorAccount: Account;
472
+ walletClient?: WalletClient;
425
473
  paymentRequirement: PaymentRequirement;
426
- iatpWalletAddress?: `0x${string}`;
474
+ iatpWalletAddress: `0x${string}`;
427
475
  requestPath?: string;
428
476
  d402Version?: number;
429
477
  }): Promise<SignedPayment>;
@@ -613,6 +661,7 @@ interface WithdrawalRequest {
613
661
  */
614
662
  declare function createIATPWallet(params: {
615
663
  ownerAccount: Account;
664
+ walletClient?: WalletClient;
616
665
  network?: 'sepolia';
617
666
  rpcUrl?: string;
618
667
  }): Promise<WalletCreationResult>;
@@ -821,6 +870,109 @@ declare function executeWithdrawal(params: {
821
870
  network?: 'sepolia';
822
871
  }): Promise<Hash>;
823
872
 
873
+ /**
874
+ * MCP Session Management
875
+ *
876
+ * Handles MCP protocol session initialization.
877
+ */
878
+ /**
879
+ * Initialize an MCP session with the server.
880
+ *
881
+ * Sends the `initialize` JSON-RPC method to establish a session.
882
+ * Some servers return a session ID in headers, others are stateless.
883
+ *
884
+ * @param endpoint - MCP server endpoint URL
885
+ * @returns Session ID if provided by server, null otherwise
886
+ */
887
+ declare function initMcpSession(endpoint: string): Promise<string | null>;
888
+
889
+ /**
890
+ * MCP Payload Builder
891
+ *
892
+ * Constructs JSON-RPC payloads for MCP tool calls.
893
+ */
894
+ interface JsonRpcPayload {
895
+ jsonrpc: '2.0';
896
+ id: string | number;
897
+ method: string;
898
+ params: {
899
+ name: string;
900
+ arguments: Record<string, unknown>;
901
+ };
902
+ }
903
+ /**
904
+ * Build a JSON-RPC payload for an MCP tool call.
905
+ *
906
+ * @param toolName - Name of the MCP tool to call
907
+ * @param args - Tool arguments
908
+ * @param requestId - Optional custom request ID (default: 1)
909
+ * @returns Complete JSON-RPC payload ready to send
910
+ *
911
+ * @example
912
+ * ```ts
913
+ * const payload = buildToolCallPayload('google_search', { q: 'test' })
914
+ * // { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'google_search', arguments: { q: 'test' } } }
915
+ * ```
916
+ */
917
+ declare function buildToolCallPayload(toolName: string, args: Record<string, unknown>, requestId?: string | number): JsonRpcPayload;
918
+ /**
919
+ * Build headers for an MCP request.
920
+ *
921
+ * @param sessionId - Optional MCP session ID
922
+ * @returns Headers object for fetch
923
+ */
924
+ declare function buildMcpHeaders(sessionId?: string | null): Record<string, string>;
925
+
926
+ /**
927
+ * MCP Response Parser
928
+ *
929
+ * Handles parsing of MCP responses in both JSON and SSE formats.
930
+ */
931
+ interface McpToolResult {
932
+ /** Whether the tool call was successful */
933
+ isError: boolean;
934
+ /** The tool's output content */
935
+ content: Array<{
936
+ type: string;
937
+ text?: string;
938
+ [key: string]: unknown;
939
+ }>;
940
+ /** Structured content if available */
941
+ structuredContent?: unknown;
942
+ }
943
+ interface ParsedMcpResponse {
944
+ /** JSON-RPC response ID */
945
+ id: string | number;
946
+ /** The tool result */
947
+ result: McpToolResult | unknown;
948
+ /** Error if the call failed */
949
+ error?: {
950
+ code: number;
951
+ message: string;
952
+ data?: unknown;
953
+ };
954
+ }
955
+ /**
956
+ * Parse an MCP response, handling both SSE and JSON formats.
957
+ *
958
+ * MCP servers may return responses as:
959
+ * - `application/json`: Standard JSON response
960
+ * - `text/event-stream`: Server-Sent Events with `data: {...}` format
961
+ *
962
+ * @param response - Fetch Response object
963
+ * @returns Parsed response data
964
+ */
965
+ declare function parseMcpResponse(response: Response): Promise<ParsedMcpResponse>;
966
+ /**
967
+ * Extract the tool result from an MCP response.
968
+ *
969
+ * Handles the nested structure and returns just the useful data.
970
+ *
971
+ * @param response - Parsed MCP response
972
+ * @returns The tool's result data
973
+ */
974
+ declare function extractToolResult(response: ParsedMcpResponse): unknown;
975
+
824
976
  /**
825
977
  * IATPSettlementLayer query functions
826
978
  */
@@ -1172,4 +1324,4 @@ declare class UnsupportedNetworkError extends PaymentError {
1172
1324
  constructor(network: string);
1173
1325
  }
1174
1326
 
1175
- export { ContractName, D402Client, type D402ClientConfig, type D402Response, type EIP712Domain, Invalid402ResponseError, MissingRequestConfigError, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, type WithdrawalRequest, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, executeWithdrawal, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChainId, getContractAbi, getContractAddress, getContractConfig, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, getWithdrawalRequest, isValidAddress, normalizeAddress, parseAllPaymentRequirements, parseMoney, parsePaymentRequirement, requestWithdrawal, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };
1327
+ export { ContractName, D402Client, type D402ClientConfig, type D402Response, type EIP712Domain, Invalid402ResponseError, type JsonRpcPayload, type McpToolResult, MissingRequestConfigError, type ParsedMcpResponse, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, type WithdrawalRequest, buildMcpHeaders, buildToolCallPayload, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, executeWithdrawal, extractToolResult, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChainId, getContractAbi, getContractAddress, getContractConfig, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, getWithdrawalRequest, initMcpSession, isValidAddress, normalizeAddress, parseAllPaymentRequirements, parseMcpResponse, parseMoney, parsePaymentRequirement, requestWithdrawal, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };