I Built an Open-Source Agent OS

I built an operating system for AI agents.

Not a terminal. Not a chat app. A full dashboard that coordinates three agents — opencode (code/DevOps), Hermes Agent (memory/scheduling), and Gemini CLI (research) — into one unified control plane.

GitHub: github.com/modimihir07/agentic-os (https://github.com/modimihir07/agentic-os)

The Problem
I was jumping between three tools:

  • opencode for coding tasks
  • Hermes for scheduling and memory
  • Gemini CLI for web research

No shared context. No central dashboard. Every session started from zero.

The Solution: 7-Layer Architecture
Layer 7 Identity / Constitution
Layer 6 Self-Evolution
Layer 5 Scheduler + Health
Layer 4 Memory Graph
Layer 3 Skills Hub + Eval
Layer 2 Business Brain
Layer 1 Agent Router

Layer 1 routes tasks automatically: code → opencode, memory → Hermes, research → Gemini.

Layer 3 gives each skill a standardized structure (SKILL.md + learnings + eval + score history) so they improve over time.

Layer 4 provides persistent memory via a shared brain/ folder and SQLite FTS5 — agents remember context across sessions.

12 Features

  • 3-Agent Engine — opencode + Hermes + Gemini CLI with auto-routing
  • 16 Skills — executable packs with eval scoring
  • Cron Scheduler — APScheduler jobs (heartbeat, standup, audit)
  • Cost Analytics — track spending across providers
  • One-Click Backup — full tar.gz snapshots
  • Audit Trail — every action logged
  • Prompt Library — 10 reusable templates
  • Dark/Light Theme — GitHub-style dark mode
  • Standards System — auto-discover project conventions
  • Plugin Registry — extend via custom skills
  • Client Timeout — 200s AbortController for long queries
  • Memory — SQLite FTS5 + shared brain/ files

vs Claude Agent OS
Honest comparison with Julian Goldie’s video project:

Claude Agent OS: Claude + OpenClaw + Hermes · $20/mo · Obsidian memory · No cost tracking · No backup · Tutorial only

Agentic OS (Mine): opencode + Hermes + Gemini · $0 (all free tiers) · Built-in memory · Built-in cost tracking · One-click backup · MIT License

Tech Stack
Backend: FastAPI (Python) · Frontend: vanilla JS SPA · Scheduler: APScheduler · Memory: SQLite FTS5 · Cost: $0 (Gemini Flash, OpenRouter free models)

Quick Start
git clone https://github.com/modimihir07/agentic-os.git
cd agentic-os && ./install.sh && ./start.sh
Open http://127.0.0.1:8080

Agentic OS is MIT licensed. Star it on GitHub if you find it useful.
👉 github.com/modimihir07/agentic-os (https://github.com/modimihir07/agentic-os)

Building an open-source Windows file transfer app with Rust, Tauri and QUIC

Building an open-source Windows file transfer app with Rust, Tauri and QUIC

I recently launched Lightning P2P, an open-source Windows file transfer app.

The idea is simple:

Select a file → generate a link or QR code → receive the file.

No account.

No cloud upload.

No artificial storage dashboard.

Just direct-first file transfer.

GitHub: https://github.com/Kerim-Sabic/lightning-p2p

Product Hunt: https://www.producthunt.com/products/download-lightning-p2p

Why I built it

File transfer still feels more complicated than it should, especially on Windows.

If you want to send a file from one device to another, you usually end up with one of these options:

  • upload it to cloud storage
  • send it through a messaging app
  • use a USB cable
  • use a tool that only works on the same LAN
  • create an account somewhere
  • deal with file-size limits
  • use something powerful but too technical for normal users

AirDrop solved this feeling well inside Apple’s ecosystem.

But outside that ecosystem, especially for Windows users, the experience still feels fragmented.

I wanted to build something closer to:

“I have a file. I want to send it now. I do not want to create an account or upload it somewhere first.”

That became Lightning P2P.

What Lightning P2P does today

The current release is Windows-first.

It lets you share files using a simple receive link or QR code flow.

Current state:

  • Windows release available
  • Android sideload alpha
  • open-source
  • no account system
  • no cloud storage bucket
  • direct-first transfer
  • relay fallback when direct connection is blocked
  • sender must stay online during transfer

The goal is not to make another complicated sync tool.

The goal is a simple file transfer experience that normal users can understand, while still being technically serious underneath.

Tech stack

The current stack is:

  • Rust for the backend
  • Tauri for the desktop app
  • iroh/QUIC for the transfer layer
  • BLAKE3 for file verification
  • mDNS for nearby discovery
  • Windows-first packaging
  • Android alpha for receiving/testing flows

I chose Rust because this type of app needs reliability, performance, and a strong foundation for networking and file handling.

I chose Tauri because I wanted a desktop app that feels lightweight and native enough, without shipping a massive Electron-style bundle.

For the transfer layer, iroh/QUIC is interesting because it supports a modern direct-first networking model while still allowing relay fallback when direct connections are blocked.

Direct-first does not mean “direct always”

One important design decision was to be honest about networking.

In an ideal world, two devices connect directly and transfer the file peer-to-peer.

In the real world, NATs, firewalls, corporate networks, mobile networks, routers, and operating systems make this harder.

So the model is:

  1. Try direct transfer first.
  2. Use relay fallback when direct connection is blocked.
  3. Avoid using a cloud storage bucket as the primary transfer path.
  4. Keep the sender online while the transfer is available.

This distinction matters.

Lightning P2P is not trying to pretend that networking is magic. The product should explain clearly what happens, what is private, and what limitations exist.

Security and trust model

The current security model is still being improved, but the basic principles are:

  • no account required
  • no cloud storage bucket
  • transfer links / QR codes act like capability tokens
  • anyone with a valid receive link can request the file while it is available
  • BLAKE3 is used for verification
  • the sender must remain online
  • nearby discovery should be treated as suitable for trusted networks

This is one of the areas where I especially want feedback.

File transfer apps are easy to make look simple, but the trust model needs to be precise.

Users should understand:

  • who can access the file
  • whether the file is uploaded somewhere
  • whether a relay can store the file
  • whether the sender must stay online
  • what happens if a link is shared accidentally
  • what happens on public Wi-Fi
  • what guarantees the app does and does not provide

I would rather be conservative and clear than make vague claims.

What makes this different from existing tools?

There are already good tools in this space.

Some examples:

  • AirDrop
  • LocalSend
  • Magic Wormhole
  • Syncthing
  • Snapdrop / PairDrop
  • WeTransfer
  • Dropbox
  • Google Drive

I am not trying to claim that Lightning P2P replaces all of them.

The difference is the product direction.

AirDrop has the best mainstream UX, but it is locked inside Apple’s ecosystem.

LocalSend is excellent, especially for LAN transfer.

Magic Wormhole is technically elegant, but it is more comfortable for technical users.

Syncthing is powerful, but it is more of a sync system than a quick “send this file now” flow.

Cloud tools are familiar, but they usually involve accounts, uploads, storage limits, and a different privacy model.

Lightning P2P is trying to sit in a specific place:

simple enough for normal Windows users, open enough for developers, and direct-first enough for people who do not want every file transfer to become a cloud upload.

What I am not claiming yet

I am not claiming speed leadership.

Proper public benchmarks still need to be published.

I also do not want to oversell the current state. This is still early.

Current limitations:

  • Windows is the main supported platform
  • Android is alpha/sideload only
  • macOS and Linux are planned but not shipped yet
  • sender must stay online
  • public benchmarks are not ready yet
  • receive links need to be treated carefully because they act like capability tokens

I think open-source projects earn trust faster when they are clear about what is missing.

What I want feedback on

I would really appreciate feedback from developers, open-source builders, Windows users, and anyone who has worked on networking or desktop apps.

The main areas where feedback would help:

  • NAT traversal reliability
  • relay fallback model
  • security model
  • receive-link capability tokens
  • installer trust and signing on Windows
  • Android UX
  • whether macOS/Linux should come next
  • README clarity
  • benchmarks to include
  • comparison with existing tools

GitHub issues, comments, criticism, and suggestions are all useful.

Roadmap

The near-term roadmap is:

  1. Improve the Windows release experience
  2. Add a clearer demo GIF/video
  3. Publish public benchmarks
  4. Improve security documentation
  5. Improve Android alpha
  6. Add macOS/Linux support
  7. Add clearer comparison docs
  8. Improve NAT traversal diagnostics
  9. Add more contributor-friendly issues
  10. Build a stronger open-source community around the project

Longer term, I would like Lightning P2P to become a trusted open-source file transfer layer that works across platforms without forcing users into accounts or cloud storage.

Links

GitHub:

https://github.com/Kerim-Sabic/lightning-p2p

Product Hunt:

https://www.producthunt.com/products/download-lightning-p2p

If the project looks useful, feedback on the repo would mean a lot.

I am especially interested in technical criticism around the networking model, security assumptions, and what should be prioritized next.

Built a Network Traffic Classifier with Random Forest (96.8% Accuracy)

I recently completed a cybersecurity + machine learning project where I trained a Random Forest model to classify network traffic into multiple attack categories using the NSL-KDD dataset.

The classifier can detect:

DoS attacks
Probe/reconnaissance traffic
R2L brute-force attempts
U2R privilege escalation
Normal traffic
Stack
Python
Scikit-learn
FastAPI
Pandas / NumPy
Results
96.8% Accuracy
<1ms inference time
Production-ready model packaging

I also wrote a detailed Medium article covering:

Dataset preprocessing
Feature selection
Model training
API integration
Real-world deployment considerations
Challenges working with synthetic vs real traffic data

Would appreciate feedback from the community, especially from people working in:

Cybersecurity
ML Engineering
Intrusion Detection
Backend Systems

Article: https://medium.com/@gulrezqayyum/building-a-production-ready-network-traffic-classifier-with-random-forest-and-nsl-kdd-b9559346e197

GitHub:
https://github.com/GulrezQayyum

LinkedIn:
https://www.linkedin.com/in/gulrez-qayyum-999345322/

OpenSparrow – open-source admin panel builder, zero dependencies, v2.1 just dropped

OpenSparrow – open-source admin panel builder, zero dependencies, v2.1 just dropped

Hey everyone!

I want to share a project I’ve been building — OpenSparrow, an open-source visual admin panel framework.

The idea: connect it to a PostgreSQL database, and you get a fully working admin panel — tables, forms, dashboards, calendar, file uploads — configured entirely through a visual /admin interface. No JSON to write by hand.

The stack is minimalist: PHP 8.1+, PostgreSQL, Vanilla JS. No npm. No Composer. No jQuery. No external libraries on either side. Pure code only.

What you get out of the box:

  • Visual table builder — create columns, set types, foreign keys, validation rules — all in the UI.
  • Full CRUD with inline cell editing, searchable FK columns, and subtables.
  • Dashboard builder — stat cards, KPI cards, bar/pie charts, and data lists with live WHERE filters.
  • Calendar view + cron-based notifications.
  • Audit trail + optional record snapshots (full JSONB history of every change).
  • User roles: Admin, Editor, Viewer.
  • Security defaults: rate limiting, CSRF, session fingerprinting, HSTS.

LGPL v3 — free for commercial use.

Version 2.1 just released with a major UX overhaul, new modules, and security fixes. More on that in the next post.

Feedback and contributors are very welcome!

Building AI Quality Checks for Construction Billing: Lessons from Real Pay Application Errors

Building AI Quality Checks for Construction Billing: Lessons from Real Pay Application Errors

We build construction billing software, and after seeing the same pay app mistakes repeatedly, we started experimenting with AI-assisted quality checks. Here’s what surprised us…

Most people working on AI tools right now are building chatbots, coding
assistants, or trying to automate customer support.

We ended up using AI for something much less glamorous:

Trying to catch construction billing mistakes before a subcontractor
submits a pay application and waits 30 days to find out something
doesn’t tie out.

Not exactly Silicon Valley material.

But if you’ve spent any time around construction billing, you know this
stuff matters. A missed retainage calculation or a continuation sheet
mismatch can delay payments, trigger back-and-forth emails, or force
someone to rebuild a spreadsheet at 8 PM on a Friday.

We build software for construction pay applications, and after seeing
the same mistakes repeat over and over, we started asking:

Could AI review a pay app the way an experienced billing person would?

Not write it. Review it.

That distinction matters.

The Problem: Most Errors Aren’t Obvious

The funny thing about construction billing errors is that they’re rarely
dramatic.

Nobody submits:

Current payment due: $500,000
Previous billing: BANANA

The mistakes are subtle.

  • Retainage doesn’t match historical calculations
  • Stored materials are billed but unsupported
  • Approved change orders weren’t included
  • Continuation sheet totals don’t roll correctly
  • Prior application amounts don’t align
  • Schedule of Values values shifted over time
  • Attachments are missing
  • Billing percentages exceed expected ranges

Can software catch them earlier?

We Didn’t Want AI to Replace Rules

Construction billing has lots of deterministic logic.

If approved change orders exist but contract values don’t update, that
isn’t AI — that’s math.

We separated checks into:

Rule-based checks

  • Missing project information
  • Amount mismatches
  • Retainage inconsistencies
  • Missing required documents
  • Invalid percentages
  • Change order math

AI-assisted checks

  • Does this billing pattern look unusual?
  • Is supporting documentation probably insufficient?
  • Does this resemble submissions that get kicked back?
  • Is there risk despite passing calculations?

The First Versions Were Annoying

Users hated outputs like:

FACT:
Stored materials exist.

Users preferred:

Issue:
Stored materials billed without supporting documentation.

Suggestion:
Attach invoices or supplier documentation.

Actionable beats informative.

Scoring Was Harder Than Detection

Not all issues carry equal risk:

  • Minor issue: -2
  • Moderate issue: -7
  • High impact issue: -20

Construction workflows differ, so tuning never stops.

Legacy Systems Add Weird Constraints

Real systems often still use:

  • Older PHP
  • Older MySQL
  • Limited JSON support

Building AI features without breaking existing workflows is harder than
it sounds.

AI Needs Context

Numbers alone create false alarms.

Historical billing, retainage overrides, stored materials, and change
orders all matter.

Context matters more than intelligence.

The Goal Isn’t Perfection

The goal is reducing avoidable delays and catching obvious problems
earlier.

If software prevents one rejected pay app or one payment delay, it
created value.

Final Thought

Some of the most useful AI applications aren’t flashy.

Sometimes they’re reviewing retainage calculations before a pay
application goes out the door.

That might matter more.

Where have you seen AI help in operational workflows — and where do
traditional rules still outperform it?

We build software that helps contractors streamline construction billing workflows, pay applications, and related processes.

Learn more:
https://payapppro.com/

Early Warning Systems for Loan Delinquency Prediction and Credit Risk Monitoring

early warning systems

Introduction

In lending, **delinquency **refers to a borrower failing to meet contractual repayment obligations on time, usually measured by days past due. In practice, even a 30-day delay can be an early signal that the borrower is moving from a temporary slip into a more serious repayment problem, while 90 days past due is often treated as a much stronger sign of financial difficulty.

This is why early warning systems matter: they help lenders identify risk before a loan turn into a loss, giving them time to adjust terms, contact borrowers, or trigger internal review processes. At the portfolio level, forecasting delinquency is important for stability and for meeting regulatory expectations around credit risk management.

A simple way to think about an early warning system is as a pipeline: borrower and repayment data go into a predictive model, the model produces a risk signal, and the lender decides whether to intervene. Traditional rule-based systems can flag obvious issues such as missed-payment thresholds, but predictive analytics can capture more subtle patterns that build up over time. For a realistic example, the UCI Default of Credit Card Clients dataset contains 30,000 instances and 23 features, including repayment history and bill/payment behavior across multiple months, which makes it a useful production-like reference point for this kind of problem.

early warning systems

Common techniques for early delinquency detection

Before moving to machine learning, it is useful to ground the problem in the methods many lenders already use. In practice, **rules-based systems **are often the first layer of defence: if an account crosses a threshold such as repeated missed payments, a sharp rise in credit utilization, or a low credit-score band, the system triggers an alert for review. These approaches are simple, fast, and easy to operationalize, but they are also backward-looking, so they can miss earlier warning signs that develop before a hard delinquency event appears.

That limitation is why **temporal and sequence modelling matters. **Delinquency rarely happens as a single isolated event; it often builds over time through a worsening payment pattern, increasing utilization, or inconsistent repayment behavior. Credit risk models that use time-varying covariates are designed to capture exactly this kind of evolution, rather than treating each borrower as a static snapshot. The UCI credit card default dataset is a good example of this structure because it includes monthly repayment status, bill amounts, and previous payment amounts across several months, which makes the time order of behavior visible.

A simple example is enough to show the idea: if a borrower’s monthly payments start falling over consecutive months while utilization rises, that pattern is more informative than a single missed payment. In the article, this section should stay conceptual, with a small timeline diagram placed right after the paragraph to show how a rule-based alert might evolve over months.

Common techniques for early delinquency detection

Machine learning approaches for early warning systems

Modern early warning systems go beyond static rules by learning delinquency patterns directly from historical loan performance. Instead of reacting only after a borrower crosses a fixed threshold, ML models can combine payment history, bureau data, utilization trends, income signals, and loan terms to estimate risk earlier and more flexibly. In practice, supervised learning is the most common starting point: the model is trained in labeled outcomes such as delinquent versus non-delinquent accounts. Strong baseline models include logistic regression, decision trees, random forests, and gradient boosting methods such as XGBoost or LightGBM. The value is not only in the algorithm, but in the feature engineering: missed-payment counts, rolling payment ratios, balance growth, utilization spikes, and recent behavior trends often carry more signal than static borrower attributes alone.

The main challenge is class imbalance. In credit portfolios, delinquent accounts are usually a small fraction of the total, so accuracy can look high while the model still misses many risky borrowers. That is why precision, recall, and PR-AUC are usually more informative than accurate. Techniques such as class weighting, threshold tuning, and oversampling methods like SMOTE can help, but they should be used carefully so the model does not become overconfident on rare events.

When labels are limited, unsupervised and semi-supervised learning can help discover emerging risk. Clustering can separate normal borrower behavior from unusual patterns, while anomaly detection methods like Isolation Forest or autoencoders can flag outliers that do not match the majority population. A semi-supervised approach is especially useful when you trust the “normal” class more than the delinquent labels, because it can learn the baseline behavior and detect deviations from it.

For sequential credit behavior, RNNs or Transformer-based models can use the full time series of borrower activity rather than flattened snapshots. This is especially useful when delinquency develops gradually over several months.

A simple way to structure this section visually is:

Machine learning approaches for early warning systems

Tutorial: Implementing early warning systems with Weights & Biases

This tutorial is a real workflow: inspect borrower data, train a model, test thresholds, orchestrate the steps, and then monitor the system in production. W&B Tables are meant for visualizing and querying tabular data, W&B Experiments track metrics, configuration, and artifacts, and Weave provides traceable evaluation workflows with visibility into inputs, outputs, and production monitoring.

Implementing early warning systems with Weights & Biases

Step 1: Data logging with W&B Tables

  • Start by loading a realistic credit-risk dataset and logging a sample of borrower-level rows. W&B Tables are designed for tabular inspection, so this is the right place to store borrower features, repayment history, and outcome labels in a way that is easy to browse and filter in the UI.
  • This gives you a visible table artifact where you can inspect examples, compare rows, and look for patterns in both labelled and unlabeled borrower behavior. That is especially useful when you want to understand how delinquency evolves over time rather than treating each account as a flat record.

Data logging with W&B Tables sample code

This gives you a visible table artifact where you can inspect examples, compare rows, and look for patterns in both labelled and unlabeled borrower behavior. That is especially useful when you want to understand how delinquency evolves over time rather than treating each account as a flat record.

Step 2: Model training and experiment tracking

  • Next, train a predictive model and track the run in W&B. The Experiments docs show the standard pattern: create a run with wandb.init(), store hyperparameters in run.config, log metrics with run.log(), and save model outputs as artifacts.

Model training and experiment tracking sample code

  • This is the point where the model becomes comparable across runs: different feature sets, different time windows, and different algorithms can all be tracked in the same workspace. W&B’s logging flow is built for exactly this kind of experiment comparison.

Step 3: Threshold experiments and trade-offs

  • Now the decision threshold and track how precision, recall, and business cost change. W&B’s logging system supports metrics over time and custom plots, so a threshold sweep can be shown clearly as a line chart or table in the dashboard.

Threshold experiments and trade-offs sample code

  • The key point to explain here is the trade-off: lower thresholds usually catch more risky borrowers early, but they also increase false positives. That is exactly why early warning systems need both model quality metrics and a business decision layer.

Step 4: Workflow orchestration with Weave

  • For the workflow layer, use Weave to keep the steps reproducible and traceable. The docs describe Weave as an observability and evaluation platform, with evaluation objects, datasets, scoring functions, and tracked model or function calls. In this article, you can present that as the orchestration layer that ties preprocessing, scoring, and evaluation together.

Workflow orchestration with Weave sample code

Step 5: Deployment monitoring and drift detection

  • Finally, monitor live scores and borrower outcomes after deployment. W&B Alerts can be triggered from Python with run.alert(), and the docs show that alerts can be sent to Slack or email when a custom condition is met. That makes it suitable for flagging degraded performance, anomalous input shifts, or failing pipeline stages

Deployment monitoring and drift detection sample code

  • The full loop: deploy → monitor → detect drift → retrain → redeploy. That is the production mindset behind an early warning system, and Weave/W&B together give you the tracking, evaluation, and alerting surface to support it.

Code run outputs and W&B graphs

To make the tutorial feel complete, include the outputs produced by the code runs, not just the code itself. The most useful artifacts are a validation summary, a threshold sweep table, and graphs that show how precision and recall change as the decision threshold moves. These are the same kinds of visual outputs you would capture from W&B and place directly under the relevant step.

Example validation output:

Console-style output from the run:

Validation run
accuracy: 0.958
precision: 0.863
recall: 0.587
roc_auc: 0.930

Threshold sweep snapshot:

Figure 1. Precision and recall across thresholds.

Figure 2. ROC curve from the validation run.

Figure 3. Confusion matrix at threshold 0.5.

Conclusion

In summary, an effective early warning system for loan delinquency combines predictive modelling with continuous monitoring, rather than relying on a one-time score. Recent work on SME loan delinquency highlights the need for accurate, interpretable forecasting to support portfolio stability and regulatory requirements, while drift-aware credit-risk research shows why monitoring must continue after deployment as borrower behavior and market conditions change. W&B helps with experiment tracking, tabular inspection, and alerting, while Weave adds traceability and versioned workflow orchestration, which makes the whole pipeline easier to reproduce and maintain.

Recommended Datasets and Synthetic Data

Public Dataset Recommendation: For a realistic example, use a real dataset. Candidates include:

  • UCI “Default of Credit Card Clients” (30,000 Taiwan loan records with features like payment history, credit limits).

  • Kaggle Credit Risk datasets: e.g. “Give Me Some Credit” (predict 90-day delinquency) or Lending Club loan data.

Model Comparison Table

Model Comparison Table

Columns: Accuracy (typical performance), Interpretability (ease of explaining predictions), Latency (inference speed), Data Requirements (amount/complexity), Production Readiness (maturity/ease of use).

Sources

  • Akhmetova et al. (2026), Interpretable Multi-Model Framework for Early Warning of SME Loan Delinquency — supports the importance of delinquency forecasting for portfolio stability and regulatory compliance. (MDPI)

  • Peng & Lessmann (2026), Incorporating data drift to perform survival analysis on credit risk — supports the drift and retraining angle. (IDEAS/RePEc)

  • Hjelkrem & de Lange (2023), Explaining Deep Learning Models for Credit Scoring with SHAP — supports the credit-scoring / calibration / explainability angle. (MDPI)

  • Weights & Biases Docs: Tables, Experiments, Weave — supports logging, tracking, and orchestration. (Weights & Biases Documentation)

  • Weights & Biases Alerts — this is the main missing source from your list, since your tutorial uses monitoring alerts. (Weights & Biases Documentation)

  • UCI ML Repository: Default of Credit Card Clients — supports the production-like dataset example. (Weights & Biases Documentation)

  • GiveMeSomeCredit / Lending Club datasets — supports additional public dataset examples. (MDPI)

💡 If you made it this far, you’re a legend! ❤️
Don’t forget to share if you liked the post, and keep your hype for learning going! 💪
That’s it for now, wish me luck! 👌
Catch ya later, Techie! 😁

P.S:
You can follow me:
LinkedIn
Facebook
Linktree

Add PoW-skip + Lightning payments to any MCP server in 10 lines

You built an MCP server. Now agents are hammering your premium tools for free and you’ve got no lever to pull.

The boring fix is “add auth” — OAuth tokens, API keys, a whole user management system. But that’s overkill for a tool that should just cost 21 sats per call.

Here’s the short fix.

What you need

Two packages:

npm install @powforge/captcha-paymcp-provider @powforge/paymcp-l402-provider paymcp

The 10-line integration

const { PayMCP } = require('paymcp');
const { CaptchaPowProvider } = require('@powforge/captcha-paymcp-provider');
const { LnbitsPaymentProvider } = require('@powforge/paymcp-l402-provider');

PayMCP(mcp, {
  providers: [
    new CaptchaPowProvider({ captchaUrl: 'https://captcha.powforge.dev' }),
    new LnbitsPaymentProvider({
      lnbitsUrl: process.env.LNBITS_URL,
      lnbitsApiKey: process.env.LNBITS_KEY,
      satsAmount: 21,
    }),
  ],
});

Drop that right after you construct your McpServer. Tag any tool with { _meta: { price: 1 } } and it’s now gated.

How it works

PoW path (free, ~5-10s of CPU):

  1. createPayment fetches a SHA-256 challenge from the captcha server.
  2. It mines the nonce server-side — no round-trip to the client needed.
  3. Returns a pow:// URI encoding all params a PoW-capable MCP client SDK needs.
  4. getPaymentStatus submits the nonce to /api/verify and returns 'paid' on confirm.

Lightning path (21 sats):

  1. createPayment mints a BOLT11 invoice via LNBits.
  2. Returns the invoice in the payment URL.
  3. getPaymentStatus polls until the invoice is settled.

paymcp tries the PoW provider first. If the calling agent doesn’t support pow:// URIs, it falls through to the Lightning invoice. The agent picks whichever it can satisfy.

Why both tiers

Some agents are compute-rich, sats-poor — they’d rather burn CPU cycles than need a wallet. Others are running in headless pipelines with a Lightning wallet already wired. Give them both options and you capture more traffic without managing two separate auth flows.

The pow:// URI scheme also means the payment proof travels in-band with the request — no session state, no cookies, no database lookup beyond the challenge ledger the captcha server already maintains.

Full example

'use strict';

const { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const { PayMCP } = require('paymcp');
const { CaptchaPowProvider } = require('@powforge/captcha-paymcp-provider');
const { LnbitsPaymentProvider } = require('@powforge/paymcp-l402-provider');
const { z } = require('zod');

const mcp = new McpServer({ name: 'my-mcp-server', version: '1.0.0' });

PayMCP(mcp, {
  providers: [
    new CaptchaPowProvider({ captchaUrl: 'https://captcha.powforge.dev' }),
    new LnbitsPaymentProvider({
      lnbitsUrl: process.env.LNBITS_URL,
      lnbitsApiKey: process.env.LNBITS_KEY,
      satsAmount: 21,
    }),
  ],
});

mcp.tool(
  'premium_lookup',
  'Premium data lookup — PoW-skip (free) or Lightning (21 sats)',
  { query: z.string() },
  { _meta: { price: 1 } },
  async ({ query }) => ({
    content: [{ type: 'text', text: `Result for: ${query}` }],
  }),
);

const transport = new StdioServerTransport();
mcp.connect(transport).then(() => {
  process.stderr.write('MCP server runningn');
});

Self-hosting the captcha server

The captchaUrl above points to captcha.powforge.dev which handles challenge issuance and verification. You can self-host it too — it’s @powforge/captcha running as a Node.js server. The whole thing is under 300 lines.

What it costs

  • PoW path: free for the agent, a few seconds of server CPU per call, and a round-trip to your captcha endpoint.
  • Lightning path: 21 sats (or whatever satsAmount you set) credited to your LNBits wallet.
  • No external auth services, no API keys to rotate, no user database.

The PoW path is also a natural rate limiter. Solving a difficulty-14 SHA-256 challenge takes roughly 5-10 seconds on a modern CPU — plenty of friction to discourage abuse, not so much that legitimate agents bail out.

Source on npm: