Documentation

Kontext SDK Documentation

Kontext is a TypeScript SDK that provides trust and compliance infrastructure for agentic workflows involving stablecoin transactions. This guide covers everything from installation to advanced integrations.

Installation

Install the Kontext SDK using your preferred package manager.

Terminalbash
npm install @kontext/sdk

Or with yarn / pnpm:

Terminalbash
yarn add @kontext/sdk
# or
pnpm add @kontext/sdk

Requirements: Node.js 18+ and TypeScript 5.0+. The SDK has zero runtime dependencies.

Quick Start

Get compliance working in your agent in under 2 minutes. Here is a complete example that initializes the SDK, verifies a transaction, and checks the result.

agent.tstypescript
import { Kontext } from '@kontext/sdk';

// Initialize with your API key (optional for open-source features)
const ctx = new Kontext({
  apiKey: process.env.KONTEXT_KEY, // only needed for Pro/Enterprise
  chain: 'base',                   // default chain
});

// Verify an agent action
const result = await ctx.verify({
  action: 'transfer',
  amount: '100.00',
  currency: 'USDC',
  from: '0x1234...abcd',
  to: '0x5678...efgh',
  agent: 'payment-agent-v2',
  metadata: {
    orderId: 'ord_123',
    reason: 'Vendor payment for API services',
  },
});

// Check the result
if (result.flagged) {
  console.warn('Action flagged:', result.flags);
  // Handle flagged action (e.g., require human approval)
} else {
  console.log('Trust score:', result.trustScore);
  // Proceed with the transaction
}

The verify() method is the core of Kontext. It logs the action, runs anomaly detection, computes a trust score, and returns a result object you can use to make decisions.

Action Logging

Every action your agents take should be logged for auditability. Kontext provides both simple logging and structured workflow logging for multi-step operations.

logging.tstypescript
import { Kontext } from '@kontext/sdk';

const ctx = new Kontext();

// Log any agent action -- not just transfers
await ctx.log({
  action: 'data_access',
  agent: 'research-agent',
  resource: 'customer_database',
  query: 'SELECT * FROM customers WHERE region = "US"',
  metadata: {
    purpose: 'quarterly_report',
    approved_by: 'admin@company.com',
  },
});

// Log a multi-step workflow
const workflow = ctx.workflow('invoice-processing');

await workflow.step('fetch_invoice', {
  source: 'email',
  invoiceId: 'inv_456',
});

await workflow.step('validate_amount', {
  amount: '2500.00',
  currency: 'USDC',
  threshold: '5000.00',
  passed: true,
});

await workflow.step('execute_payment', {
  txHash: '0xabc...def',
  chain: 'base',
  status: 'confirmed',
});

await workflow.complete();

Workflow logging groups related actions together, making it easy to trace the full lifecycle of a multi-step agent operation.

Task Confirmation

For high-value or sensitive actions, you can require human-in-the-loop confirmation before the action proceeds. Define policies declaratively and Kontext handles the confirmation flow.

confirmation.tstypescript
import { Kontext } from '@kontext/sdk';

const ctx = new Kontext();

// Define a confirmation policy
ctx.setPolicy({
  requireConfirmation: {
    when: [
      { field: 'amount', operator: 'gt', value: '1000' },
      { field: 'action', operator: 'eq', value: 'withdrawal' },
      { field: 'trustScore', operator: 'lt', value: '0.5' },
    ],
    timeout: 300_000, // 5 minute timeout
    fallback: 'deny', // deny if no confirmation received
  },
});

// This will pause and wait for confirmation if triggered
const result = await ctx.verify({
  action: 'transfer',
  amount: '5000.00',
  currency: 'USDC',
  agent: 'payment-agent',
});

if (result.pendingConfirmation) {
  console.log('Awaiting human confirmation...');
  console.log('Confirmation URL:', result.confirmationUrl);
  // The result resolves when confirmed or times out
}

Confirmation policies are evaluated before every verify() call. When triggered, the call pauses until a human confirms or denies the action via the dashboard or API.

Audit Export

Export your complete audit trail in JSON, CSV, or PDF format. Filter by date range, agent, action type, or flagged status. Streaming export is available for large datasets.

export.tstypescript
import { Kontext } from '@kontext/sdk';

const ctx = new Kontext();

// Export audit trail for a date range
const audit = await ctx.export({
  from: '2025-01-01',
  to: '2025-01-31',
  format: 'json', // or 'csv', 'pdf'
  filters: {
    agents: ['payment-agent-v2'],
    actions: ['transfer', 'withdrawal'],
    flaggedOnly: false,
  },
});

// Write to file
await Bun.write('audit-jan-2025.json', JSON.stringify(audit, null, 2));

// Or stream directly
const stream = ctx.exportStream({
  from: '2025-01-01',
  to: '2025-01-31',
  format: 'csv',
});

for await (const chunk of stream) {
  process.stdout.write(chunk);
}

Trust Scoring

Every verified action receives a trust score between 0 and 1. The score is computed from multiple factors including agent history, amount normality, transaction velocity, and recipient trust. Pro feature for historical analysis and trend tracking.

trust.tstypescript
import { Kontext } from '@kontext/sdk';

const ctx = new Kontext({ apiKey: process.env.KONTEXT_KEY });

// Get trust score for an action
const result = await ctx.verify({
  action: 'transfer',
  amount: '500.00',
  currency: 'USDC',
  agent: 'payment-agent-v2',
});

console.log(result.trustScore);    // 0.94
console.log(result.trustFactors);
// {
//   agentHistory: 0.98,       -- agent's track record
//   amountNormality: 0.92,    -- how normal is this amount
//   velocityCheck: 0.95,      -- transaction frequency check
//   recipientTrust: 0.89,     -- recipient's trust score
//   contextMatch: 0.97,       -- does context match pattern
// }

// Query historical trust scores
const history = await ctx.trustHistory({
  agent: 'payment-agent-v2',
  period: '30d',
});

console.log(history.average);      // 0.96
console.log(history.trend);        // 'stable'
console.log(history.flagCount);    // 2

Anomaly Detection

Configure rules to automatically flag or block suspicious agent behavior. Built-in checks include velocity limits, amount thresholds, and behavioral analysis. Pro plans include ML-powered detection.

anomaly.tstypescript
import { Kontext } from '@kontext/sdk';

const ctx = new Kontext();

// Configure anomaly detection rules
ctx.setRules({
  velocity: {
    maxTransactions: 50,
    period: '1h',
    action: 'flag', // or 'block'
  },
  amount: {
    maxSingle: '10000',
    maxDaily: '50000',
    currency: 'USDC',
    action: 'flag',
  },
  behavioral: {
    detectUnusualTiming: true,
    detectNewRecipients: true,
    detectAmountSpikes: true,
    sensitivity: 'medium', // 'low' | 'medium' | 'high'
  },
});

// Actions are automatically checked against rules
const result = await ctx.verify({
  action: 'transfer',
  amount: '15000.00', // exceeds maxSingle
  currency: 'USDC',
  agent: 'payment-agent-v2',
});

console.log(result.flagged);  // true
console.log(result.flags);
// [
//   {
//     rule: 'amount.maxSingle',
//     message: 'Amount 15000.00 exceeds single transaction limit of 10000',
//     severity: 'high',
//   }
// ]

USDC on Base Integration

Integrate Kontext with USDC transfers on Base (or any EVM chain). Verify transactions before sending and log the result after confirmation.

usdc-base.tstypescript
import { Kontext } from '@kontext/sdk';
import { createPublicClient, http } from 'viem';
import { base } from 'viem/chains';

const ctx = new Kontext({ chain: 'base' });

const client = createPublicClient({
  chain: base,
  transport: http(),
});

// Verify before sending a USDC transfer
async function sendUSDC(to: string, amount: string) {
  const result = await ctx.verify({
    action: 'transfer',
    amount,
    currency: 'USDC',
    to,
    agent: 'treasury-agent',
    chain: 'base',
  });

  if (result.flagged) {
    throw new Error(`Transfer flagged: ${result.flags[0].message}`);
  }

  // Proceed with the on-chain transfer
  // ... your viem/ethers transfer logic here

  // Log the completed transaction
  await ctx.log({
    action: 'transfer_complete',
    txHash: '0x...',
    amount,
    currency: 'USDC',
    trustScore: result.trustScore,
  });
}

x402 Protocol Integration

Add Kontext verification to x402 HTTP-native payment flows. Use as middleware to verify payments before processing requests.

x402-middleware.tstypescript
import { Kontext } from '@kontext/sdk';

const ctx = new Kontext();

// Middleware for x402 payment verification
function kontextMiddleware(handler) {
  return async (req, res) => {
    const payment = req.headers['x-402-payment'];

    if (payment) {
      const result = await ctx.verify({
        action: 'x402_payment',
        amount: payment.amount,
        currency: payment.currency,
        from: payment.payer,
        agent: payment.agent || 'unknown',
        metadata: {
          resource: req.url,
          method: req.method,
        },
      });

      if (result.flagged) {
        return res.status(402).json({
          error: 'Payment flagged for review',
          flags: result.flags,
        });
      }

      req.kontextResult = result;
    }

    return handler(req, res);
  };
}

Google UCP / A2A Integration

Verify agent-to-agent transactions using Google's Universal Checkout Protocol. Kontext wraps each UCP transaction with trust scoring and audit logging.

ucp-integration.tstypescript
import { Kontext } from '@kontext/sdk';

const ctx = new Kontext();

// Google UCP / A2A agent verification
async function handleAgentTransaction(ucpPayload) {
  const result = await ctx.verify({
    action: 'ucp_transaction',
    amount: ucpPayload.amount,
    currency: ucpPayload.currency,
    agent: ucpPayload.agentId,
    metadata: {
      ucpSessionId: ucpPayload.sessionId,
      merchantId: ucpPayload.merchantId,
      items: ucpPayload.lineItems,
    },
  });

  return {
    approved: !result.flagged,
    trustScore: result.trustScore,
    auditId: result.auditId,
  };
}

Stripe Agentic Commerce

Pair Kontext with Stripe to verify agent-initiated payments. The audit ID is attached to the Stripe payment intent metadata for full traceability.

stripe-integration.tstypescript
import { Kontext } from '@kontext/sdk';
import Stripe from 'stripe';

const ctx = new Kontext();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

// Verify agent commerce transactions via Stripe
async function handleAgentPayment(agentId: string, amount: number) {
  // Verify with Kontext before creating payment intent
  const result = await ctx.verify({
    action: 'stripe_payment',
    amount: String(amount / 100), // cents to dollars
    currency: 'USD',
    agent: agentId,
    metadata: {
      provider: 'stripe',
      type: 'payment_intent',
    },
  });

  if (result.flagged) {
    throw new Error('Payment flagged for compliance review');
  }

  // Create the Stripe payment intent
  const intent = await stripe.paymentIntents.create({
    amount,
    currency: 'usd',
    metadata: {
      kontext_audit_id: result.auditId,
      kontext_trust_score: String(result.trustScore),
      agent_id: agentId,
    },
  });

  return intent;
}

API Reference

Complete reference for all Kontext SDK methods and types.

Kontext Constructor

types.tstypescript
const ctx = new Kontext(options?: KontextOptions);

interface KontextOptions {
  apiKey?: string;      // API key for Pro/Enterprise features
  chain?: string;       // Default chain ('base' | 'ethereum' | 'polygon')
  environment?: string; // 'production' | 'staging' | 'development'
  baseUrl?: string;     // Custom API base URL (self-hosted)
}

ctx.verify(action)

Verifies an agent action against configured rules, computes a trust score, and returns the result.

types.tstypescript
interface VerifyAction {
  action: string;           // Action type identifier
  amount?: string;          // Transaction amount
  currency?: string;        // Currency code (e.g., 'USDC')
  chain?: string;           // Blockchain chain
  from?: string;            // Source address
  to?: string;              // Destination address
  agent: string;            // Agent identifier
  metadata?: Record<string, unknown>; // Additional context
}

interface VerifyResult {
  auditId: string;          // Unique audit trail ID
  trustScore: number;       // 0-1 trust score
  flagged: boolean;         // Whether any rules triggered
  flags: Flag[];            // Array of triggered flags
  trustFactors: TrustFactors; // Breakdown of trust score
  pendingConfirmation?: boolean;
  confirmationUrl?: string;
  timestamp: string;        // ISO 8601 timestamp
}

ctx.log(entry)

Logs an action without verification. Useful for non-financial events.

ctx.export(options)

Exports the audit trail for a given date range and filter set.

ctx.setPolicy(policy)

Configures task confirmation policies.

ctx.setRules(rules)

Configures anomaly detection rules.

ctx.trustHistory(query)

Queries historical trust scores for an agent. Pro feature.

ctx.workflow(name)

Creates a workflow context for multi-step action logging.

Configuration

Kontext can be configured via the constructor, environment variables, or a kontext.config.ts file in your project root.

kontext.config.tstypescript
// kontext.config.ts
import { defineConfig } from '@kontext/sdk';

export default defineConfig({
  chain: 'base',
  environment: 'production',
  rules: {
    velocity: {
      maxTransactions: 100,
      period: '1h',
      action: 'flag',
    },
    amount: {
      maxSingle: '10000',
      maxDaily: '100000',
      currency: 'USDC',
      action: 'flag',
    },
  },
  confirmation: {
    when: [
      { field: 'amount', operator: 'gt', value: '5000' },
    ],
    timeout: 300_000,
    fallback: 'deny',
  },
});

Environment Variables

.envbash
KONTEXT_API_KEY=sk_live_...     # Pro/Enterprise API key
KONTEXT_CHAIN=base              # Default chain
KONTEXT_ENVIRONMENT=production  # Environment

TypeScript Types

All types are exported from the main package and available for your IDE's autocomplete.

types.tstypescript
import type {
  KontextOptions,
  VerifyAction,
  VerifyResult,
  LogEntry,
  ExportOptions,
  AuditTrail,
  Flag,
  TrustFactors,
  TrustHistory,
  Policy,
  Rules,
  WorkflowContext,
} from '@kontext/sdk';

Need help?

If you run into issues or have questions, reach out through any of these channels: