npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@settlegrid/mcp

v0.1.1

Published

The Settlement Layer for the AI Economy — monetize any MCP tool, REST API, or AI agent with per-call billing, real-time metering, and automated Stripe payouts.

Downloads

94

Readme

@settlegrid/mcp

The Settlement Layer for the AI Economy — monetize any AI service with one line of code.

npm version License: MIT

SettleGrid enables developers to add per-call billing to MCP tools, REST APIs, AI agents, and model endpoints. Real-time Redis metering, automated Stripe payouts, and multi-protocol settlement (MCP, x402, AP2, Visa TAP).

Quick Start

npm install @settlegrid/mcp
import { settlegrid } from '@settlegrid/mcp'

const sg = settlegrid.init({
  toolSlug: 'my-tool',
  pricing: {
    defaultCostCents: 1,
    methods: {
      'search': { costCents: 5 },
      'analyze': { costCents: 10 },
    },
  },
})

// Wrap any MCP tool handler with billing
const billedHandler = sg.wrap(myHandler, { method: 'search' })

That's it. Every call to billedHandler validates the consumer's API key, checks their credit balance, executes your function, and meters the usage — all in under 50ms.

How It Works

  1. Developer registers a tool on settlegrid.ai and sets per-method pricing
  2. Consumer purchases credits via Stripe and receives an API key (sg_live_...)
  3. SDK wraps your tool handler — validates key, checks balance, executes, meters
  4. SettleGrid splits revenue automatically (85% to developer, 15% platform fee)

Features

  • Sub-50ms metering — Redis DECRBY on the hot path, async DB writeback
  • Per-method pricing — different costs for different operations
  • Budget enforcement — consumers set spending limits, get HTTP 402 when exceeded
  • Auto-refill — automatic Stripe charges when balance drops below threshold
  • LRU cache — key validation cached for 5 minutes (configurable)
  • Fire-and-forget metering — doesn't block your response
  • 6 pricing models — per-invocation, per-token, per-byte, per-second, tiered, outcome-based

REST API Middleware

For non-MCP services (Express, Next.js API routes):

import { settlegridMiddleware } from '@settlegrid/mcp'

const withBilling = settlegridMiddleware({
  toolSlug: 'my-api',
  costCents: 5,
})

// Next.js App Router
export async function GET(request: Request) {
  return withBilling(request, async () => {
    return Response.json({ data: 'hello' })
  })
}

MCP Payment Capability

Declare billing support in your MCP server's capabilities:

import { createPaymentCapability } from '@settlegrid/mcp'

const server = new Server({
  capabilities: {
    experimental: {
      payment: createPaymentCapability({
        toolSlug: 'my-tool',
        pricing: {
          model: 'per-invocation',
          defaultCostCents: 5,
          currencyCode: 'USD',
        },
      }),
    },
  },
})

MCP Server Card

Generate .well-known/mcp-server billing metadata:

import { generateServerCard } from '@settlegrid/mcp'

const card = generateServerCard({
  name: 'My Tool',
  version: '1.0.0',
  description: 'A useful AI tool',
  tools: [{ name: 'search', description: 'Search the web', inputSchema: {} }],
  billing: {
    toolSlug: 'my-tool',
    pricing: { model: 'per-invocation', defaultCostCents: 5, currencyCode: 'USD' },
  },
})

API Key Extraction

The SDK extracts API keys from multiple sources (priority order):

  1. MCP _meta['settlegrid-api-key']
  2. Authorization: Bearer sg_live_... header
  3. x-api-key header
import { extractApiKey } from '@settlegrid/mcp'

const key = extractApiKey(headers, metadata) // returns string | null

Error Handling

The SDK throws typed errors you can catch:

import {
  InvalidKeyError,        // 401 — key doesn't exist or is revoked
  InsufficientCreditsError, // 402 — balance too low
  ToolNotFoundError,       // 404 — tool slug not registered
  ToolDisabledError,       // 403 — tool is deactivated
  RateLimitedError,        // 429 — too many requests
  TimeoutError,            // 503 — request timed out
  NetworkError,            // 503 — connection failed
} from '@settlegrid/mcp'

Configuration

settlegrid.init({
  toolSlug: 'my-tool',      // Required — registered on settlegrid.ai
  pricing: { ... },          // Required — pricing configuration
  apiUrl: 'https://settlegrid.ai', // Optional — API base URL
  debug: false,              // Optional — sync metering + console logs
  cacheTtlMs: 300000,       // Optional — key validation cache TTL (5 min default)
  timeoutMs: 5000,           // Optional — API request timeout (5s default)
})

Pricing Models

// Per-invocation (default)
{ model: 'per-invocation', defaultCostCents: 5 }

// Per-token (LLM proxies)
{ model: 'per-token', defaultCostCents: 1 }

// Tiered (volume discounts)
{ model: 'tiered', defaultCostCents: 1, tiers: [
  { upTo: 1000, costCents: 2 },
  { upTo: 10000, costCents: 1 },
]}

// Outcome-based (pay for results)
{ model: 'outcome', defaultCostCents: 0, outcomeConfig: {
  successCostCents: 50,
  failureCostCents: 0,
  successCondition: 'result.success === true',
}}

Protocol Support

SettleGrid is protocol-agnostic. This SDK supports:

  • MCP (Model Context Protocol) — native wrap() integration
  • REST APIssettlegridMiddleware() for any HTTP endpoint
  • x402 (Coinbase) — facilitator endpoints at /api/x402/verify and /api/x402/settle
  • AP2 (Google Agent Payments) — credentials provider at /api/a2a/skills
  • Visa TAP — adapter ready (pending sandbox access)

Links

License

MIT