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

@marginfront/sdk

v0.8.0

Published

Official Node.js SDK for MarginFront - usage-based billing, invoicing, and analytics

Readme

@marginfront/sdk

npm version License: MIT Docs

Official Node.js SDK for MarginFront — usage-based billing, invoicing, and analytics for AI agents.

Full Documentation · Quickstart · Tracking Events · OpenAI Recipe · Anthropic Recipe

Breaking Changes in 0.8.0

The CLI env var MF_API_KEY has been renamed to MF_API_SECRET_KEY.

If you use the mf CLI with a .env.marginfront.cli file (or shell env var), rename the variable:

- MF_API_KEY=mf_sk_your_key_here
+ MF_API_SECRET_KEY=mf_sk_your_key_here

Why: MarginFront now has two key types — secret keys (mf_sk_*) for server-side writes and publishable keys (mf_pk_*) for client-side reads. The old name MF_API_KEY was ambiguous. The new names (MF_API_SECRET_KEY and MF_API_PUBLISHABLE_KEY) follow the same convention as Stripe.

There is no backward-compat fallback — setting only MF_API_KEY will now produce a "missing --api-key" error. This is intentional: the SDK surfaces misconfiguration instead of hiding it.

Installation

npm install @marginfront/sdk
# or
yarn add @marginfront/sdk

Quick Start

import { MarginFrontClient } from "@marginfront/sdk";

const client = new MarginFrontClient("mf_sk_your_secret_key");

// Track a usage event (e.g. an LLM call your agent made)
await client.usage.record({
  customerExternalId: "cust_123",
  agentCode: "sourcing-agent",
  signalName: "llm_call",
  model: "gpt-4o",
  modelProvider: "openai",
  inputTokens: 523,
  outputTokens: 117,
});

Documentation

Configuration

const client = new MarginFrontClient("mf_sk_your_secret_key", {
  baseUrl: "https://api.marginfront.com/v1",
  timeout: 5000, // 5 seconds (default)
  retries: 3, // retry failed requests up to 3 times (default)
  retryDelay: 300, // milliseconds between retries
  fireAndForget: true, // (default) usage.record() never throws — errors retry silently
  logging: {
    enabled: true,
    level: "info",
  },
  telemetry: {
    enabled: true,
    sampleRate: 1,
  },
});

await client.connect();

Usage Tracking

Every event you track needs model and modelProvider so MarginFront knows what service was used and can calculate costs automatically.

LLM event (OpenAI, Anthropic, etc.)

When your agent calls a language model, pass the token counts and MarginFront handles the cost math:

await client.usage.record({
  customerExternalId: "cust_123",
  agentCode: "sourcing-agent",
  signalName: "llm_call",
  model: "gpt-4o",
  modelProvider: "openai",
  inputTokens: 523,
  outputTokens: 117,
});

Non-LLM event (Twilio, AWS, etc.)

For services that aren't LLMs, use quantity instead of token counts:

await client.usage.record({
  customerExternalId: "cust_123",
  agentCode: "notification-agent",
  signalName: "sms_sent",
  model: "twilio-sms",
  modelProvider: "twilio",
  quantity: 3,
});

Batch tracking

Send multiple events at once. You can mix LLM and non-LLM events in the same batch:

await client.usage.recordBatch([
  {
    customerExternalId: "cust_123",
    agentCode: "sourcing-agent",
    signalName: "llm_call",
    model: "claude-sonnet-4-20250514",
    modelProvider: "anthropic",
    inputTokens: 1024,
    outputTokens: 256,
  },
  {
    customerExternalId: "cust_456",
    agentCode: "notification-agent",
    signalName: "sms_sent",
    model: "twilio-sms",
    modelProvider: "twilio",
    quantity: 5,
  },
]);

Customer Management

// Create a customer
const customer = await client.customers.create({
  name: "Acme Corp",
  email: "[email protected]",
  externalId: "acme-123",
});

// List customers
const customers = await client.customers.list({
  limit: 10,
  page: 1,
});

// Get, update and delete customers
const customer = await client.customers.get("customer_id");
await client.customers.update("customer_id", { name: "Updated Name" });
await client.customers.delete("customer_id");

Invoices

// List invoices with filters
const { invoices, totalResults } = await client.invoices.list({
  customerId: "cust_123",
  status: "pending",
  page: 1,
  limit: 20,
});

// Get a specific invoice
const invoice = await client.invoices.get("inv_abc");
console.log(`Invoice ${invoice.invoiceNumber}: $${invoice.totalAmount}`);

Analytics

const analytics = await client.analytics.usage({
  startDate: "2024-01-01",
  endDate: "2024-01-31",
  groupBy: "daily",
  customerId: "cust_123",
});

console.log(`Total usage: ${analytics.summary.totalQuantity}`);
console.log(`Total cost: $${analytics.summary.totalCost}`);

// Time series data
analytics.data.forEach((point) => {
  console.log(`${point.date}: ${point.quantity} units, $${point.cost}`);
});

Subscriptions

// List subscriptions
const { subscriptions } = await client.subscriptions.list({
  status: "active",
  customerId: "cust_123",
});

// Get subscription with usage details
const sub = await client.subscriptions.get("sub_abc");
console.log(`Usage this period: ${sub.usage.totalQuantity}`);

Portal Sessions

// Create a portal session (requires secret key mf_sk_*)
const session = await client.portalSessions.create({
  customerId: "cust_123",
  returnUrl: "https://myapp.com/account",
  features: ["invoices", "usage", "subscriptions"],
});

// Redirect customer to the portal
res.redirect(session.url);

Error Handling

Default behavior: fireAndForget (recommended)

By default, fireAndForget is true. This means usage.record() will never throw an error into your code. Your agent keeps running no matter what.

  • Network failures (server down, timeout, etc.) go into the retry buffer and get retried automatically in the background.
  • Validation errors (missing required fields, bad data) log a warning to the console and drop the event. There's nothing to retry if the data is wrong.
// This will never crash your app, even if the network is down
await client.usage.record({
  customerExternalId: "cust_123",
  agentCode: "sourcing-agent",
  signalName: "llm_call",
  model: "gpt-4o",
  modelProvider: "openai",
  inputTokens: 523,
  outputTokens: 117,
});
// Execution continues immediately — no try/catch needed

Opt-out: throw errors normally

If you want to handle errors yourself (e.g. in a testing environment), turn off fireAndForget:

const client = new MarginFrontClient("mf_sk_your_secret_key", {
  fireAndForget: false, // errors throw normally, no retry buffer
});

try {
  await client.usage.record({
    /* ... */
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error(`Authentication failed. Request ID: ${error.requestId}`);
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limit exceeded. Retry after ${error.retryAfter}s`);
  } else if (error instanceof ValidationError) {
    console.error(`Validation error: ${error.message}`);
  } else if (error instanceof MarginFrontError) {
    console.error(`API Error (${error.statusCode}): ${error.message}`);
  }
}

Retry Buffer

When fireAndForget is true (the default), failed events go into an in-memory retry buffer instead of throwing. Think of it like an outbox that keeps trying to deliver your events.

  • Capacity: Holds up to 1,000 events. If the buffer is full, the oldest event is dropped with a warning.
  • Retries: Each event gets up to 5 attempts before being dropped.
  • Backoff: Waits 10s, then 20s, then 40s, then 60s between retries (exponential with a ceiling). Resets on success.
  • Overhead: Zero when empty. No background timer runs unless there are actually events to retry.
  • Caveat: The buffer lives in memory only. If your process crashes, any buffered events are lost. For most use cases this is fine — the buffer only holds events during brief network blips.

Required Fields Reference

Every call to usage.record() needs these fields. The SDK validates them before sending anything to the server.

| Field | Type | Required | Default | Notes | | -------------------- | ----------- | -------- | ------- | ------------------------------------------------------ | | customerExternalId | string | Yes | -- | Your customer's ID in your system | | agentCode | string | Yes | -- | The agent/product code from the dashboard | | signalName | string | Yes | -- | The metric being tracked (e.g. "llm_call", "sms_sent") | | model | string | Yes | -- | Model identifier (e.g. "gpt-4o", "twilio-sms") | | modelProvider | string | Yes | -- | Provider in lowercase (e.g. "openai", "twilio") | | inputTokens | number | No | -- | Prompt tokens (LLM events) | | outputTokens | number | No | -- | Completion tokens (LLM events) | | quantity | number | No | 1 | Billing units (non-LLM events) | | usageDate | string/Date | No | now | When the event happened | | metadata | object | No | {} | Custom key-value pairs for your own tracking |

What happens when the model isn't recognized

If you send a model value that MarginFront hasn't seen before (say, a brand new OpenAI model that launched today):

  1. The event is stored normally with a null cost. It is never dropped and never assigned a zero cost.
  2. The dashboard shows it under "Needs attention" so you or your team can see it immediately.
  3. You map it to a known model with one click in the dashboard.
  4. Future events with that same model auto-resolve -- no code changes needed.

Bottom line: you can ship new models without worrying about breaking billing. MarginFront catches up.

Advanced Features

Request Retries

const client = new MarginFrontClient("mf_sk_your_secret_key", {
  retries: 3,
  retryDelay: 300,
});

Logging & Telemetry

The SDK includes a telemetry system that tracks API request performance and usage patterns:

const client = new MarginFrontClient("mf_sk_your_secret_key", {
  logging: {
    enabled: true,
    level: "debug",
    handler: (level, message, data) => {
      myLoggingSystem.log(level, message, data);
    },
  },
  telemetry: {
    enabled: true,
    sampleRate: 0.5, // Track 50% of requests
    handler: (metrics) => {
      myMonitoringSystem.trackApiRequest(metrics);
    },
  },
});

You can access telemetry statistics programmatically:

// Get current statistics
const stats = client.getTelemetryStats();
console.log(`Total Requests: ${stats.requestCount}`);
console.log(`Success Rate: ${(stats.successRate * 100).toFixed(2)}%`);

CLI (Testing Tool)

The SDK ships with a lightweight CLI (mf) for testing your integration without writing code.

Note: The CLI is a testing tool only. It has no effect on the SDK when used as a library in your application.

Install globally

npm install -g @marginfront/sdk

Then run commands from anywhere:

mf verify
mf track-event --customer-id customer-1 --agent-code my-agent --signal CALL_MINUTES --quantity 10

Commands

mf verify

Verifies your API key and returns organization details.

mf verify [options]

Options:
  --api-key <key>    API key (mf_sk_* or mf_pk_*)
  --base-url <url>   API base URL (default: https://api.marginfront.com/v1)
  --debug            Enable debug output

mf track-event

Sends a single usage event to the API.

mf track-event [options]

Options:
  --api-key <key>      API key (mf_sk_*)
  --base-url <url>     API base URL (default: https://api.marginfront.com/v1)
  --customer-id <id>   Customer external ID
  --agent-code <code>  Agent code (external ID set in the UI)
  --signal <name>      Signal name (e.g. CALL_MINUTES)
  --quantity <number>  Quantity to record (default: 1)
  --metadata <json>    Optional metadata as a JSON string
  --debug              Enable debug output

Default values via .env.marginfront.cli

To avoid repeating flags, create a .env.marginfront.cli file in the directory where you run the CLI. Any value set here is used as a default and can be overridden by passing the flag directly.

# ⚠️  FOR TESTING ONLY
# This file is NOT used when the SDK is imported as a library.
# It only applies when running the mf CLI.

MF_API_SECRET_KEY=mf_sk_your_key_here
MF_BASE_URL=http://localhost:4000/v1
MF_AGENT_CODE=your-agent-code
MF_CUSTOMER_ID=customer-1
MF_SIGNAL=CALL_MINUTES
MF_QUANTITY=10
MF_DEBUG=false

Priority: CLI flags > .env.marginfront.cli > built-in defaults

| CLI Flag | .env Key | | --------------- | ------------------- | | --api-key | MF_API_SECRET_KEY | | --base-url | MF_BASE_URL | | --customer-id | MF_CUSTOMER_ID | | --agent-code | MF_AGENT_CODE | | --signal | MF_SIGNAL | | --quantity | MF_QUANTITY | | --debug | MF_DEBUG |

Add .env.marginfront.cli to your .gitignore to avoid committing test credentials.

License

MIT License. See LICENSE for details.