Package Exports
- @marginfront/sdk
Readme
@marginfront/sdk
Official Node.js SDK for MarginFront. usage-based billing, invoicing, and analytics for AI agents.
Full Documentation · Quickstart · Tracking Events · OpenAI Recipe · Anthropic Recipe
Installation
npm install @marginfront/sdk
# or
yarn add @marginfront/sdkQuick Start
You don't need to set anything up first. When you fire an event with a new
customerExternalId,agentCode, orsignalName, MarginFront creates the customer, agent, or signal automatically. Your existing user IDs from your own database flow straight through. The dashboard updates the moment the event lands.
import { MarginFrontClient } from "@marginfront/sdk";
const client = new MarginFrontClient("mf_sk_your_secret_key");
// signalName is the unit on your customer's invoice. name it after
// what they pay for (pages, reports, messages), NOT after the model.
// See "Picking signalName and quantity" below for the full rule.
await client.usage.record({
customerExternalId: "<your_db_user_id>", // whatever ID your system already uses for this user
agentCode: "<your_agent_identifier>", // a stable name for this agent. e.g. "report_writer"
signalName: "<your_billing_unit>", // what the customer is paying for. e.g. "reports-generated"
model: "gpt-4o",
modelProvider: "openai",
inputTokens: 523,
outputTokens: 117,
});Picking signalName and quantity
The most important decision you'll make before writing integration code: what unit do you want your customer to see on their invoice? That answer becomes your signalName.
Four rules cover it:
- Fire one event per business outcome. a finished report, a completed call, a sent email. Not one per page, not one per minute, not one per token. The
quantityfield exists so you don't have to loop. - The signal name IS the billing unit. Bill per page → name it
pages. Bill per report → name itreports. Bill per minute → name itminutes. quantityis the count of that billing unit for this one event. A 50-page report fired aspageshasquantity: 50. The same report fired asreportshasquantity: 1. Same LLM call, same token cost, different invoice line.- Cost and revenue are decoupled. MarginFront calculates cost automatically from
model+modelProvider+ token counts. Revenue isquantity × your pricing-plan rate. The gap is your margin.
Same Claude call (a 50-page market research report), three different billing configurations:
signalName |
quantity |
Rate | Invoice line |
|---|---|---|---|
reports_generated |
1 | $50 per report | "1 report × $50" |
report_pages |
50 | $2 per page | "50 pages × $2" |
tokens_used |
15000 | $0.01 per 1K | "15K tokens × $0.01" |
Bad signal names (internal details the customer shouldn't see): llm_call, gpt-4o-call, api-requests. Good signal names (what the customer is actually paying for): messages, reports-generated, pages, minutes, sms-sent.
Full walkthrough with examples: Choosing your signal name and quantity.
Documentation
- Configuration Options
- Usage Tracking
- Customer Management
- Error Handling
- Retry Buffer
- Required Fields Reference
- What happens when the model isn't recognized
- Advanced Features
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 (or a services[] array for multi-service events) 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. Note that signalName is the billing unit, not the model name:
await client.usage.record({
customerExternalId: "cust_123",
agentCode: "cs-bot",
signalName: "support-reply",
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,
});Multi-service event (one outcome, multiple services)
Real agents often use several services for one outcome. A cold-outreach agent finds a prospect via Exa, enriches them via Hunter.io, writes the message via Claude Opus, and sends it via Pipedream. From your customer's perspective that's ONE outreach. From your cost perspective four services contributed.
Track it as ONE event with a services[] array. Each entry becomes a per-service cost line under one parent event. The dashboard shows one event with the rolled-up total; the customer's invoice still bills per signal (one outreach = one charge, regardless of how many services contributed):
await client.usage.record({
customerExternalId: "cust_123",
agentCode: "outreach-bot",
signalName: "outreaches-sent",
// Top-level quantity stays signal-level: ONE outreach
quantity: 1,
services: [
{ model: "exa-search", modelProvider: "exa", quantity: 1 },
{ model: "hunter-enrich", modelProvider: "hunter", quantity: 1 },
{
// LLM entries can carry tokens AND quantity together
model: "claude-opus-4-1",
modelProvider: "anthropic",
inputTokens: 4500,
outputTokens: 1200,
quantity: 1,
},
{ model: "pipedream-workflow", modelProvider: "pipedream", quantity: 1 },
],
});Send model + modelProvider (single-service shape) OR send services[] (multi-service shape), never both, never neither. The SDK rejects mixed-shape requests before the network call leaves your code.
Batch tracking
Send multiple events at once. You can mix single-service LLM, single-service non-LLM, and multi-service events in the same batch:
await client.usage.recordBatch([
{
customerExternalId: "cust_123",
agentCode: "research-agent",
signalName: "reports-generated",
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,
},
{
// Multi-service entry mixed into the same batch
customerExternalId: "cust_123",
agentCode: "outreach-bot",
signalName: "outreaches-sent",
quantity: 1,
services: [
{ model: "exa-search", modelProvider: "exa", quantity: 1 },
{
model: "claude-opus-4-1",
modelProvider: "anthropic",
inputTokens: 4500,
outputTokens: 1200,
quantity: 1,
},
],
},
]);Customer Management
// Create a customer
const customer = await client.customers.create({
name: "Acme Corp",
email: "billing@acmecorp.com",
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",
subscriptionId: "sub_abc", // optional filter (added in 0.9.0)
});
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}`);
});Revenue & Cost Analytics (canonical, added in 0.9.0)
Nine methods return the canonical shapes the dashboard uses internally. Every
dollar amount is a plain number (not string), and marginPercent is null
when revenue is zero (never 0%, never NaN).
Revenue metrics
// Canonical revenue. org-wide for the last 30 days
const metrics = await client.analytics.revenue({
startDate: "2024-01-01",
endDate: "2024-01-31",
});
console.log(`Revenue: $${metrics.revenue.toFixed(2)}`);
console.log(`Cost: $${metrics.cost.toFixed(2)}`);
console.log(`Margin: $${metrics.margin.toFixed(2)}`);
console.log(`Margin %: ${metrics.marginPercent?.toFixed(1) ?? "-"}%`);
// Revenue decomposes by charge type
console.log(`Usage: $${metrics.usageRevenue}`);
console.log(`Recurring: $${metrics.recurringRevenue}`);
console.log(`Seat: $${metrics.seatRevenue}`);
console.log(`Onetime: $${metrics.onetimeRevenue}`);
// Scoped by customer, agent, signal, or subscription
const perCustomer = await client.analytics.revenue({
startDate: "2024-01-01",
endDate: "2024-01-31",
customerId: "cust_123",
});Cost breakdown
const cost = await client.analytics.costBreakdown({
startDate: "2024-01-01",
endDate: "2024-01-31",
includePriorWindow: true, // period-over-period trend
});
console.log(`Total cost: $${cost.cost.toFixed(2)}`);
console.log(`Events: ${cost.eventCount}`);
console.log(`Needs attention (null cost): ${cost.eventCountWithNullCost}`);
// Six breakdown arrays for drill-downs
cost.byAgent.forEach((row) => console.log(`${row.agentId}: $${row.cost}`));
cost.byModel.forEach((row) => console.log(`${row.model}: $${row.cost}`));
// Prior-window trend (when includePriorWindow: true)
if (cost.prior) {
const delta = cost.cost - cost.prior.cost;
console.log(`Δ vs prior window: $${delta.toFixed(2)}`);
}MRR (three variants)
// MRR1. canonical. "What did we bill last calendar month?"
const { mrr, arr } = await client.analytics.mrr();
console.log(`MRR: $${mrr}, ARR: $${arr}`); // arr === mrr * 12
// MRR2. run-rate. "What would we bill per month at the 30-day pace?"
const runRate = await client.analytics.runRateMrr();
console.log(`Run-rate MRR: $${runRate.mrr}`);
runRate.breakdown.forEach((row) => {
console.log(` ${row.subscriptionId}: total $${row.total}`);
});
// MRR3. committed. "Contractual floor regardless of usage."
const committed = await client.analytics.committedMrr();
console.log(`Committed MRR floor: $${committed.mrr}`);
// Invariant: committed.mrr ≤ runRate.mrr (floor ≤ trajectory)Invoice totals (billed, collected, outstanding)
const totals = await client.analytics.invoiceTotals({
startDate: "2024-01-01",
endDate: "2024-01-31",
});
console.log(`Billed: $${totals.billed}`);
console.log(`Collected: $${totals.collected}`);
console.log(`Outstanding: $${totals.outstanding}`); // billed - collected
console.log(`Draft: $${totals.draft}`);
if (totals.overdueCount > 0) {
console.log(`${totals.overdueCount} overdue ($${totals.overdueAmount})`);
}Agent-Earned (activity-only revenue)
// Events × pricing rate only. excludes recurring / seat / onetime.
// The "did my agent do billable work?" number, independent of invoice cadence.
const earned = await client.analytics.agentEarned({
startDate: "2024-01-01",
endDate: "2024-01-31",
agentId: "agent_abc", // optional scope
});
console.log(`Activity revenue: $${earned.revenue}`);
console.log(`Events: ${earned.eventCount}`);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}`);
// Get subscription + canonical revenue in one parallel call (added in 0.9.0)
const result = await client.subscriptions.getWithRevenue("sub_abc");
console.log(`Plan: ${result.subscription.plan.name}`);
console.log(`Revenue: $${result.revenue.revenue}`);
console.log(`Margin: ${result.revenue.marginPercent?.toFixed(1) ?? "-"}%`);
// Same, but with an explicit window
const custom = await client.subscriptions.getWithRevenue("sub_abc", {
startDate: "2024-01-01",
endDate: "2024-01-31",
});Customers (with revenue)
// Get customer + canonical revenue in one parallel call (added in 0.9.0)
const { customer, revenue } = await client.customers.getWithRevenue("cust_123");
console.log(`${customer.name}: $${revenue.revenue} revenue`);
console.log(`Cost: $${revenue.cost}, Margin: $${revenue.margin}`);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: "cs-bot",
signalName: "support-reply",
model: "gpt-4o",
modelProvider: "openai",
inputTokens: 523,
outputTokens: 117,
});
// Execution continues immediately. no try/catch neededOpt-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 billing unit, matching your invoice line (e.g. "messages", "reports-generated", "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):
- The event is stored normally with a
nullcost. It is never dropped and never assigned a zero cost. - The dashboard shows it under "Needs attention" so you or your team can see it immediately.
- You map it to a known model with one click in the dashboard.
- 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/sdkThen run commands from anywhere:
mf verify
mf track-event --customer-id customer-1 --agent-code my-agent --signal CALL_MINUTES --quantity 10Commands
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 outputmf 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 outputDefault 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=falsePriority: 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.