undrift-sdk
v1.3.0
Published
Runtime API drift detection and self-healing for third-party integrations
Maintainers
Readme
Undrift SDK
Runtime API drift detection and self-healing for the third-party services your application does not control.
Modern software depends on APIs, SDKs, MCP servers and webhooks. When one of them silently changes shape, status codes, field formats or enum values, your application fails without an error. Undrift sits in front of those calls, learns each endpoint's real behaviour from traffic, detects meaningful changes the moment they happen, heals responses in-flight with fixes approved on your dashboard, and reports everything so you can see which workflows are affected.
External service → Observed behaviour → Fingerprint (learned contract) → Drift detection
→ Impact (workflow, money, silent failure) → Approved adapter → Validated response → Your app- Zero runtime dependencies. Works in Node 18+ and in browsers.
- Never breaks the host app:
undrift.fetchalways returns a realResponse, non-JSON passes through, and the SDK keeps working when the Undrift backend is unreachable. - No raw values leave the process. Telemetry carries types, formats, paths and counts only.
Install
npm install undrift-sdkQuick start
import { Undrift } from 'undrift-sdk';
const undrift = new Undrift({
apiKey: process.env.UNDRIFT_API_KEY!, // from undrift.anik8.me
env: 'prod',
service: 'paygate',
});
// Use undrift.fetch where you would use fetch.
export async function checkout(paymentId: string) {
return undrift.workflow('checkout', async () => {
const res = await undrift.fetch(`https://api.paygate.example/v1/payments/${paymentId}`);
const payment = await res.json();
return payment.amount / 100; // still integer paise, even after the provider switched to "500.00"
});
}What happens on each call:
- Learn. The first few responses for
GET /v1/payments/:id(ids are collapsed automatically) build a fingerprint: every field path, its types, value formats (ISO date, epoch, decimal string, email, id, enum…), enum value sets, status codes and header names. Nothing is reported during warm-up (minSamples, default 3). - Detect. Every later response is compared with the fingerprint. Findings are typed:
envelope,key-rename,key-casing,nesting,type-change,format-change,enum-casing,enum-value-added,field-removed,field-added,status-code,header-rename. Renames are matched by normalised name and by value, socreated_at: 1760054460→createdAt: "2025-10-10T00:01:00Z"is onekey-casingplus oneformat-change, not a removal and an addition. - Assess. Each finding carries a severity and confidence; events are flagged
silent_failure(2xx with drifted data) andmoney_flag(amount, price, total…). The activeworkflowis attached so impact can be mapped per feature. - Heal. Fixes approved on your dashboard are pulled every 60 s and applied inside
fetch: envelope unwrapping, renames, restructuring, type and format coercion, enum normalisation, status-code remapping, header aliases and even path rewrites (POST /v1/payments/{id}/refundretired → re-issued toPOST /v1/refunds). The SDK never invents a fix. A kill switch rolls any fix back within one poll. - Report. One event per call is batched (gzipped in Node) to the backend: shape, enum sets, findings, healed fixes, workflow, and about once a minute per endpoint a redacted sample so the dashboard can replay proposed fixes. Baselines stay frozen while drift is present, so the drifted shape never silently becomes the new truth.
Healing happens before your code gets the Response; detection and reporting happen after, so the hot path stays well under a millisecond.
Configuration
new Undrift({
apiKey: string,
env?: string,
service?: string,
endpoint?: string, // backend base URL, default https://undrift.anik8.me
minSamples?: number, // observations before drift is reported, default 3
routes?: string[], // explicit templates, e.g. ['/v1/payments/:id/refund']
store?: BaselineStore, // persist baselines across restarts (see below)
heal?: boolean, // apply approved fixes inside fetch, default true
telemetry?: boolean, // send events, default true
onDrift?: (event) => void, // local callback for every event with drift
onEvent?: (event) => void, // local callback for every event, even with telemetry off (dashboards, tests)
samples?: boolean, // attach a redacted sample ~1/min per endpoint for fix replay, default true
redact?: boolean, // mask emails, phones, names, secrets, card numbers, addresses, free text, default true
redactFields?: string[], // extra field names to mask
compress?: boolean, // gzip batches in Node, default true
fixPollIntervalMs?, flushIntervalMs?, maxQueue?, sampleIntervalMs?,
});service defaults to the host of the URL being called, so each provider shows up on the dashboard without configuration.
Persist baselines
import { Undrift, FileBaselineStore } from 'undrift-sdk';
const undrift = new Undrift({ apiKey, store: new FileBaselineStore('.undrift/baselines.json') });Or use exportBaselines() / importBaselines(json) with your own storage. Baselines are JSON and contain no raw values. listBaselines() summarises every learned endpoint (samples, status counts, field-path count, last observation) and clearBaselines(prefix?) forgets them.
Other HTTP clients, MCP and webhooks
// axios / got / node:http — hand the response to inspect()
const { body, status, drift } = await undrift.inspect({ method: 'GET', url, status: res.status, headers: res.headers, body: res.data });
// Third-party SDKs that use the global fetch: observed as kind "sdk", healed, restorable
const restore = undrift.instrumentGlobalFetch({ kind: 'sdk' });
// MCP clients: tools/list schemas and every tools/call (tool name, argument shape, result) fingerprinted per tool
const client = undrift.wrapMcpClient(mcpClient, { service: 'inventory-mcp' });
// Incoming webhooks: one baseline per event type (the event key is read case-insensitively from body.event / type /
// event_type, also inside a single-object envelope), payload shape + headers observed, fixes applied to req.body
// and req.headers before the handler runs
app.post('/webhooks/paygate', undrift.wrapWebhook(handler));
// Playground / tests: heal a parsed body, or a fetch Response
const healedBody = undrift.applyFixes(body, { method: 'GET', pathTemplate: '/v1/payments/:id' });
const healedResponse = await undrift.applyFixes(response);Offline use
The detector and healer are plain functions you can use without a backend:
import { Fingerprint, detectDrift, analyzeStructuralDrift, healResponse } from 'undrift-sdk';
const fp = new Fingerprint();
fp.observe(200, headers, body1); fp.observe(200, headers, body2); fp.observe(200, headers, body3);
const findings = detectDrift(fp, { status: 200, headers, body: live });
const quick = analyzeStructuralDrift(baselineBody, currentBody); // one-sample comparison
const healed = healResponse({ body, status, headers, fixes, ctx: { method: 'GET', pathTemplate: '/v1/payments/:id' } });Impact analysis on your code (optional)
undrift-sdk/ast finds which lines of an application read which API fields and correlates them with drift findings, so a dashboard can say "checkout.ts:42 reads amount without a guard". It parses TypeScript and JavaScript with the TypeScript compiler, an optional peer dependency, so the core import stays dependency-free. Install typescript where you run it, usually the backend:
import { analyzeRepoFiles, correlateAstWithDrift } from 'undrift-sdk/ast';
const repo = analyzeRepoFiles([{ path: 'src/checkout.ts', content }]); // e.g. files from the GitHub API
const impact = correlateAstWithDrift(repo, event.drift, { endpoint: event.path_template });
// → [{ filePath, line, property: 'amount', accessPath, confidence: 'exact', riskLevel: 'HIGH', isGuarded, hasFallback }, …]It follows API data through the file: results of .json(), undrift.inspect(), axios res.data, .then(data => …) and variables derived from them by property access or destructuring, with the endpoint the data came from when the URL was literal. A match is exact when the read hangs off such a root with the right path, path when only the dotted path matches, and name when only the field name matches; name matches, and reads of data known to come from another endpoint, are left out unless you lower minConfidence.
Flow charts
Two Mermaid charts document the flow. docs/FLOW.mmd is the complete request path in ten stages (integration points, hot path, heal, learn, diff, save, event, upload, backend, fix sync). docs/FLOW-KINDS.mmd follows each kind of dependency through the same core: a third-party REST API via fetch/inspect, a vendor SDK via instrumentGlobalFetch, an incoming webhook via wrapWebhook, and an MCP server via wrapMcpClient, showing how each one enters, how its baseline is keyed, what is healed, and what the caller gets back. Both render on GitHub, in VS Code and on mermaid.live.
Demo and test data
The simulated dependencies live in the demo repo, Undrift-test, under simulation/, and the SDK suites in test/ read them from the sibling checkout (or UNDRIFT_SIM_DIR). It contains five simulated dependencies, each with a baseline contract, a drifted one, and a manifest of every intentional difference: a payment provider (simulation/DRIFT.md, 39 drifts), an identity service, a logistics service, incoming webhooks and an MCP server (simulation/services/*). A backend stand-in serves the approved fixes. The offline report learns each endpoint, diffs the drifted fixtures, scores detection against the manifests and verifies healing. On top of that, simulation/generated/ holds 6000 generated cases: 1500 over 30 realistic REST API archetypes, 1500 over 30 incoming-webhook providers (Stripe, GitHub, Shopify, Razorpay, PayPal, Square, Twilio, Slack, Svix-style, Jira, Linear, Sentry, Vercel…) 1500 reached through 30 third-party SDKs (stripe, @octokit/rest, twilio, @slack/web-api, googleapis, openai, @anthropic-ai/sdk, @supabase/supabase-js, algoliasearch, @elastic/elasticsearch, airtable, auth0…) and 1500 over 30 MCP servers (GitHub, Slack, filesystem, Postgres, Brave Search, fetch, memory, Google Drive, Gmail, Jira, Linear, Notion, Sentry, Cloudflare, S3, Kubernetes, Docker, Playwright, Supabase, Vercel…; one baseline per tool, plus tools/list catalogues where a tool is renamed or gains a required argument), each with 1 to 4 undocumented changes, verified for detection, false positives, exact healing and idempotence (pnpm run test:generated). The webhook cases are also replayed through the real wrapWebhook() from the provider's delivery to the application's handler (pnpm run test:e2e:webhooks), and the SDK cases through a vendor SDK module calling global fetch under instrumentGlobalFetch({ kind: 'sdk' }), including vendors that start answering 429 (pnpm run test:e2e:sdks), and the MCP cases through wrapMcpClient() with an agent calling callTool and listTools (pnpm run test:e2e:mcp).
git clone https://github.com/aniketsingh1023/Undrift-test ../Undrift-test # simulation data + demo studio
pnpm install && pnpm run build
pnpm test # offline: manifest accuracy report + 114-check harness + 6000 generated cases (REST, webhook, SDK, MCP) + live replays
# live demo: see ../Undrift-test (npm start for the studio; npm run sim:backend for the backend stand-in)Development
pnpm run typecheck
pnpm run build
pnpm testLicense
MIT
