Skip to main content
Glama

create_l402_challenge

Generate Lightning Network payment challenges to charge for resource access using the L402 protocol. Creates invoices and macaroons for automated transactions between agents.

Instructions

Create an L402 payment challenge to charge another agent or user for accessing a resource. Returns a Lightning invoice and macaroon. The payer must pay the invoice and present the L402 token (macaroon:preimage) back to you for verification. Requires LIGHTNING_ENABLE_API_KEY with an Agentic Commerce subscription.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
resourceYesResource identifier - URL, service name, or description of what you're charging for
price_satsYesPrice in satoshis to charge
descriptionNoDescription shown on the Lightning invoice

Implementation Reference

  • The main handler function `create_l402_challenge` that implements the creation of an L402 challenge via the Lightning Enable API.
    async def create_l402_challenge(
        resource: str,
        price_sats: int,
        description: str | None = None,
        api_client: "LightningEnableApiClient | None" = None,
    ) -> str:
        """
        Create an L402 payment challenge to charge another agent or user for accessing a resource.
    
        Returns a Lightning invoice and macaroon. The payer must pay the invoice and present
        the L402 token (macaroon:preimage) back to you for verification.
    
        Args:
            resource: Resource identifier - URL, service name, or description of what you're charging for
            price_sats: Price in satoshis to charge
            description: Description shown on the Lightning invoice
            api_client: Lightning Enable API client instance
    
        Returns:
            JSON with challenge details (invoice, macaroon, paymentHash) or error message
        """
        # Input validation
        if not resource or not resource.strip():
            return json.dumps({
                "success": False,
                "error": "Resource identifier is required. Provide a URL, service name, or description of what you're charging for."
            })
    
        if price_sats <= 0:
            return json.dumps({
                "success": False,
                "error": "Price must be greater than 0 sats"
            })
    
        if api_client is None:
            return json.dumps({
                "success": False,
                "error": "Lightning Enable API service not available"
            })
    
        if not api_client.is_configured:
            return json.dumps({
                "success": False,
                "error": "Lightning Enable API key not configured. "
                         "Set LIGHTNING_ENABLE_API_KEY environment variable or add 'lightningEnableApiKey' to ~/.lightning-enable/config.json. "
                         "Requires an Agentic Commerce subscription at https://lightningenable.com."
            })
    
        try:
            result = await api_client.create_challenge(resource, price_sats, description)
    
            if not result.get("success"):
                return json.dumps({
                    "success": False,
                    "error": result.get("error", "Unknown error creating challenge")
                })
    
            challenge = result.get("challenge", {})
            macaroon = challenge.get("macaroon", "")
    
            return json.dumps({
                "success": True,
                "challenge": {
                    "invoice": challenge.get("invoice"),
                    "macaroon": macaroon,
                    "paymentHash": challenge.get("paymentHash"),
                    "expiresAt": challenge.get("expiresAt"),
                },
                "resource": resource,
                "priceSats": price_sats,
                "instructions": {
                    "forPayer": f"Pay the Lightning invoice, then present the L402 token: 'L402 {macaroon}:<preimage>' "
                               "where <preimage> is the proof of payment received after paying the invoice.",
                    "tokenFormat": "L402 {macaroon}:{preimage}",
                    "verifyWith": "After receiving the L402 token from the payer, use verify_l402_payment to confirm payment before granting access."
                },
                "message": f"L402 challenge created for {price_sats} sats. Share the invoice with the payer."
            }, indent=2)
    
        except Exception as e:
            logger.exception("Error creating L402 challenge")
            return json.dumps({
                "success": False,
                "error": sanitize_error(str(e))
            })
  • The tool is registered and invoked in the `server.py` file within the MCP tool handler logic.
    elif name == "create_l402_challenge":
        result = await create_l402_challenge(
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 behaviors: it returns specific outputs (Lightning invoice and macaroon), outlines the payer's required actions (pay invoice and present token), and mentions authentication needs (API key requirement). However, it lacks details on rate limits or error handling.

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

Conciseness5/5

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

The description is appropriately sized and front-loaded, with three concise sentences that each add value: the first states the purpose, the second explains the return and process, and the third notes prerequisites, with no wasted words.

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

Completeness4/5

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

Given the tool's complexity (payment challenge creation) and lack of output schema, the description is fairly complete, covering purpose, process, and prerequisites. However, it could benefit from more details on output format or error cases to fully compensate for the missing structured data.

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 the schema already documents all parameters. The description adds no additional meaning beyond what the schema provides, such as examples or usage context for parameters like 'resource' or 'price_sats', meeting the baseline for high coverage.

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

Purpose5/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 with specific verbs ('create', 'charge') and resource ('L402 payment challenge'), distinguishing it from siblings like 'create_invoice' or 'pay_l402_challenge' by focusing on generating a challenge for accessing resources.

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

Usage Guidelines4/5

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

It provides clear context on when to use this tool (to charge for resource access) and mentions prerequisites (requires LIGHTNING_ENABLE_API_KEY with Agentic Commerce subscription), but does not explicitly state when not to use it or name alternatives among siblings.

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/refined-element/lightning-enable-mcp'

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