Skip to main content
Glama

pay_l402_api

Automatically pay for API access using Lightning (L402) or USDC (X402) protocols when required, handling HTTP 402 responses with preferred protocol detection.

Instructions

Make a request to a paid API. Supports L402 (Lightning) and X402 (USDC on Base) protocols. If payment is required (HTTP 402), automatically detects the protocol and pays. L402 is preferred when both are available. REQUIRES AGENT KEY.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesThe URL to request
methodNoHTTP methodGET
bodyNoRequest body for POST/PUT requests
max_payment_satsNoMaximum amount in satoshis to pay for this request

Implementation Reference

  • Handler for the 'pay_l402_api' tool, which processes the request using the client's l402Pay method and constructs the response.
    case 'pay_l402_api': {
      const parsed = PayL402ApiSchema.parse(args);
      const result = await session.requireClient().l402Pay(
        parsed.url,
        parsed.method,
        parsed.body,
        parsed.max_payment_sats
      );
      // Determine if the target returned a success response
      const targetSuccess = result.statusCode >= 200 && result.statusCode < 300;
      const message = targetSuccess
        ? (result.amountPaid ? `Request completed with payment of ${result.amountPaid} sats` : 'Request completed (no payment required)')
        : `Target returned HTTP ${result.statusCode}`;
      const responseData: Record<string, unknown> = {
        success: targetSuccess,
        message,
        status_code: result.statusCode,
        data: result.data,
        payment_hash: result.paymentHash,
        amount_paid: result.amountPaid,
        fee: result.fee,
      };
      if (result.paymentProtocol) {
        responseData.payment_protocol = result.paymentProtocol;
      }
      if (result.usdcAmount !== undefined) {
        responseData.usdc_amount = result.usdcAmount;
      }
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(responseData, null, 2),
          },
        ],
      };
    }
  • The client-side method l402Pay that executes the API request for the pay_l402_api tool by calling the underlying API.
     * Pay an L402-protected API endpoint
     */
    async l402Pay(
      url: string,
      method: string = 'GET',
      body?: string,
      maxPaymentSats: number = 1000
    ): Promise<{
      data: unknown;
      statusCode: number;
      paymentHash?: string;
      amountPaid?: number;
      fee?: number;
      paymentProtocol?: 'l402' | 'x402';
      usdcAmount?: number;
      rawResponse: L402PayResponse;
    }> {
      const requestData: Record<string, unknown> = {
        url,
        method: method.toUpperCase(),
        max_payment_sats: maxPaymentSats,
      };
    
      if (body) {
        requestData.body = body;
      }
    
      const result = await this.request<L402PayResponse>('l402_pay', requestData);
    
      let responseData: unknown;
      if (result.body) {
        try {
          responseData = JSON.parse(result.body);
        } catch {
          responseData = result.body;
        }
      } else {
        responseData = result.data;
      }
    
      return {
        data: responseData,
        statusCode: result.status_code || 200,
        paymentHash: result.payment_hash,
        amountPaid: result.amount_paid,
        fee: result.fee,
        paymentProtocol: result.payment_protocol,
        usdcAmount: result.usdc_amount,
        rawResponse: result,
      };
    }
  • Input schema for the pay_l402_api tool.
    const PayL402ApiSchema = z.object({
      url: z.string().describe('The URL to request'),
      method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).default('GET').describe('HTTP method'),
      body: z.string().optional().describe('Request body for POST/PUT requests'),
      max_payment_sats: z.number().min(1).max(100000).default(1000)
        .describe('Maximum amount in satoshis to pay for this request'),
    });
  • src/index.ts:314-338 (registration)
    Registration definition for the pay_l402_api tool.
    {
      name: 'pay_l402_api',
      description: 'Make a request to a paid API. Supports L402 (Lightning) and X402 (USDC on Base) protocols. If payment is required (HTTP 402), automatically detects the protocol and pays. L402 is preferred when both are available. REQUIRES AGENT KEY.',
      inputSchema: {
        type: 'object',
        properties: {
          url: { type: 'string', description: 'The URL to request' },
          method: {
            type: 'string',
            enum: ['GET', 'POST', 'PUT', 'DELETE'],
            default: 'GET',
            description: 'HTTP method',
          },
          body: { type: 'string', description: 'Request body for POST/PUT requests' },
          max_payment_sats: {
            type: 'integer',
            minimum: 1,
            maximum: 100000,
            default: 1000,
            description: 'Maximum amount in satoshis to pay for this request',
          },
        },
        required: ['url'],
      },
    },
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: automatic payment detection on HTTP 402, protocol preference (L402 over X402), and the agent key requirement. However, it doesn't mention rate limits, error handling, or what happens when payment fails, leaving some behavioral aspects unclear.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with three sentences that each add value: protocol support, payment automation behavior, and key requirement. It's front-loaded with the core purpose. Minor improvement could be made by explicitly stating this is for HTTP API calls with payment.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 4 parameters, no annotations, and no output schema, the description provides adequate context about payment protocols and automation. However, it doesn't explain return values, error conditions, or provide examples of typical use cases. Given the complexity of payment handling, more completeness would be beneficial.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so parameters are well-documented in the schema. The description doesn't add any meaningful parameter semantics beyond what's already in the schema descriptions. The baseline of 3 is appropriate since the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Make a request to a paid API' with support for L402 and X402 protocols. It specifies the verb ('Make a request') and resource ('paid API'), but doesn't explicitly differentiate from sibling tools like 'pay_invoice' or 'pay_lightning_address' which handle different payment scenarios.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context ('If payment is required (HTTP 402)') and states 'L402 is preferred when both are available', but doesn't provide explicit guidance on when to use this tool versus alternatives like 'pay_invoice' or 'keysend'. It mentions 'REQUIRES AGENT KEY' as a prerequisite, but lacks comprehensive when/when-not instructions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/lightningfaucet/lightning-wallet-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server