$ DOCUMENTATION

Kontext is a TypeScript SDK that provides compliance infrastructure for agents that move money. Audit trails, OFAC screening, trust scoring, on-chain anchoring, and agent-to-agent attestation -- all in a single function call.

Installation

Install the Kontext SDK using your preferred package manager.

Terminal
bash
npm install kontext-sdk

Or with yarn / pnpm:

Terminal
bash
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. Initialize the SDK, call verify(), and check the result.

agent.ts
typescript
import { Kontext } from 'kontext-sdk';

// Initialize -- no API key needed for local mode
const ctx = Kontext.init({
  projectId: 'my-project',
  environment: 'development',
});

// Verify an x402 micropayment — OFAC screening on every transfer
const result = await ctx.verify({
  txHash: '0xabc...def',
  chain: 'base',
  amount: '0.50',
  token: 'USDC',
  from: '0xAgentWallet',
  to: '0xAPIProvider',
  agentId: 'research-agent',
});

if (!result.compliant) {
  console.warn('Blocked:', result.checks.filter(c => !c.passed));
  console.warn('Risk level:', result.riskLevel);
  // result.recommendations tells you what to do next
} else {
  console.log('Trust score:', result.trustScore.score);
  console.log('Digest proof valid:', result.digestProof.valid);
}

The verify() method is the core of Kontext. It logs the transaction, runs OFAC and threshold checks, computes a trust score, and returns everything you need to make a decision. Every call is chained into a tamper-evident SHA-256 digest.

Action Logging

Every action your agents take should be logged for auditability. Kontext provides action logging, transaction logging, and reasoning logging -- each feeds into the digest chain.

logging.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({ projectId: 'my-project' });

// Log any agent action -- not just transfers
await ctx.log({
  action: 'data_access',
  agentId: 'research-agent',
  details: 'Queried customer database',
  metadata: { purpose: 'quarterly_report' },
});

// Log agent reasoning separately
// When regulators ask "why did your agent do that?" -- you can answer
await ctx.logReasoning({
  agentId: 'payment-agent-v2',
  action: 'approve-transfer',
  reasoning: 'Transfer within daily limit. Recipient verified in allowlist.',
  confidence: 0.95,
  context: { dailyTotal: '32000', recipientVerified: true },
});

// Retrieve reasoning entries later
const entries = ctx.getReasoningEntries('payment-agent-v2');

Reasoning entries are separate from action logs. When regulators ask "why did your agent approve that transfer?" -- reasoning logs are your answer.

Task Confirmation

For high-value or sensitive actions, create a task that requires human approval before the agent proceeds. Tasks track required evidence and who confirmed them.

confirmation.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({ projectId: 'treasury-app' });

// Create a task that requires human approval
const task = await ctx.createTask({
  description: 'Approve $25,000 USDC transfer to 0xrecipient',
  agentId: 'treasury-agent-v2',
  requiredEvidence: ['txHash', 'recipientVerified'],
});

// ... human reviews and approves ...

// Confirm with evidence
const confirmed = await ctx.confirmTask({
  taskId: task.id,
  evidence: {
    txHash: '0xabc...def',
    recipientVerified: true,
  },
  confirmedBy: 'admin@company.com',
});

// Check task status at any time
const status = await ctx.getTaskStatus(task.id);

// List all pending tasks
const pending = ctx.getTasks('pending');

Audit Export

Export your complete audit trail as JSON (CSV on Pro). The digest chain provides cryptographic proof that no records have been tampered with. Generate compliance certificates that bundle the audit trail, trust scores, and reasoning.

export.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({ projectId: 'my-project' });

// ... log some actions and transactions ...

// Export the full audit trail as JSON
const audit = await ctx.export({ format: 'json' });
// audit.data contains all action logs with digest proofs

// Verify the digest chain is intact (no tampering)
const chain = ctx.verifyDigestChain();
console.log('Chain valid:', chain.valid);
console.log('Chain length:', chain.chainLength);

// Get the terminal digest -- your tamper-evident fingerprint
const terminal = ctx.getTerminalDigest();

// Export the full digest chain for external verification
const exported = ctx.exportDigestChain();
// { genesisHash, links, terminalDigest }

// Generate a compliance certificate (includes digest proof + trust score)
const cert = await ctx.generateComplianceCertificate({
  agentId: 'treasury-agent-v2',
  timeRange: { from: startOfMonth, to: endOfMonth },
  includeReasoning: true,
});

Trust Scoring

Every agent gets a trust score from 0 to 100, computed from five factors: history, amount patterns, transaction frequency, destination trust, and behavioral consistency. Use it to gate actions, set thresholds, or flag agents for review.

trust.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({ projectId: 'my-project' });

// Get trust score for any agent
const trust = await ctx.getTrustScore('payment-agent-v2');

console.log(trust.score);   // 87 (0-100)
console.log(trust.level);   // 'high'
console.log(trust.factors);
// {
//   history: 0.95,       -- agent's track record
//   amount: 0.88,        -- transaction amount patterns
//   frequency: 0.92,     -- how often the agent transacts
//   destination: 0.85,   -- recipient trust level
//   behavior: 0.90,      -- behavioral consistency
// }

// Evaluate a transaction before executing it
const evaluation = await ctx.evaluateTransaction({
  txHash: '0xabc...def',
  chain: 'base',
  amount: '15000',
  token: 'USDC',
  from: '0xsender...',
  to: '0xrecipient...',
  agentId: 'payment-agent-v2',
});

Anomaly Detection

Enable rule-based anomaly detection to flag or block suspicious agent behavior. The free tier includes two rules (unusualAmount and frequencySpike). Pro unlocks four more: newDestination, offHoursActivity, rapidSuccession, and roundAmount.

anomaly.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({ projectId: 'my-project' });

// Enable anomaly detection with rules
ctx.enableAnomalyDetection({
  rules: ['unusualAmount', 'frequencySpike'],
  thresholds: {
    maxAmount: '50000',
    maxFrequency: 20,
  },
});

// React to anomalies in real time
const unsubscribe = ctx.onAnomaly((event) => {
  console.log('Anomaly detected:', event.type);
  console.log('Details:', event.details);
  // Alert your compliance team via Slack, PagerDuty, etc.
});

// verify() automatically checks anomaly rules
const result = await ctx.verify({
  txHash: '0xabc...def',
  chain: 'base',
  amount: '75000',
  token: 'USDC',
  from: '0xsender...',
  to: '0xrecipient...',
  agentId: 'payment-agent-v2',
});

// Turn it off when you don't need it
ctx.disableAnomalyDetection();

On-Chain Anchoring

The digest chain gives you tamper-evidence at the software level. On-chain anchoring takes it further -- write the terminal digest to a smart contract on Base or Arc. Now anyone can independently verify that your compliance checks ran at a specific block height. No Kontext account needed.

anchoring.ts
typescript
import { Kontext, verifyAnchor, getAnchor, anchorDigest } from 'kontext-sdk';

const ctx = Kontext.init({ projectId: 'my-project' });

// Option 1: Anchor automatically via verify()
const result = await ctx.verify({
  txHash: '0xabc...def',
  chain: 'base',
  amount: '5000',
  token: 'USDC',
  from: '0xsender...',
  to: '0xrecipient...',
  agentId: 'payment-agent-v2',
  anchor: {
    rpcUrl: 'https://base-mainnet.g.alchemy.com/v2/YOUR_KEY',
    contractAddress: '0xYourAnchorContract',
    privateKey: process.env.ANCHOR_PRIVATE_KEY,
  },
});
// result.anchorProof = { txHash, blockNumber, chain, ... }

// Option 2: Read-only verification -- zero dependencies
const verified = await verifyAnchor(rpcUrl, contractAddress, digest);
// verified.anchored = true/false

// Option 3: Get full anchor details
const details = await getAnchor(rpcUrl, contractAddress, digest);
// details = { anchorer, projectHash, timestamp }

// Option 4: Write an anchor manually (requires viem as peer dep)
const anchorResult = await anchorDigest(
  { rpcUrl, contractAddress, privateKey },
  digest,
  'my-project'
);

The verifyAnchor() and getAnchor() functions have zero dependencies -- they use native fetch() with ABI-encoded RPC calls. The anchorDigest() write function requires viem as a peer dependency.

A2A Attestation

When two agents transact, both sides need proof that the other ran compliance. A2A attestation handles this automatically -- pass a counterparty config to verify() and the SDK exchanges digests via the counterparty's /.well-known/kontext.json agent card and /kontext/attest endpoint.

attestation.ts
typescript
import { Kontext, fetchAgentCard, exchangeAttestation } from 'kontext-sdk';

const ctx = Kontext.init({ projectId: 'my-project' });

// Option 1: Attestation via verify()
const result = await ctx.verify({
  txHash: '0xabc...def',
  chain: 'base',
  amount: '5000',
  token: 'USDC',
  from: '0xsender...',
  to: '0xrecipient...',
  agentId: 'sender-agent',
  counterparty: {
    endpoint: 'https://receiver.example.com',
    agentId: 'receiver-v1',
  },
});
// result.counterparty = { attested, digest, agentId, timestamp }

// Option 2: Discover a counterparty agent
const card = await fetchAgentCard('https://receiver.example.com');
// card = { agentId, kontextVersion, capabilities, attestEndpoint }

// Option 3: Exchange attestation directly
const attestation = await exchangeAttestation(
  { endpoint: 'https://receiver.example.com', agentId: 'receiver-v1' },
  {
    senderDigest: ctx.getTerminalDigest(),
    senderAgentId: 'sender-agent',
    amount: '5000',
    token: 'USDC',
    timestamp: new Date().toISOString(),
  }
);

The attestation protocol uses native fetch() with zero dependencies. Both agents end up with the other's digest linked in their audit trail -- bilateral, cryptographic proof of mutual compliance.

Agent Provenance

Agent provenance adds three layers of accountability on top of the digest chain. Each layer answers a different question regulators ask.

Layer 1: Session Delegation

Records who authorized the agent to act. Every session captures the delegator, the agent, the permitted scope, and an optional expiration. The agent cannot create its own session -- a human or upstream system delegates authority.

Layer 2: Action Binding

Every verify(), log(), and logReasoning() call accepts a sessionId. The action envelope binds the call to the session that authorized it. Actions without a sessionId still log normally but lack the provenance binding.

Layer 3: Human Attestation

After actions execute, a human reviewer creates a checkpoint that references specific action IDs, then attests to it with a signature. The attestation key is held by the reviewer -- the agent never touches it. This proves a human reviewed the actions, not just that they ran.

provenance.ts
typescript
import { Kontext, FileStorage } from 'kontext-sdk';

const ctx = Kontext.init({
  projectId: 'treasury-app',
  storage: new FileStorage('.kontext'),
});

// Layer 1: Session delegation — record who authorized the agent
const session = await ctx.createAgentSession({
  agentId: 'treasury-agent',
  delegatedBy: 'user:vinay',
  scope: ['transfer', 'approve'],
  expiresAt: new Date(Date.now() + 3600_000).toISOString(),
});

// Layer 2: Action binding — every verify() call ties to the session
const result = await ctx.verify({
  txHash: '0xabc...def',
  chain: 'base',
  amount: '5000',
  token: 'USDC',
  from: '0xAgentWallet',
  to: '0xRecipient',
  agentId: 'treasury-agent',
  sessionId: session.sessionId,
});

// Layer 3: Human attestation — reviewer signs off
const checkpoint = await ctx.createCheckpoint({
  sessionId: session.sessionId,
  actionIds: [result.transaction.id],
  summary: 'Reviewed $5K USDC transfer to known vendor',
});

// Attest with a key the agent never touches
const attested = await ctx.attestCheckpoint({
  checkpointId: checkpoint.checkpointId,
  attestedBy: 'compliance-officer@company.com',
  signature: reviewerSignature,
});

// End the session when done
await ctx.endAgentSession(session.sessionId);

// List all sessions and checkpoints
const sessions = ctx.getAgentSessions('treasury-agent');
const checkpoints = ctx.getCheckpoints(session.sessionId);

CLI Commands

Terminal
bash
# Create a session for an agent
npx kontext-sdk session create --agent treasury-agent --delegated-by user:vinay --scope transfer,approve

# List active sessions
npx kontext-sdk session list --agent treasury-agent

# End a session
npx kontext-sdk session end <sessionId>

# Create a checkpoint referencing specific actions
npx kontext-sdk checkpoint create --session <sessionId> --actions act_1,act_2 --summary "Reviewed transfers"

# Attest a checkpoint (human signs off)
npx kontext-sdk checkpoint attest <checkpointId> --attested-by compliance@company.com

# List checkpoints for a session
npx kontext-sdk checkpoint list --session <sessionId>

Agent Identity

Pro

Register agent identities with wallet mappings, reverse-lookup which agent owns a wallet, and manage identity lifecycles. Requires the Pro plan (kya-identity gate).

agent-identity.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({
  apiKey: process.env.KONTEXT_KEY,
  projectId: 'forensics',
  plan: 'payg',
});

// Register an agent with wallet mappings
ctx.registerAgentIdentity({
  agentId: 'treasury-agent-v2',
  displayName: 'Treasury Agent',
  entityType: 'autonomous',  // 'autonomous' | 'semi-autonomous' | 'human-supervised'
  wallets: [
    { address: '0xTreasury...abc', chain: 'base', label: 'primary' },
    { address: '0xReserve...def', chain: 'base', label: 'reserve' },
  ],
});

// Add a wallet later
ctx.addAgentWallet('treasury-agent-v2', {
  address: '0xOps...ghi', chain: 'ethereum', label: 'operations',
});

// Reverse lookup: which agent owns this wallet?
const agent = ctx.lookupAgentByWallet('0xTreasury...abc');
console.log(agent?.agentId); // 'treasury-agent-v2'

// Retrieve identity
const identity = ctx.getAgentIdentity('treasury-agent-v2');

Wallet Clustering

Pro

Detect wallets controlled by the same agent using a Union-Find algorithm with 5 heuristics. Each cluster includes evidence trails documenting why wallets were grouped.

wallet-clustering.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({
  apiKey: process.env.KONTEXT_KEY,
  projectId: 'forensics',
  plan: 'payg',
});

// Register agents and their wallets...
// Then detect clusters across all registered agents
const clusters = ctx.getWalletClusters();

for (const cluster of clusters) {
  console.log('Cluster wallets:', cluster.wallets);
  console.log('Heuristics matched:', cluster.heuristics);
  // e.g. ['shared-owner', 'funding-chain', 'temporal-correlation']
  console.log('Evidence:', cluster.evidence);
}

// 5 clustering heuristics:
// - shared-owner: wallets registered to the same agent
// - temporal-correlation: wallets active in the same time windows
// - funding-chain: one wallet funds another
// - amount-pattern: matching transaction amounts across wallets
// - network-overlap: shared counterparties

Confidence Scoring

Pro

Compute a composite identity confidence score (0-100) for registered agents. The score combines 5 components: identity-completeness, wallet-verification, behavioral-consistency, historical-depth, and cluster-coherence.

confidence-scoring.ts
typescript
import { Kontext } from 'kontext-sdk';

const ctx = Kontext.init({
  apiKey: process.env.KONTEXT_KEY,
  projectId: 'forensics',
  plan: 'payg',
});

// Compute identity confidence for an agent
const score = ctx.getKYAConfidenceScore('treasury-agent-v2');

console.log(score.score);      // 82 (0-100)
console.log(score.level);      // 'high' | 'medium' | 'low' | 'very-low'
console.log(score.components); // breakdown by factor

// Components: identity-completeness, wallet-verification,
//             behavioral-consistency, historical-depth, cluster-coherence

// Export all forensics data
const envelope = ctx.getKYAExport();
// { identities, clusters, embeddings, links, scores, generatedAt }

CLI Installation

The Kontext CLI (@kontext-sdk/cli) provides 12 commands for compliance operations from the terminal. Install globally or run via npx — no project setup required.

Terminal
bash
# Install globally
npm install -g @kontext-sdk/cli

# Or run directly with npx (no install)
npx @kontext-sdk/cli verify --chain base --amount 0.50

# Verify installation
kontext --version  # 0.8.0

CLI Commands

Every SDK operation has a CLI equivalent. Run compliance checks, verify transactions, generate certificates, export audit trails, and anchor digests — all from the command line.

Terminal
bash
# Static compliance check (no digest chain)
kontext check --chain base --amount 0.50 --from 0xSender --to 0xRecipient

# Full verification with digest chain and trust scoring
kontext verify --chain base --amount 0.50 --token USDC \
  --from 0xSender --to 0xRecipient --agent research-agent

# Log agent reasoning
kontext reason --agent payment-agent-v2 \
  --action approve-transfer \
  --reasoning "Within daily limit. Recipient verified."

# Generate compliance certificate
kontext cert --agent payment-agent-v2 --format json

# Export audit trail
kontext audit --format json --output ./audit-trail.json

# Anchor digest on-chain
kontext anchor --rpc https://mainnet.base.org --contract 0xbc71...b46

# Exchange A2A attestation
kontext attest --endpoint https://counterparty.example.com

# Sync OFAC SDN list
kontext sync --list ofac

# Manage agent sessions and checkpoints
kontext session create --agent treasury-agent --scope transfer,approve
kontext checkpoint create --session <sessionId> --summary "Reviewed batch"

MCP Server

The CLI includes a built-in MCP (Model Context Protocol) server that exposes 8 compliance tools to AI coding assistants like Claude Code, Cursor, and Windsurf. Start it with kontext mcp.

Terminal
bash
# Start the MCP server
kontext mcp

# Add to Claude Code / Cursor / Windsurf config:
{
  "mcpServers": {
    "kontext": {
      "command": "npx",
      "args": ["@kontext-sdk/cli", "mcp"]
    }
  }
}

# 8 MCP tools exposed:
# - kontext_check: static compliance check
# - kontext_verify: full verification
# - kontext_reason: log agent reasoning
# - kontext_cert: generate certificate
# - kontext_audit: export audit trail
# - kontext_trust: get trust score
# - kontext_anchor: on-chain anchoring
# - kontext_attest: A2A attestation

API Reference

Complete reference for all Kontext SDK methods. The SDK uses a private constructor with a static Kontext.init(config) factory.

api-reference.ts
typescript
// Initialization
const ctx = Kontext.init(config: KontextConfig): Kontext;

// The main function -- compliance check + transaction log in one call
await ctx.verify(input: VerifyInput): Promise<VerifyResult>;

// Action logging
await ctx.log(input: LogActionInput): Promise<ActionLog>;
await ctx.logTransaction(input: LogTransactionInput): Promise<TransactionRecord>;
await ctx.logReasoning(input: LogReasoningInput): Promise<ReasoningEntry>;
ctx.getReasoningEntries(agentId: string): ReasoningEntry[];
await ctx.flushLogs(): Promise<void>;

// Task confirmation (human-in-the-loop)
await ctx.createTask(input: CreateTaskInput): Promise<Task>;
await ctx.confirmTask(input: ConfirmTaskInput): Promise<Task>;
await ctx.getTaskStatus(taskId: string): Promise<Task | undefined>;
await ctx.startTask(taskId: string): Promise<Task>;
await ctx.failTask(taskId: string, reason: string): Promise<Task>;
ctx.getTasks(status?: TaskStatus): Task[];

// Trust scoring
await ctx.getTrustScore(agentId: string): Promise<TrustScore>;
await ctx.evaluateTransaction(tx: LogTransactionInput): Promise<TransactionEvaluation>;

// Anomaly detection
ctx.enableAnomalyDetection(config: AnomalyDetectionConfig): void;
ctx.disableAnomalyDetection(): void;
ctx.onAnomaly(callback: AnomalyCallback): () => void;

// Audit export
await ctx.export(options: ExportOptions): Promise<ExportResult>;
await ctx.generateReport(options: ReportOptions): Promise<ComplianceReport>;
await ctx.generateComplianceCertificate(input): Promise<ComplianceCertificate>;

// Digest chain (tamper-evidence)
ctx.getTerminalDigest(): string;
ctx.verifyDigestChain(): DigestVerification;
ctx.exportDigestChain(): { genesisHash, links, terminalDigest };
ctx.getActions(): ActionLog[];

// Agent provenance
await ctx.createAgentSession(input: CreateAgentSessionInput): Promise<AgentSession>;
await ctx.endAgentSession(sessionId: string): Promise<AgentSession>;
ctx.getAgentSessions(agentId: string): AgentSession[];
await ctx.createCheckpoint(input: CreateCheckpointInput): Promise<Checkpoint>;
await ctx.attestCheckpoint(input: AttestCheckpointInput): Promise<Checkpoint>;
ctx.getCheckpoints(sessionId: string): Checkpoint[];

// Persistence
await ctx.flush(): Promise<void>;
await ctx.restore(): Promise<void>;

// Plan management
ctx.getUsage(): PlanUsage;
ctx.setPlan(tier: PlanTier): void;
ctx.onUsageWarning(callback): () => void;
ctx.onLimitReached(callback): () => void;

// Lifecycle
await ctx.destroy(): Promise<void>;

Configuration

Kontext is configured via Kontext.init(config). No config files, no environment variable magic. Everything is explicit in code.

config.ts
typescript
import { Kontext, FileStorage } from 'kontext-sdk';

const ctx = Kontext.init({
  // Required
  projectId: 'my-project',

  // Optional
  environment: 'production',  // 'development' | 'staging' | 'production'
  apiKey: 'sk_live_...',      // only needed for cloud mode
  plan: 'free',               // 'free' | 'payg' | 'enterprise'

  // Persistence -- default is in-memory (resets on restart)
  storage: new FileStorage('./compliance-data'),

  // Event exporters -- where to send events
  exporters: [
    // new ConsoleExporter(),       // prints to stdout (dev)
    // new JsonFileExporter(path),  // writes JSONL to disk
    // new HttpExporter(config),    // sends to any HTTP endpoint
    // new KontextCloudExporter(),  // ships to api.getkontext.com (payg)
  ],
});

Environment Variables

.env
bash
KONTEXT_API_KEY=sk_live_...     # API key for cloud mode (Pro)
KONTEXT_CHAIN=base              # Default chain
KONTEXT_ENVIRONMENT=production  # Environment

TypeScript Types

All types are exported from the main package. Full autocomplete in any TypeScript-aware editor.

types.ts
typescript
import type {
  // Core
  KontextConfig,
  KontextMode,
  LogActionInput,
  LogTransactionInput,
  TransactionRecord,
  ActionLog,

  // Verify
  VerifyInput,
  VerifyResult,

  // Tasks
  Task,
  CreateTaskInput,
  ConfirmTaskInput,

  // Trust & Anomaly
  TrustScore,
  AnomalyEvent,
  AnomalyDetectionConfig,

  // Export & Reports
  ExportOptions,
  ExportResult,
  ComplianceReport,
  DigestVerification,

  // Reasoning & Certificates
  ReasoningEntry,
  ComplianceCertificate,

  // On-chain anchoring
  OnChainAnchorConfig,
  AnchorResult,
  AnchorVerification,

  // A2A attestation
  AgentCard,
  CounterpartyConfig,
  AttestationRequest,
  AttestationResponse,
  CounterpartyAttestation,

  // Agent provenance
  AgentSession,
  CreateAgentSessionInput,
  Checkpoint,
  CreateCheckpointInput,
  AttestCheckpointInput,
} from 'kontext-sdk';

Need help?

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