import express from "express";
import Anthropic from "@anthropic-ai/sdk";
import { MarginFrontClient } from "@marginfront/sdk";
const app = express();
app.use(express.json());
// Set up clients once at startup
const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY from environment
const mf = new MarginFrontClient(process.env.MF_API_SECRET_KEY!);
app.post("/research", async (req, res) => {
const { customerId, question } = req.body;
// --- Step 1: Call Claude ---
const response = await anthropic.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: question }],
});
// --- Step 2: Send the answer to your customer ---
const answer =
response.content[0].type === "text" ? response.content[0].text : "";
res.json({ answer });
// --- Step 3: Track the usage in MarginFront (AFTER responding) ---
// Runs after the response is sent. If MarginFront is unreachable,
// the SDK queues the event and retries. Your customer never waits.
await mf.usage.record({
customerExternalId: customerId, // who used it
agentCode: "research-bot", // which product did the work
signalName: "analyses", // what you're measuring
model: response.model, // 'claude-sonnet-4-20250514' -- from Anthropic's response
modelProvider: "anthropic", // tells MarginFront which pricing table to check
inputTokens: response.usage.input_tokens, // Anthropic calls it input_tokens
outputTokens: response.usage.output_tokens, // Anthropic calls it output_tokens
});
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});