Skip to main content
Glama

Lightning Memory

PyPI version Python 3.10+ License: MIT

Persistent memory for AI agents in the Lightning economy.

The Problem

AI agents spend sats over Lightning via L402 — but they can't remember what they bought. Every session starts from zero. Every vendor is a stranger. Every price is accepted at face value. An agent that paid 500 sats yesterday doesn't know if today's 5,000 sat invoice is a price spike or normal.

Related MCP server: giskard-memory

The Solution

L1: Bitcoin      — settles
L2: Lightning    — pays
L3: Lightning Memory — remembers

Lightning Memory gives agents persistent memory, vendor intelligence, and payment safety gates. Agents learn from their spending history, track vendor reputations, detect price anomalies, enforce budgets, and share trust signals with other agents.

Interactive Demo — watch an agent learn, get rugged, and route around bad actors.

Building the Agent Economy — trust, budgets, compliance, and the memory marketplace.

Who Is This For

  • Agents making L402 payments that need vendor reputation and spending discipline

  • Developers building autonomous agents on Bitcoin/Lightning

  • Anyone running an MCP-compatible AI agent (Claude, GPT, or any MCP client)

Quick Start

pip install lightning-memory
lightning-memory  # starts MCP server

Configure in Claude Code

{
  "mcpServers": {
    "lightning-memory": {
      "command": "lightning-memory"
    }
  }
}

Configure in Claude Desktop

{
  "mcpServers": {
    "lightning-memory": {
      "command": "python",
      "args": ["-m", "lightning_memory.server"]
    }
  }
}

How It Compares

Feature

Lightning Memory

Mem0

Raw file storage

No memory

Lightning/L402 awareness

Yes

No

No

No

Vendor reputation tracking

Yes

No

Manual

No

Spending anomaly detection

Yes

No

No

No

Nostr identity (BIP-340)

Yes

No

No

No

Relay sync (NIP-78)

Yes

No

No

No

Full-text + semantic search

Yes

Yes

No

No

Agent-to-agent knowledge markets

Yes (L402 gateway)

No

No

No

Budget enforcement

Yes

No

No

No

KYC/trust profiles

Yes

No

No

No

Payment pre-flight gate

Yes

No

No

No

Contradiction detection

Yes

No

No

No

Local-first / offline

Yes

Cloud

Yes

N/A

MCP native

Yes

Plugin

No

No

Zero config

Yes

API key required

Manual setup

N/A

Tools (22)

Memory

Tool

Description

memory_store

Store a memory (transaction, vendor, preference, error, decision)

memory_query

Search by relevance (FTS5 + optional semantic search)

memory_list

List memories with type/time filters

memory_edit

Edit content or metadata with audit trail

memory_sync

Sync with Nostr relays (push/pull)

memory_export

Export as NIP-78 Nostr events

memory_store(
  content="Paid 500 sats to bitrefill.com for a $5 Amazon gift card via L402.",
  type="transaction",
  metadata='{"vendor": "bitrefill.com", "amount_sats": 500}'
)

memory_query(query="bitrefill payment history", limit=5)
# → recency-weighted results with dedup and contradiction alerts

Lightning Intelligence

Tool

Description

ln_vendor_reputation

Reputation score from transaction history

ln_spending_summary

Spending breakdown by vendor and protocol

ln_anomaly_check

Detect if a payment is abnormally high

ln_vendor_reputation(vendor="bitrefill.com")
# → {reputation: {total_txns: 12, success_rate: 0.92, avg_sats: 450}, recommendation: "reliable"}

ln_anomaly_check(vendor="bitrefill.com", amount_sats=5000)
# → {anomaly: {verdict: "high", context: "5000 sats is 11.1x the historical average..."}}

Payment Safety

Tool

Description

ln_preflight

Pre-flight gate: budget + anomaly + trust check before payment

ln_budget_set

Set per-vendor spending limits (per txn, per day, per month)

ln_budget_check

Check spending against limits

ln_budget_status

Gateway earnings and L402 payment stats

ln_preflight(vendor="bitrefill.com", amount_sats=500)
# → {decision: {verdict: "approve", budget_remaining_today: 4500, trust_score: 0.89}}

# If the vendor suddenly charges 50x:
ln_preflight(vendor="bitrefill.com", amount_sats=25000)
# → {decision: {verdict: "reject", reasons: ["exceeds daily limit of 5000 sats"]}}

Trust & Compliance

Tool

Description

ln_vendor_trust

Full trust profile (KYC + reputation + community score)

ln_trust_attest

Publish NIP-85 trust attestation to Nostr relays

ln_agent_attest

Store a KYA (Know Your Agent) attestation

ln_agent_verify

Look up an agent's compliance status

ln_auth_session

Store LNURL-auth session records

ln_auth_lookup

Look up LNURL-auth sessions

ln_compliance_report

Generate structured compliance export

Marketplace

Tool

Description

ln_discover_gateways

Find remote Lightning Memory gateways via Nostr

ln_remote_query

Query a remote gateway via L402 micropayment

ln_discover_gateways(operation="memory_query")
# → {count: 2, gateways: [{url: "https://gw1.example.com", operations: {...}}, ...]}

ln_remote_query(
  gateway_url="https://gw.example.com",
  operation="ln_vendor_reputation",
  params='{"vendor": "openai"}'
)
# → Pays 3 sats, returns remote agent's vendor intelligence

Architecture

  • Nostr identity: Agent identity = Nostr keypair (BIP-340). No accounts, no API keys.

  • Local-first: SQLite with FTS5 full-text search + optional ONNX semantic search. Works offline.

  • Nostr sync: Memories written as NIP-78 events to relays. Portable, tamper-proof.

  • L402 payments: Pay-per-query gateway. 1-10 sats per operation.

  • Memory quality: Deduplication, contradiction detection, noise filtering, recency-weighted ranking, access tracking.

L402 Gateway

Run an L402 pay-per-query HTTP gateway. Other agents pay Lightning micropayments to access your agent's memory — no API keys, no accounts.

pip install lightning-memory[gateway]
lightning-memory-gateway  # Listening on 0.0.0.0:8402

How L402 Works

Agent                          Gateway                      Phoenixd
  |                               |                            |
  |-- GET /memory/query?q=... --->|                            |
  |<-- 402 + Lightning invoice ---|--- create_invoice -------->|
  |                               |<-- bolt11 + payment_hash --|
  |                               |                            |
  | [pay invoice via Lightning]   |                            |
  |                               |                            |
  |-- GET + L402 token ---------->|                            |
  |   (macaroon:preimage)         |--- verify preimage ------->|
  |<-- 200 + query results -------|                            |

Endpoints

Endpoint

Method

Price

Description

/info

GET

Free

Gateway status, pricing, node info

/health

GET

Free

Health check

/memory/store

POST

3 sats

Store a memory

/memory/query

GET

2 sats

Search memories by relevance

/memory/list

GET

1 sat

List memories with filters

/ln/vendor/{name}

GET

3 sats

Vendor reputation report

/ln/spending

GET

2 sats

Spending summary

/ln/anomaly-check

POST

3 sats

Payment anomaly detection

/ln/preflight

POST

3 sats

Pre-flight payment gate

/ln/trust/{name}

GET

2 sats

Vendor trust profile

/ln/budget

GET

1 sat

Budget rules and spending

/ln/compliance-report

GET

10 sats

Compliance report export

Phoenixd Setup

  1. Download and run Phoenixd (listens on localhost:9740)

  2. Fund it with ~10,000 sats for initial channel opening

  3. Configure: ~/.lightning-memory/config.json → {"phoenixd_password": "<from ~/.phoenix/phoenix.conf>"}

  4. Start: lightning-memory-gateway

Docker

PHOENIXD_PASSWORD=your-password docker compose up

CLI Commands

lightning-memory                  # Start MCP server
lightning-memory stats            # Memory statistics dashboard
lightning-memory export json      # Export memories as JSON
lightning-memory export csv       # Export memories as CSV
lightning-memory relay-status     # Check Nostr relay connectivity
lightning-memory-gateway          # Start L402 HTTP gateway
lightning-memory-manifest         # Generate gateway discovery manifest

Relay Configuration

Default relays: wss://relay.damus.io, wss://nos.lol, wss://relay.nostr.band

Customize in ~/.lightning-memory/config.json:

{
  "relays": ["wss://relay.damus.io", "wss://nos.lol", "wss://relay.primal.net"],
  "sync_timeout_seconds": 30,
  "max_events_per_sync": 500
}

Relay

Speed

Reliability

Notes

wss://relay.damus.io

Fast

High

Most popular, good uptime

wss://nos.lol

Fast

High

Reliable, good NIP-78 support

wss://relay.nostr.band

Medium

Medium

Search-focused, may be slow

wss://relay.primal.net

Fast

High

Well-maintained

wss://nostr.wine

Fast

High

Paid relay, less spam

Add ONNX-based semantic similarity search alongside FTS5 keyword search:

pip install lightning-memory[semantic]

Queries then use hybrid ranking: FTS5 BM25 + cosine similarity with reciprocal rank fusion. "Which vendors are reliable for transcription" matches memories containing "whisper API" and "audio-to-text" even without exact keyword overlap.

Data Storage

~/.lightning-memory/
  memories.db    # SQLite database
  keys/
    private.key  # Nostr private key (chmod 600)
    public.key   # Nostr public key (your agent identity)

Roadmap

  • Phase 1: MCP server with local SQLite storage

  • Phase 2: Lightning intelligence (vendor reputation, spending summary, anomaly detection)

  • Phase 3: Nostr relay sync (NIP-78, Schnorr signing, bidirectional sync)

  • Phase 4: L402 payment gateway (macaroons, Phoenixd, HTTP gateway)

  • Phase 5: Compliance & trust (budget enforcement, vendor KYC, community reputation, pre-flight gate)

  • Phase 6: Memory marketplace (gateway discovery, remote L402 queries, gateway client)

  • Phase 7: Agent reliability (semantic search, deduplication, contradiction detection, circuit breakers)

Star History

Star History Chart

License

MIT

Available Tools

22 tools
ln_agent_attestA

Store an attestation about an agent's identity and compliance status.

Used for Know Your Agent (KYA) — agents self-attesting, operators attesting their agents, or third-party KYA providers.

Args: agent_pubkey: The agent's Nostr public key (64 hex chars). owner_id: Owner identifier (email, company name, etc.). jurisdiction: Legal jurisdiction (e.g., "US", "EU", "SG"). compliance_level: One of: unknown, self_declared, kyc_verified, regulated_entity. source: Verification source (e.g., "manual", "sumsub", "trulioo").

Returns: The stored attestation record.

Inputs: agent_pubkey (required), owner_id, jurisdiction, compliance_level, +1 more.

ln_agent_verifyA

Look up an agent's compliance attestation.

Args: agent_pubkey: The agent's Nostr public key to verify.

Returns: Attestation details or {status: "unknown"} if not found.

Inputs: agent_pubkey (required).

ln_anomaly_checkA

Check if a proposed payment amount is normal for a vendor.

Use this before making a payment to catch price anomalies. Compares the proposed amount against historical averages.

Args: vendor: Vendor name or domain. amount_sats: Proposed payment amount in satoshis.

Returns: Anomaly report: verdict (normal/high/first_time), context, and historical average.

Inputs: vendor (required), amount_sats (required).

ln_auth_lookupA

Check if an LNURL-auth session exists with a vendor.

Args: vendor: Vendor name or domain to check.

Returns: Session details if found, or {has_session: false}.

Inputs: vendor (required).

ln_auth_sessionB

Store or update an LNURL-auth session record.

Record-keeping for externally-established LNURL-auth sessions.

Args: vendor: Vendor name or domain. linking_key: The LNURL-auth linking key for this vendor. session_state: Session state: active, expired, or revoked.

Returns: The stored session record.

Inputs: vendor (required), linking_key (required), session_state.

ln_budget_checkA

List budget rules and current spending status.

Shows all active budget rules, or details for a specific vendor including how much has been spent today and this month.

Args: vendor: Optional vendor to check. If omitted, lists all rules.

Returns: Budget rules with current spending against limits.

Inputs: vendor.

ln_budget_setA

Set spending limits for a vendor.

Creates budget rules that the pre-flight gate enforces. Any payment exceeding these limits will be rejected.

Args: vendor: Vendor name or domain (e.g., "bitrefill.com"). max_sats_per_txn: Maximum sats allowed per single transaction. max_sats_per_day: Maximum total sats per day to this vendor. max_sats_per_month: Maximum total sats per month to this vendor.

Returns: The created/updated budget rule.

Inputs: vendor (required), max_sats_per_txn, max_sats_per_day, max_sats_per_month.

ln_budget_statusA

Check L402 gateway earnings and payment stats.

Shows total sats earned from L402 gateway payments, broken down by operation. Reads from locally stored payment records (logged by the gateway).

Returns: Earnings summary: total sats, payment count, breakdown by operation.

Inputs: no named parameters.

ln_compliance_reportA

Generate a structured compliance report.

Produces a comprehensive report covering agent identity, transactions, budget rules, vendor KYC status, anomaly flags, and trust attestations. Designed for regulatory compliance export.

Args: since: Time period for temporal data. Relative: "1h", "24h", "7d", "30d". Current-state data (budget rules, KYC) is always included. format: Output format. Only "json" supported in v1.

Returns: Compliance report as a structured dict.

Inputs: since, format.

ln_discover_gatewaysA

List known Lightning Memory gateways discovered via Nostr relays.

Args: operation: Optional filter — only return gateways offering this operation (e.g., "memory_query", "ln_vendor_reputation").

Returns: List of known gateways with URL, operations, pricing, and last seen time.

Inputs: operation.

ln_preflightA

Pre-flight check before making a payment.

Runs budget limits, anomaly detection, and trust verification to produce an approve/reject/escalate decision. Use this before every payment to catch overspending, price anomalies, and unverified vendors.

Args: vendor: Vendor name or domain. amount_sats: Proposed payment amount in satoshis.

Returns: Decision: verdict (approve/reject/escalate), reasons, budget remaining, anomaly status, and trust score.

Inputs: vendor (required), amount_sats (required).

ln_remote_queryB

Query a remote Lightning Memory gateway via L402 micropayment.

Pays the gateway's Lightning invoice automatically via Phoenixd, then returns the query results. The payment is logged as a transaction memory.

Args: gateway_url: URL of the remote gateway (e.g., "https://gw.example.com"). operation: Operation to perform. One of: memory_query, memory_list, ln_vendor_reputation, ln_spending_summary, ln_anomaly_check, ln_preflight, ln_vendor_trust, ln_budget_check, ln_compliance_report. params: JSON string of operation-specific parameters.

Returns: Remote gateway's response data, or error details.

Inputs: gateway_url (required), operation (required), params.

ln_spending_summaryB

Get a spending summary for budget awareness.

Shows total sats spent, broken down by vendor and protocol.

Args: since: Time period. Relative: "1h", "24h", "7d", "30d". Or Unix timestamp.

Returns: Spending breakdown with totals by vendor and protocol.

Inputs: since.

ln_trust_attestA

Publish a trust attestation for a vendor.

Creates a NIP-85 Trusted Assertion and pushes it to Nostr relays. Other agents can pull these attestations to build community reputation.

Args: vendor: Vendor name or domain to attest. score: Trust score 0.0-1.0. If omitted, auto-calculated from local reputation (success_rate * volume factor). basis: Reason for the score (default: "transaction_history").

Returns: Attestation details including score and relay push status.

Inputs: vendor (required), score, basis.

ln_vendor_reputationA

Check a vendor's reputation based on transaction history.

Use this before paying a vendor to see if they're reliable. Aggregates all past transactions to build a reputation score.

Args: vendor: Vendor name or domain (e.g., "bitrefill.com", "openai").

Returns: Reputation report: total transactions, total sats spent, success rate, average payment size, and tags.

Inputs: vendor (required).

ln_vendor_trustA

Get a vendor's full trust profile.

Combines KYC verification status, local transaction reputation, and community trust attestations (from Nostr NIP-85) into a unified trust profile.

Args: vendor: Vendor name or domain.

Returns: Trust profile: KYC status, jurisdiction, community score, attestation count, and local reputation data.

Inputs: vendor (required).

memory_editA

Edit an existing memory's content or metadata.

Use this to correct wrong vendor information, update prices, or add context to an existing memory. Tracks edit history.

Args: id: The memory ID to edit. content: New content to replace the existing content. If omitted, content is unchanged. metadata: JSON string of metadata fields to merge into existing metadata. Example: '{"vendor": "bitrefill.com", "note": "price updated"}'

Returns: The updated memory record with old_content_preview for audit trail.

Inputs: id (required), content, metadata.

memory_exportA

Export memories as Nostr NIP-78 events.

Converts local memories into portable Nostr event format. Events are signed if secp256k1 is available. Useful for backup, sharing, or manual relay publishing.

Args: limit: Maximum number of memories to export (default 100).

Returns: List of NIP-78 events with memory content.

Inputs: limit.

memory_listA

List memories, optionally filtered by type and time range.

Use this to browse recent memories, check all transactions, or review memories of a specific type.

Args: type: Filter by memory type (transaction, vendor, preference, error, decision, general). since: Time filter. Relative: "1h", "24h", "7d", "30d". Or Unix timestamp. limit: Maximum number of results (default 50, max 200).

Returns: List of memories in reverse chronological order with stats.

Inputs: type, since, limit.

memory_queryA

Search memories by relevance. Returns the most relevant matches.

Use this to recall past transactions, check vendor reputation, retrieve spending patterns, or find any previously stored information.

Args: query: Natural language search query. Examples: - "bitrefill payment history" - "which APIs gave rate limit errors?" - "spending decisions this week" limit: Maximum number of results (default 10, max 100). type: Optional filter by memory type (transaction, vendor, preference, error, decision, general).

Returns: List of matching memories ranked by relevance, with scores.

Inputs: query (required), limit, type.

memory_storeA

Store a memory for later retrieval.

Use this to remember transactions, vendor experiences, decisions, spending patterns, API responses, or any information worth recalling.

Args: content: The memory content to store. Be descriptive. Examples: - "Paid 500 sats to bitrefill.com for a $5 Amazon gift card via L402. Fast, reliable." - "OpenAI API returned 429 rate limit after 50 requests/min. Backoff to 30/min." - "User prefers to cap spending at 10,000 sats per session." type: Memory category. One of: - general: Default, uncategorized - transaction: Payment records, invoices, L402 purchases - vendor: Service/API reputation and reliability notes - preference: User or agent preferences and settings - error: Error patterns and failure modes - decision: Key decisions and their reasoning metadata: JSON string of additional key-value pairs. Example: '{"vendor": "bitrefill.com", "amount_sats": 500}'

Returns: The stored memory record with id, content, type, and timestamps.

Inputs: content (required), type, metadata.

memory_syncA

Sync memories with Nostr relays.

Push local memories to relays and/or pull remote memories to local. When gateway_discovery is enabled, also syncs gateway announcements. Requires secp256k1 for push (signing). Pull works with any identity.

Args: direction: Sync direction. One of: - "push": Upload local memories to relays - "pull": Download memories from relays - "both": Push then pull (default)

Returns: Sync result with counts of pushed/pulled memories and any errors.

Inputs: direction.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 22 tools

    Disambiguation4/5

    Most tools have distinct purposes. There is some overlap like ln_vendor_reputation vs ln_vendor_trust, but descriptions clarify differences. The ln_preflight tool bundles multiple checks but is clearly described as a composite.

    Naming Consistency5/5

    All tools follow a consistent pattern: 'ln_' prefix for Lightning-related and 'memory_' for memory operations. Verbs are consistent and all snake_case.

    Tool Count3/5

    22 tools is on the higher side for a single server. While each tool has a clear role, some could potentially be combined (e.g., multiple budget tools). The count feels slightly bloated for the domain.

    Completeness4/5

    The tool surface covers memory CRUD, budget, compliance, vendor reputation, and remote queries. Minor gaps exist: no memory delete, no revoke attestation, but overall coverage is solid.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      MCP server exposing a Lightning wallet to LLM agents over Nostr Wallet Connect (NIP-47): balance, invoices, LN address/LNURL payments, batch pay, and keysend. All spend tools are wrapped in a defense-in-depth safety stack — budget caps, allowlist, two-step confirmation, audit log.
      13
      54 npm
      MIT

    Appeared in Searches