@marginfront/sdk
v0.8.0
Published
Official Node.js SDK for MarginFront - usage-based billing, invoicing, and analytics
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
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_hereWhy: 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/sdkQuick 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 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 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 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 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):
- 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.
