Skip to main content
Glama

Servidor MCP de LiveAuth

npm version MIT license L402 MCP

Autenticación, medición de pago por llamada y recibos firmados para agentes de IA y herramientas MCP: nativo de Bitcoin, respaldado por Lightning y compatible con L402.

Este servidor MCP permite que cualquier agente de IA se autentique contra tu API mediante prueba de trabajo (gratis, sin cuenta) o micropagos de Lightning Network (sats), y luego mida y monetice las llamadas posteriores a herramientas con precios por llamada, eventos de ingresos idempotentes y recibos firmados con HMAC que los auditores pueden verificar sin conexión.

Úsalo cuando quieras:

  • Proteger una API o herramienta MCP detrás de un costo real de cómputo o sats reales (anti-spam por diseño, no por CAPTCHA).

  • Cobrar a los agentes de IA por llamada sin necesidad de que creen una cuenta.

  • Emitir un rastro de auditoría a prueba de manipulaciones (recibo firmado mcp-call-receipt-v1) por cada invocación de herramienta de pago.

  • Ofrecer acceso a paquetes L402 respaldados por Lightning para sesiones MCP prepagadas.

Pruébalo en 5 segundos: sin cuenta, sin clave de API:

npx @liveauth-labs/mcp-server

Sin configuración, el servidor utiliza el proyecto de demostración anónimo de LiveAuth y el flujo real de PoW. Añade LIVEAUTH_API_KEY solo cuando necesites la política, los precios o la atribución de un proyecto específico.


Herramientas disponibles (detección automática de Glama / MCP)

Herramienta

Propósito

liveauth_mcp_start

Iniciar una sesión. Devuelve un desafío PoW, una factura Lightning o una pista de paquete L402.

liveauth_mcp_confirm

Enviar un desafío PoW resuelto, una factura Lightning pagada o un macarrón L402 → recibir un JWT.

liveauth_mcp_charge

Medir el uso después de una llamada. Con toolName, resuelve el precio de la herramienta registrada y registra un evento de ingresos pagado.

liveauth_mcp_refresh

Intercambiar un token de actualización por un nuevo JWT: sin necesidad de reautenticación.

liveauth_mcp_status

Consultar el estado de la sesión/pago (confirmación de Lightning, caducidad).

liveauth_mcp_lnurl

Obtener la factura BOLT11 de una sesión (compatible con lnget).

liveauth_mcp_usage

Consultar el presupuesto restante, las llamadas utilizadas y las ventanas de límite de velocidad.

Los esquemas completos de parámetros y respuestas están en la Referencia de herramientas a continuación.


Related MCP server: Agent Receipts

Inicio rápido en 5 minutos

Opción 1 — PoW sin credenciales (sin cuenta, sin clave, sin cartera)

npx @liveauth-labs/mcp-server

En un cliente MCP, llama a liveauth_mcp_start y luego a liveauth_mcp_confirm solo con el quoteId devuelto. El paquete reutiliza su solucionador de PoW existente localmente y la API de LiveAuth verifica el desafío firmado antes de emitir un JWT de sesión de corta duración.

Opción 2 — Modo de producción

  1. Obtén una clave de API en liveauth.app.

  2. Añádela al claude_desktop_config.json de Claude Desktop:

{
  "mcpServers": {
    "liveauth": {
      "command": "npx",
      "args": ["-y", "@liveauth-labs/mcp-server"],
      "env": {
        "LIVEAUTH_API_BASE": "https://api.liveauth.app",
        "LIVEAUTH_API_KEY": "la_pk_your_public_key"
      }
    }
  }
}
  1. Reinicia Claude. Listo.

Opción 3 — Programático (CLI / SDK)

export LIVEAUTH_API_KEY=la_pk_xxx
npx @liveauth-labs/mcp-server

El paquete también es un SDK de TypeScript: consulta Uso del SDK a continuación. El binario CLI es liveauth-mcp.

¿Por qué LiveAuth?

Para proveedores de API / desarrolladores de herramientas:

  • Detén bots en la capa de protocolo. PoW y los sats de Lightning no son reproducibles, no son suplantables y no requieren cuentas de usuario.

  • Cobra por llamada en sats. Firmamos un recibo que puedes mostrar a auditores, clientes o tu contable.

  • Envuelve cualquier herramienta MCP con una línea (createMcpGate) y obtienes ingresos por herramienta, precios mín/máx por herramienta y reintentos idempotentes.

Para agentes de IA / creadores de agentes:

  • Acceso sin permisos a APIs de pago: resuelve un PoW o paga sats, obtén un JWT. Sin registro, sin correo electrónico, sin baile de OAuth.

  • Usa PoW, facturas Lightning o macarrones de paquete L402 para el acceso de agentes.

  • Los proyectos pueden liquidar a través de un nodo Lightning personalizado cuando se configura; de lo contrario, los pagos usan el nodo configurado por LiveAuthCore.

Las matemáticas que importan: si tu herramienta está siendo extraída por un bot, cobrar 1 sat por llamada es suficiente para que el raspador no sea rentable. Llamamos a esto economía del costo del ataque, y es la razón de nuestra existencia.

Instalación

npm install -g @liveauth-labs/mcp-server

O úsalo directamente con npx:

npx @liveauth-labs/mcp-server

Goose

LiveAuth para Goose usa el mismo servidor MCP stdio basado en estándares que cualquier otro cliente: no hay envoltorio de Goose, demonio ni tiempo de ejecución de autenticación duplicado.

Instalar en Goose

O imprime el enlace profundo oficial y los respaldos actuales:

npx @liveauth-labs/mcp-server setup goose

Para una sesión CLI de Goose única:

goose session --with-extension "liveauth:npx -y @liveauth-labs/mcp-server"

Configuración manual de stdio de Goose, cuando el enlace profundo no esté disponible:

extensions:
  liveauth:
    type: stdio
    name: LiveAuth
    enabled: true
    cmd: npx
    args: ["-y", "@liveauth-labs/mcp-server"]
    env_keys: []
    envs: {}
    timeout: 300

No edites una configuración existente de Goose de forma destructiva. Prefiere el enlace profundo o goose configure; si añades configuración de proyecto más adelante, introdúcela a través de la configuración de secretos de la extensión de Goose en lugar de YAML de texto plano compartido.

Prueba rápida de Goose

Pregunta a Goose:

Usa LiveAuth para iniciar el flujo de autenticación predeterminado. Confirma la cotización devuelta y luego muestra mi uso de LiveAuth.

El flujo inicial usa el desafío PoW del proyecto de demostración anónimo y no requiere cartera. Una clave pública de proyecto es opcional:

Variable

Cuándo configurarla

LIVEAUTH_API_KEY

Política, precios y atribución específicos del proyecto.

LIVEAUTH_API_BASE

Una API de LiveAuth autoalojada en lugar de https://api.liveauth.app.

LIVEAUTH_DEMO=true

Optar explícitamente por la demostración Lightning simulada localmente más antigua.

Cuando se solicita un flujo de pago, los resultados de la herramienta conservan los campos de factura existentes y también incluyen datos estructurados portátiles:

{
  "lightning": {
    "invoice": "lnbc...",
    "lightningUri": "lightning:lnbc...",
    "amountSats": 21,
    "expiresAt": "2030-03-17T17:46:40.000Z",
    "status": "pending"
  }
}

Los clientes con soporte de MCP Apps pueden renderizar el QR incluido, la acción de abrir cartera, la caducidad y el estado en vivo pagado/pendiente/caducado. Otros clientes reciben el JSON y el contenido de la imagen QR como resultados MCP ordinarios.

Solución de problemas de Goose

  • Si el enlace no se abre, ejecuta npx @liveauth-labs/mcp-server setup goose y usa su respaldo de una sesión o manual.

  • Si npx no está disponible, instala una versión actual de Node.js (Node 18 o posterior).

  • Si una clave de proyecto proporcionada es rechazada, elimínala para verificar el flujo PoW anónimo; las claves inválidas y revocadas intencionalmente no recurren a la demostración.

  • Si una factura Lightning caduca, llama a liveauth_mcp_start de nuevo para obtener una cotización nueva.

  • Mantén los tokens de actualización y cualquier credencial no pública fuera de los registros y de la configuración en texto plano.

LiveAuth permite que los agentes adquieran autorización en tiempo de ejecución en lugar de requerir que cada herramienta se aprovisione con credenciales permanentes de antemano.

Uso del SDK

El paquete también se puede importar como SDK de TypeScript/JavaScript. Importar el paquete no inicia el servidor MCP stdio; el CLI se encuentra en el binario liveauth-mcp.

Helper de autenticación de cliente

import { createMcpClient } from '@liveauth-labs/mcp-server';

const liveauth = createMcpClient({
  publicKey: 'la_pk_xxx',
  baseUrl: 'https://api.liveauth.app',
  onInvoice(invoice) {
    // Render invoice.bolt11 as a QR code for a paid Lightning test.
    console.log(invoice.bolt11);
  },
});

const session = await liveauth.start();
const token = await liveauth.confirm(session);

console.log(token.jwt);

El cliente almacena los JWT confirmados, los actualiza antes de la caducidad cuando se devuelve un token de actualización y expone el token actual a través de liveauth.token. Llama a liveauth.destroy() cuando tu aplicación se esté cerrando para limpiar el estado del token y los temporizadores de actualización.

Para requerir una factura de pago real:

const session = await liveauth.start({ forceLightning: true });
console.log(session.invoice?.bolt11);

// Poll this after the invoice is paid.
const token = await liveauth.confirmLightning(session);

Helper de puerta de servidor

import { createMcpGate } from '@liveauth-labs/mcp-server';

const gate = createMcpGate({
  publicKey: 'la_pk_xxx',
  baseUrl: 'https://api.liveauth.app',
});

const result = await gate.invoke(
  jwtFromYourTransport,
  { message: 'hello' },
  async (input, context) => ({
    content: [{ type: 'text', text: input.message }],
    charge: context.liveAuth.charge,
  }),
  {}
);

gate.invoke(...) valida el JWT, cobra el costo configurado en sats o el predeterminado del proyecto backend, y pasa context.liveAuth a tu manejador. El nombre más antiguo gate.gateTool(...) todavía es compatible.

Atribución de herramientas de pago

Si tu servidor MCP tiene un ID de herramienta LiveAuth registrado, pasa toolId al crear la puerta. Los cargos entonces van a:

POST /api/mcp/tools/{toolId}/charge

en lugar del endpoint genérico heredado:

POST /api/mcp/charge

También puedes pasar un slug/nombre de herramienta registrado como toolName. En ese modo, los cargos van al endpoint genérico con la identidad de la herramienta en el cuerpo:

POST /api/mcp/charge

Los cargos de herramientas conservan las mismas comprobaciones de presupuesto de sesión, pero también registran un evento de ingresos inmutable con sats brutos, tarifa de plataforma de LiveAuth, sats netos para el desarrollador, nombre del método de la herramienta, proyecto/sesión/token de pago, metadatos y clave de idempotencia. Cuando se omite costSats, LiveAuthCore usa el precio predeterminado de la herramienta registrada; sin toolId o toolName, recurre al precio MCP global del proyecto.

Las herramientas registradas también pueden tener una URL de webhook de llamada de pago. En cada nueva llamada de pago exitosa, LiveAuthCore pone en cola un webhook liveauth.mcp.tool.paid_call con la identidad de la herramienta, sats brutos/plataforma/netos, ID del evento de ingresos, metadatos y el recibo firmado. Si la URL del webhook de la herramienta está en blanco, LiveAuthCore recurre a la URL del webhook del proyecto; los reintentos idempotentes no ponen en cola duplicados.

import { createMcpGate } from '@liveauth-labs/mcp-server';

const gate = createMcpGate({
  publicKey: process.env.LIVEAUTH_PUBLIC_KEY!,
  baseUrl: process.env.LIVEAUTH_API_URL ?? 'https://api.liveauth.app',
  toolName: 'paid-research-tool',
});

const result = await gate.invoke(
  jwtFromYourTransport,
  { url: 'https://example.com' },
  async (input, context) => {
    const page = await fetch(input.url).then(r => r.text());

    return {
      text: page,
      revenueEventId: context.liveAuth.charge.revenueEventId,
      receipt: context.liveAuth.charge.receipt,
      netSats: context.liveAuth.charge.netSats,
    };
  },
  { requestId: 'req_123' },
  {
    toolMethodName: 'web_fetch',
    idempotencyKey: 'req_123',
    agentId: 'agent_abc',
    metadata: {
      urlHost: new URL('https://example.com').hostname,
    },
  }
);

Cuando se establece toolId o toolName, GateToolOptions admite:

Opción

Propósito

costSats

Sats opcionales a cobrar por esta llamada. Omítelo para usar el precio de la herramienta registrada o el precio global del proyecto.

toolName

Sobrescritura opcional del slug/nombre de la herramienta por llamada al usar el endpoint genérico.

toolMethodName

Método dentro de la herramienta, como web_fetch o search.

idempotencyKey

Clave segura para reintentos. Reutilizarla para la misma herramienta devuelve el evento de ingresos original y el recibo firmado en lugar de cobrar dos veces.

agentId

Identificador opcional de llamante/agente para informes.

metadata

Objeto JSON pequeño para contexto de auditoría. No almacenes salida privada de la herramienta aquí.

Las respuestas de cargos de herramientas incluyen los contadores de presupuesto normales más la contabilidad de ingresos:

{
  "status": "ok",
  "callsUsed": 3,
  "satsUsed": 15,
  "grossSats": 5,
  "platformFeeSats": 1,
  "netSats": 4,
  "feeBasisPoints": 500,
  "revenueEventId": "event-guid",
  "toolId": "tool-guid",
  "toolName": "Paid Research Tool",
  "toolSlug": "paid-research-tool",
  "receipt": {
    "version": "mcp-call-receipt-v1",
    "payload": "base64url-canonical-json",
    "signature": "base64url-hmac-sha256",
    "signatureAlgorithm": "HMAC-SHA256",
    "keyId": "liveauth-mcp-receipt-v1",
    "body": {
      "receiptId": "mcp_receipt_eventguid",
      "revenueEventId": "event-guid",
      "mcpToolId": "tool-guid",
      "toolName": "Paid Research Tool",
      "toolSlug": "paid-research-tool",
      "toolMethodName": "web_fetch",
      "grossSats": 5,
      "platformFeeSats": 1,
      "netSats": 4,
      "idempotencyKey": "req_123"
    }
  }
}

El recibo es un artefacto de auditoría firmado por llamada devuelto por LiveAuthCore para cargos de herramientas de pago. Guárdalo con el resultado de tu herramienta cuando necesites prueba de cargo o conciliación posterior.

Si no se configura toolId ni toolName, el SDK sigue usando /api/mcp/charge para la medición de uso compatible con versiones anteriores.

Configuración

Claude Desktop

Añade a tu claude_desktop_config.json:

{
  "mcpServers": {
    "liveauth": {
      "command": "npx",
      "args": ["-y", "@liveauth-labs/mcp-server"],
      "env": {
        "LIVEAUTH_API_BASE": "https://api.liveauth.app",
        "LIVEAUTH_API_KEY": "la_pk_your_public_key"
      }
    }
  }
}

Modo sin credenciales: si omites LIVEAUTH_API_KEY, el servidor llama a los endpoints MCP normales sin un encabezado de proyecto. LiveAuth vincula su proyecto de demostración anónimo configurado, devuelve un desafío PoW firmado y preserva los límites normales de verificación, JWT, límite de velocidad y medición. LIVEAUTH_DEMO=true sigue siendo una opción explícita para la vista previa Lightning simulada localmente más antigua.

Otras variables de entorno:

Variable

Predeterminado

Propósito

LIVEAUTH_API_KEY

(sin establecer)

Tu clave pública de proyecto LiveAuth (la_pk_…).

LIVEAUTH_API_BASE

https://api.liveauth.app

Sobrescritura para LiveAuth autoalojado.

LIVEAUTH_DEMO

false

Usar explícitamente la demostración Lightning simulada localmente heredada.

Otros clientes MCP

El servidor habla stdio (JSON-RPC 2.0). Inícialo con:

liveauth-mcp

También funciona con cualquier cliente compatible con MCP: Cursor, VS Code, ChatGPT, Windsurf, Continue, Cline.

Referencia de herramientas

Esquemas completos para cada herramienta MCP. Cada herramienta es compatible con JSON-RPC 2.0 y está probada en src/index.test.ts y src/cli.test.ts.

liveauth_mcp_start

Inicia una nueva sesión de LiveAuth MCP. Devuelve un desafío PoW por defecto, o una factura Lightning si forceLightning=true.

Parámetros:

  • forceLightning (booleano, opcional): Si es true, solicita una factura Lightning en lugar del desafío PoW

  • forceL402 (booleano, opcional): Si es true, inicia una sesión que debe confirmarse con un macarrón de paquete L402

Devuelve (PoW):

{
  "quoteId": "uuid-of-session",
  "powChallenge": {
    "projectId": "guid",
    "projectPublicKey": "la_pk_...",
    "challengeHex": "a1b2c3...",
    "targetHex": "0000ffff...",
    "difficultyBits": 18,
    "expiresAtUnix": 1234567890,
    "signature": "sig..."
  },
  "invoice": null
}

Devuelve (Lightning):

{
  "quoteId": "uuid-of-session",
  "powChallenge": null,
  "invoice": {
    "bolt11": "lnbc...",
    "amountSats": 50,
    "expiresAtUnix": 1234567890,
    "paymentHash": "abc123..."
  },
  "lightning": {
    "invoice": "lnbc...",
    "lightningUri": "lightning:lnbc...",
    "amountSats": 50,
    "expiresAt": "2009-02-13T23:31:30.000Z",
    "expiresAtUnix": 1234567890,
    "status": "pending"
  }
}

Devuelve (paquete L402):

{
  "quoteId": "uuid-of-session",
  "powChallenge": null,
  "invoice": null,
  "authHint": "l402_bundle"
}

liveauth_mcp_confirm

Envía un desafío de prueba de trabajo resuelto, permite que el paquete resuelva su desafío en caché, consulta un pago Lightning o presenta un macarrón L402 para recibir un token de autenticación JWT.

Parámetros:

  • quoteId (cadena): El quoteId de la respuesta de inicio

  • challengeHex (cadena, opcional, solo PoW): El challengeHex de la respuesta de inicio

  • nonce (número, opcional, solo PoW): El nonce que resuelve el desafío PoW

  • hashHex (cadena, opcional, solo PoW): El hash resultante (sha256 de projectPublicKey:challengeHex:nonce)

  • expiresAtUnix (número, opcional, solo PoW): Marca de tiempo de expiración del desafío

  • difficultyBits (número, opcional, solo PoW): Bits de dificultad del desafío

  • signature (cadena, opcional, solo PoW): Firma del desafío

  • macaroon (cadena, solo L402): Macarrón de paquete devuelto por el flujo de reclamación del paquete L402

Cuando el desafío proviene de este servidor MCP, llamar a confirm con quoteId solo reutiliza el solucionador PoW existente del paquete. Los campos de solución explícitos siguen siendo compatibles por compatibilidad.

Devuelve:

{
  "jwt": "eyJhbGc...",
  "expiresIn": 600,
  "remainingBudgetSats": 10000,
  "refreshToken": "abc123def456..."
}

Nota: Almacena el refreshToken de forma segura. Se devuelve en los datos de la herramienta MCP pero nunca se escribe en stderr ni en los registros de la aplicación. Usa liveauth_mcp_refresh para obtener un nuevo JWT sin volver a autenticarte.

liveauth_mcp_charge

Mide el uso de la API después de realizar una llamada autenticada. El servidor MCP incluido llama al endpoint genérico /api/mcp/charge. Proporcionar toolName permite que LiveAuth resuelva una herramienta registrada, aplique su precio configurado y cree un evento de ingresos de herramienta de pago; omitir toolName mantiene la medición genérica compatible con versiones anteriores.

Parámetros:

  • callCostSats (número, opcional): Coste de la llamada a la API en sats. Omítelo para usar el precio del backend.

  • toolName (cadena, opcional): Slug/nombre de la herramienta MCP registrada para precios y atribución por herramienta.

Devuelve:

{
  "status": "ok",
  "callsUsed": 5,
  "satsUsed": 15
}

Si se supera el presupuesto:

{
  "status": "deny",
  "callsUsed": 100,
  "satsUsed": 1000,
  "reason": "budget_exceeded"
}

liveauth_mcp_status

Comprueba el estado de una sesión MCP. Úsalo para consultar la confirmación del pago Lightning.

Parámetros:

  • quoteId (cadena): El quoteId de la respuesta de inicio

Devuelve:

{
  "quoteId": "uuid-of-session",
  "status": "pending",
  "paymentStatus": "pending",
  "expiresAt": "2026-02-17T12:00:00Z"
}

Cuando paymentStatus es "paid", la sesión está confirmada. Llama a liveauth_mcp_confirm de nuevo para obtener el JWT.

liveauth_mcp_lnurl

Obtiene la factura Lightning de una sesión (compatible con lnget). Úsalo para recuperar la factura BOLT11 para el pago con cualquier monedero Lightning.

Parámetros:

  • quoteId (cadena): El quoteId de la respuesta de inicio

Devuelve:

{
  "pr": "lnbc2100n1...",
  "routes": []
}

Nota: Esto es compatible con lnget y otras herramientas de pago Lightning. Úsalo para consultar la factura cuando liveauth_mcp_confirm devuelva "payment pending".

liveauth_mcp_usage

Consulta el uso actual y el presupuesto restante sin realizar un cargo. Úsalo para comprobar el estado antes de hacer llamadas a la API.

Parámetros: (ninguno requerido)

Devuelve:

{
  "status": "active",
  "callsUsed": 5,
  "satsUsed": 15,
  "maxSatsPerDay": 10000,
  "remainingBudgetSats": 9985,
  "maxCallsPerMinute": 60,
  "expiresAt": "2026-02-17T12:00:00Z",
  "dayWindowStart": "2026-02-17T00:00:00Z"
}

liveauth_mcp_refresh

Renueva el token JWT sin volver a autenticarte. Usa el refreshToken devuelto por confirm para obtener un nuevo JWT cuando el actual expire.

Parámetros:

  • refreshToken (cadena): El refreshToken de la respuesta de confirm

Devuelve:

{
  "jwt": "eyJhbGc...",
  "expiresIn": 600,
  "remainingBudgetSats": 9985
}

Nota: Guarda el refreshToken de forma segura. Lo necesitarás para extender la sesión sin resolver un nuevo PoW ni realizar otro pago Lightning.

Ejemplo de uso

Autenticación PoW

  1. Llama a liveauth_mcp_start para obtener un desafío PoW y un quoteId

  2. Llama a liveauth_mcp_confirm con el quoteId; el servidor MCP resuelve su desafío en caché con el solucionador de paquetes existente

  3. Los clientes avanzados pueden enviar una solución explícita (hash = sha256(projectPublicKey:challengeHex:nonce) donde hash < targetHex)

  4. Usa el JWT en el encabezado Authorization: Bearer <token> para las solicitudes de API

  5. Después de cada llamada genérica a la API, llama a liveauth_mcp_charge con un coste de llamada, u omítelo para usar el precio MCP global del proyecto

  6. Para herramientas MCP monetizadas, envuelve los manejadores con createMcpGate({ toolId }) o createMcpGate({ toolName }) para que cada llamada cree un evento de ingresos y un recibo firmado

Autenticación Lightning

  1. Llama a liveauth_mcp_start con forceLightning: true para obtener una factura Lightning

  2. Usa liveauth_mcp_lnurl (o consulta liveauth_mcp_status) para obtener la factura BOLT11

  3. Paga la factura usando tu nodo/monedero Lightning

  4. Consulta liveauth_mcp_status con el quoteId hasta que paymentStatus sea "paid"

  5. Llama a liveauth_mcp_confirm solo con el quoteId para recibir el JWT

  6. Usa el JWT con la medición genérica de liveauth_mcp_charge o con la atribución de herramientas de pago del SDK

Flujo de autenticación

┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│  AI Agent       │────▶│  MCP Server     │────▶│  LiveAuth API   │
│                 │     │                 │     │                 │
│ 1. Start       │     │ /api/mcp/start  │     │ Returns PoW    │
│ 2. Solve PoW   │     │                 │     │ challenge       │
│ 3. Confirm     │     │ /api/mcp/confirm│     │ Returns JWT    │
│ 4. API calls   │     │                 │     │                 │
│ 5. Charge      │     │ /api/mcp/charge │     │ Meter usage    │
└─────────────────┘     └─────────────────┘     └─────────────────┘

Los servidores de herramientas de pago usan el mismo JWT pero cobran a través de un endpoint atribuido:

Agent calls MCP tool
→ Tool server calls POST /api/mcp/tools/{toolId}/charge
  or POST /api/mcp/charge with toolName
→ LiveAuth validates JWT and budget
→ LiveAuth records gross / platform fee / net revenue and returns a signed receipt
→ Tool handler runs and returns the result

Flujo de paquete L402

LiveAuthCore admite paquetes L402 respaldados por Lightning para acceso MCP prepagado. Compra un paquete, reclama el macarrón después del pago, luego inicia una sesión MCP en modo L402 y confírmala con ese macarrón.

# 1. Create a bundle invoice.
curl -X POST https://api.liveauth.app/api/public/l402/bundle/invoice \
  -H "Content-Type: application/json" \
  -d '{"publicKey":"la_pk_xxx","tier":"starter","agentId":"agent_abc"}'

# 2. After the invoice is paid, claim a macaroon.
curl -X POST https://api.liveauth.app/api/public/l402/bundle/claim \
  -H "Content-Type: application/json" \
  -d '{"publicKey":"la_pk_xxx","paymentHash":"payment_hash_from_step_1"}'

# 3. Start and confirm an MCP session with the macaroon.
curl -X POST https://api.liveauth.app/api/mcp/start \
  -H "X-LW-Public: la_pk_xxx" \
  -H "Content-Type: application/json" \
  -d '{"forceL402":true}'

curl -X POST https://api.liveauth.app/api/mcp/confirm \
  -H "X-LW-Public: la_pk_xxx" \
  -H "Content-Type: application/json" \
  -d '{"quoteId":"quote_id_from_step_3","macaroon":"macaroon_from_step_2"}'

Desarrollo

# Install dependencies
npm install

# Build
npm run build

# Run locally
node dist/cli.js

Recursos

Licencia

MIT


Categorías: authentication · payments · lightning · l402 · bitcoin · pay-per-call · metering · agent-tools · anti-abuse · mcp-server · typescript

Available Tools

7 tools
liveauth_mcp_chargeA

Meter API usage after making an authenticated call. Call this with the cost in sats for each API request made using the JWT.

ParametersJSON Schema
NameRequiredDescriptionDefault
toolNameNoOptional registered MCP tool slug or name for per-tool pricing and revenue attribution.
callCostSatsNoOptional cost of the API call in sats. Omit to use LiveAuth project or tool pricing.

TDQS

A3.7/5.0
Behavior2/5

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

With no annotations provided, the description must disclose behavioral traits on its own. It mentions the action 'Meter API usage' but does not explain side effects like deducting sats, idempotency (e.g., calling twice), prerequisites beyond JWT authentication, or error behavior. As a monetary/charge operation, the lack of these details is a significant gap.

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 extremely concise—two short sentences that front-load the core action ('Meter API usage') and then provide the invocation details. There is no redundant or filler content; every sentence earns its place.

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 two optional parameters, the description gives a decent overview of purpose and usage. However, with no annotations or output schema, it omits important context such as the expected response, idempotency, and failure modes. It is minimally sufficient but not fully complete for a financial metering operation.

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?

The input schema already provides full documentation for both parameters (100% coverage). The description adds minor context (e.g., 'cost in sats for each API request') but does not meaningfully enrich the understanding of toolName or callCostSats beyond their schema descriptions. The high schema coverage justifies the baseline score of 3.

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 function: 'Meter API usage after making an authenticated call.' It identifies a specific verb (meter/charge) and resource (API usage), and the context (after an authenticated call) distinguishes it from sibling tools like liveauth_mcp_usage, which likely queries usage rather than recording it.

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?

The description explicitly instructs when to call the tool: 'Call this with the cost in sats for each API request made using the JWT.' This clearly conveys per-request usage after authentication. However, it doesn't explicitly mention alternatives or conditions when not to use it, preventing a perfect score.

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

liveauth_mcp_confirmA

Submit the solved proof-of-work challenge (or poll for Lightning payment) to receive a JWT. For Lightning, call with just quoteId to check/poll payment status.

ParametersJSON Schema
NameRequiredDescriptionDefault
nonceNoThe nonce that solves the PoW challenge (PoW only)
hashHexNoThe resulting hash hex (PoW only)
quoteIdYesThe quoteId from the start response
macaroonNoL402 bundle macaroon (L402 only)
signatureNoSignature from the challenge (PoW only)
challengeHexNoThe challenge hex from the start response (PoW only)
expiresAtUnixNoExpiration timestamp from the challenge (PoW only)
difficultyBitsNoDifficulty bits from the challenge (PoW only)

TDQS

A4.1/5.0
Behavior3/5

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

With no annotations, the description carries the burden. It discloses the dual-mode behavior (PoW vs Lightning), that polling is possible, and the outcome (JWT). However, it does not disclose failure modes, side effects like challenge invalidation, or retry semantics, leaving important behavioral gaps.

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?

Two sentences, front-loaded with the main action, and the second provides a specific usage tip. No waste or redundancy.

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?

The tool has 8 parameters and two distinct flows, with no annotations and no output schema. The description covers the core purpose and outcome but lacks details on error conditions, success/failure responses, and safety of repeated calls. It is adequate but not comprehensive for the complexity.

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

Parameters4/5

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

Schema coverage is 100%, so baseline is 3. The description adds mode-specific guidance: 'call with just quoteId' for Lightning, implying PoW uses the other fields. This clarifies how to select parameters by mode, going beyond the schema's individual descriptions.

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 states a specific action: submitting a solved proof-of-work challenge or polling for Lightning payment to receive a JWT. This clearly distinguishes it from siblings like start (which likely initiates) and status (which likely checks overall status).

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 explicit guidance: for Lightning, call with just quoteId to check/poll payment status, and PoW requires the challenge-solution fields. It does not explicitly name alternatives or when-not-to-use, but the sibling names and context make it inferable.

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

liveauth_mcp_lnurlB

Get the Lightning invoice for a session (lnget-compatible). Use this to retrieve the BOLT11 invoice for payment.

ParametersJSON Schema
NameRequiredDescriptionDefault
quoteIdYesThe quoteId from the start response

TDQS

B3/5.0
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It only states that the tool retrieves an invoice, but does not clarify side effects, return format, expiration, or whether it is a read-only operation. The mention of 'lnget-compatible' is vague and adds little transparency.

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

Conciseness3/5

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

The description is short and front-loaded, but the two sentences are somewhat redundant: 'Get the Lightning invoice' is repeated as 'retrieve the BOLT11 invoice.' It could be condensed into a single sentence without losing information, so it is not maximally concise.

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

Completeness2/5

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

The tool has only one parameter with good schema coverage, but no output schema and no annotations. The description does not explain what the response looks like, potential errors, or any behavioral context like payment flow or invoice validity. Given the lack of structured metadata, this is insufficient for an agent to fully understand the tool's role.

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?

The input schema already provides 100% coverage by describing quoteId as 'The quoteId from the start response.' The description adds no additional meaning about the parameter, so the baseline score of 3 is appropriate.

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 function: 'Get the Lightning invoice for a session' and also mentions 'retrieve the BOLT11 invoice for payment.' This provides a specific verb and resource, but it does not explicitly differentiate from sibling tools like start, status, or charge, so it does not reach a 5.

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 says 'Use this to retrieve the BOLT11 invoice for payment,' which implies the tool is for obtaining an invoice after starting a session. However, it does not explicitly state when to use it versus alternatives, nor does it mention any prerequisites or exclusions. This falls under implied usage rather than clear guidance.

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

liveauth_mcp_refreshA

Refresh the JWT token without re-authenticating. Use the refreshToken returned from confirm to get a new JWT.

ParametersJSON Schema
NameRequiredDescriptionDefault
refreshTokenYesThe refreshToken from the confirm response

TDQS

A4/5.0
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses a key behavior (no re-authentication required) and the outcome (new JWT). However, it does not mention token rotation, single-use semantics, error handling, or response format, leaving gaps for an agent.

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?

Two concise sentences, no filler. The main purpose is front-loaded, and the parameter guidance is integrated naturally. Every word earns its place.

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?

For a simple one-parameter tool with no output schema, the description is nearly complete: it explains the purpose, the input source, and the expected result (new JWT). It lacks only minor details like potential errors or whether the refresh token is reusable, but these are not critical for basic invocation.

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?

The schema description for refreshToken already provides full coverage (100%), and the tool description essentially restates the same source. Since the schema does the heavy lifting, the description adds minimal extra meaning, hence the baseline score of 3.

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 uses a specific verb+resource ('refresh the JWT token') and explicitly states what it achieves ('get a new JWT'). It also distinguishes itself from siblings by referencing the confirm response, making its role in the auth flow clear.

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?

The description clearly states when to use this tool: after confirm, using the refreshToken from confirm. It implies it is the alternative to re-authenticating, providing a clear context. It does not explicitly list exclusions or alternatives, but the sibling set makes the intended use obvious.

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

liveauth_mcp_startA

Start a new LiveAuth MCP session. Returns a PoW challenge (default), Lightning invoice, or L402 bundle auth hint.

ParametersJSON Schema
NameRequiredDescriptionDefault
forceL402NoIf true, request an L402 bundle auth session
forceLightningNoIf true, request Lightning invoice instead of PoW challenge

TDQS

A3.8/5.0
Behavior3/5

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

With no annotations provided, the description must fully disclose behavioral traits. It does state the return types and the default PoW challenge, but it omits potential side effects, such as whether starting a new session invalidates existing ones or requires prior authentication. This leaves important behavioral context undisclosed.

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 a single, front-loaded sentence that directly states the action and the possible outcomes. It contains no redundant or filler phrases, making it highly concise and well-structured.

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?

For a simple tool with two optional parameters and no output schema, the description covers the core return types and default behavior. While it could provide more detail about the response structure or next steps, the information given is sufficient to understand the tool's basic operation.

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?

The input schema has 100% coverage with descriptive definitions for both boolean parameters. The description adds no additional parameter-level meaning, so the baseline score of 3 is appropriate.

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 uses a specific verb 'Start' and resource 'LiveAuth MCP session', making the purpose unambiguous. It distinguishes itself from sibling tools by clearly indicating this is the initialization action, and it enumerates the distinct return types (PoW challenge, Lightning invoice, L402 bundle).

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 this is the entry point for starting a session, but it does not explicitly state when to use it versus sibling tools like liveauth_mcp_status or liveauth_mcp_charge. No prerequisites or alternative usage scenarios are provided, so the guidance remains at an implied level.

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

liveauth_mcp_statusA

Check the status of an MCP session. Use to poll for Lightning payment confirmation. Also returns the invoice via lnurl compatibility.

ParametersJSON Schema
NameRequiredDescriptionDefault
quoteIdYesThe quoteId from the start response

TDQS

A4/5.0
Behavior3/5

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

With no annotations provided, the description carries the full burden. It reveals that the tool returns an invoice via lnurl compatibility and implies a read-only polling nature, but it doesn't explicitly state read-only behavior, side effects, or what constitutes a 'status.' This is adequate but lacks rich safety or state-change disclosure.

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 two sentences, front-loaded with the primary purpose, and includes a specific usage example. Every sentence adds value with no fluff or redundancy.

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 simplicity (single parameter, no output schema), the description covers the essential context: what it does, when to use it, and a hint about the returned invoice. However, it doesn't describe the full status response structure or possible statuses, which might be useful for a polling tool, but overall it's sufficient for the low complexity.

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% with the only parameter 'quoteId' described as 'The quoteId from the start response.' The description adds no additional parameter-level meaning, but the schema already covers it fully, so the baseline of 3 is appropriate.

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 function: 'Check the status of an MCP session' with a specific use case ('poll for Lightning payment confirmation'). It also distinguishes itself from siblings by focusing on status and polling, and the added detail about lnurl compatibility further clarifies the tool's unique role.

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?

The description explicitly says 'Use to poll for Lightning payment confirmation,' which provides clear guidance for when to invoke this tool. It doesn't mention alternatives or exclusions, but the polling context is sufficient for a status tool in a payment flow, making it clear this is the follow-up to start/confirm actions.

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

liveauth_mcp_usageA

Query current usage and remaining budget for the MCP session. Use this to check how many sats and calls have been used without making a charge.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.3/5.0
Behavior3/5

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

No annotations are provided, so the description must carry the full burden. It does disclose a key behavioral trait: 'without making a charge' indicates the call is non-destructive and free. However, it doesn't clarify whether the usage query itself counts as a call or affect the budget, nor does it explain any side effects or limit conditions. This is a minor gap for a read-only usage tool.

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 two sentences long, front-loaded with the core purpose, and contains no filler. Every word contributes to understanding the tool's function and when to use it.

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

Completeness5/5

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

For a simple tool with no parameters and no output schema, the description is complete. It clearly states what it queries (usage and remaining budget), the metrics (sats and calls), and the key safety aspect (no charge). No additional context is necessary.

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

Parameters4/5

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

The tool has zero parameters, so the baseline is 4. The description adds no parameter details, but none are needed. It correctly focuses on the tool's purpose and usage rather than param syntax.

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 uses a specific verb 'Query' and identifies a clear resource: 'current usage and remaining budget for the MCP session.' It also distinguishes itself from siblings like 'status' and 'charge' by focusing on budget/calls usage, making the purpose unambiguous.

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?

The description explicitly states when to use the tool: 'Use this to check how many sats and calls have been used without making a charge.' This provides clear context and implies it's a non-charging alternative to 'liveauth_mcp_charge'. It doesn't explicitly name alternatives or exclusions, but the guidance is practical and sufficient.

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

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 7 tool updatesv1.0.8
    • First observedliveauth_mcp_charge
    • First observedliveauth_mcp_confirm
    • First observedliveauth_mcp_lnurl
    • First observedliveauth_mcp_refresh
    • First observedliveauth_mcp_start
    • First observedliveauth_mcp_status
    • First observedliveauth_mcp_usage

TDQS

A3.8/5.0
Disambiguation4/5

Each tool maps to a distinct auth lifecycle step: start initiates, lnurl fetches invoice, confirm resolves auth, refresh renews token, charge/usage handle metering, and status reports state. Slight overlap exists between status and confirm when polling payment, but descriptions clarify their primary roles.

Naming Consistency4/5

All tools share the consistent liveauth_mcp_ prefix and snake_case format. Most use verbs (start, confirm, refresh, charge), but status, usage, and lnurl are noun-based, creating minor deviations from a strict verb pattern.

Tool Count5/5

With 7 tools, the set is well-scoped for the server's purpose. Each tool covers a specific function without redundancy, fitting comfortably in the ideal 3-15 tool range.

Completeness5/5

The toolset provides full lifecycle coverage: starting a session, retrieving invoices, confirming authentication, refreshing tokens, and tracking/metering usage. No significant operational gaps are apparent for the stated authentication and payment domain.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    B
    maintenance
    MCP server that enables AI agents to make autonomous Bitcoin Lightning Network payments using the L402 protocol. Agents can pay for API access, purchase resources, and complete transactions without human intervention — invoice comes in, sats go out, done.
    17
    9
    MIT
  • A
    license
    A
    quality
    A
    maintenance
    L402 + x402 client MCP. AI agents discover, pay for, and consume any payment-gated API autonomously. Supports Lightning (NWC), Cashu ecash, stablecoins, and human-in-the-loop payments.
    11
    284
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    MCP server that gates API calls to AI agents using proof-of-work (free) or Lightning payment (3 sats), providing challenge, verify, and status tools for per-call authentication without accounts.
    3
    76
    1
    MIT

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/dulzuradev/liveauth-mcp'

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