Skip to content

TypeScript SDK ​

The TypeScript SDK is a REST client for contextdb, located in sdk/typescript/.

Installation ​

bash
npm install contextdb

Connection ​

typescript
import { ContextDB } from "contextdb";

const db = new ContextDB("http://localhost:7701");

Namespace ​

typescript
const ns = db.namespace("my-app", "general");

The mode parameter accepts: general, belief_system, agent_memory, procedural.

Write ​

typescript
const result = await ns.write({
  content: "Go 1.22 added routing patterns to net/http",
  sourceId: "docs-crawler",
  labels: ["Claim"],
  properties: { url: "https://go.dev/blog" },
  confidence: 0.9,
});

console.log(result.nodeId);     // UUID string
console.log(result.admitted);   // true/false
console.log(result.reason);     // rejection reason if not admitted
console.log(result.conflictIds); // contradicting node IDs

WriteRequest fields ​

FieldTypeRequiredDescription
contentstringYesText content
sourceIdstringYesExternal source identifier
labelsstring[]NoNode labels
propertiesRecord<string, unknown>NoArbitrary metadata
vectornumber[]NoPre-computed embedding
modelIdstringNoEmbedding model identifier
confidencenumberNoConfidence [0, 1]

WriteResult fields ​

FieldTypeDescription
nodeIdstringUUID of the written node
admittedbooleanWhether the write was accepted
reasonstringRejection reason (empty if admitted)
conflictIdsstring[]UUIDs of contradicting nodes

Retrieve ​

typescript
// Vector-based query
const results = await ns.retrieve({ vector: [0.1, 0.2, 0.3], topK: 5 });

// Text-based query (lexical; also vector search if an embedder is configured)
const results = await ns.retrieve({ text: "What changed in Go 1.22?", topK: 5, candidateK: 40, rerankK: 12 });

// With label filtering
const results = await ns.retrieve({
  text: "routing patterns",
  labels: ["Claim"],
  topK: 10,
});

// With custom score weights
const results = await ns.retrieve({
  text: "routing patterns",
  topK: 5,
  scoreParams: {
    similarityWeight: 0.6,
    confidenceWeight: 0.2,
    recencyWeight: 0.1,
    utilityWeight: 0.1,
  },
});

for (const r of results) {
  console.log(`${r.score.toFixed(2)} ${r.node.properties.text}`);
}

// Retract one source's support without removing other corroboration.
await ns.retractSourceAssertion("<node-uuid>", "ledger", "corrected");

RetrieveRequest fields ​

FieldTypeRequiredDescription
vectornumber[]For vector searchQuery embedding
textstringFor text searchLexical search; also auto-embedded when configured
seedIdsstring[]For graph walkKnown relevant node IDs
topKnumberNoMax results (default: 10)
candidateKnumberNoPer-path candidate budget before fusion
rerankKnumberNoNumber of fused candidates sent to an optional reranker
labelsstring[]NoFilter to nodes with all specified labels
scoreParamsScoreParamsNoOverride scoring weights

Result fields ​

FieldTypeDescription
nodeNodeFull node with labels, properties, metadata
scorenumberComposite score [0, 1]
similarityScorenumberVector similarity component
confidenceScorenumberConfidence component
recencyScorenumberRecency component
utilityScorenumberUtility component
retrievalSourcestring"vector", "graph", or "fused"

Ingest text ​

typescript
const result = await ns.ingestText(
  "Alice knows Go and Python. Bob specializes in Rust.",
  "docs-crawler",
);

console.log(result.nodesWritten); // 4
console.log(result.edgesWritten); // 3
console.log(result.rejected);     // 0

Label source ​

typescript
await ns.labelSource("user:spammer", ["troll"]);
await ns.labelSource("moderator:alice", ["moderator"]);

Acquisition execution ​

typescript
const preview = await ns.acquisitionExecution({
  budget: 2,
  maxResults: 3,
  maxAttempts: 2,
  allowedSourceIds: ["docs/runbook"],
  connectors: [{
    id: "docs-search",
    type: "search",
    endpoint: "https://search.example.internal/contextdb",
    allowedSourceIds: ["docs/runbook"],
    defaultLabels: ["acquired"],
  }],
});

console.log(preview.dry_run); // true

Set execute: true only after reviewing the dry-run connector calls. Execution writes returned connector items through the normal contextdb write path after source allow-list filtering. maxAttempts opts into retrying transient connector failures. Use acquisitionExecutionReceipts, acquisitionRetryCandidates, and acquisitionRetryRecommendations to inspect append-only attempt receipts and retry guidance.

Health check ​

typescript
await db.ping();   // { status: "ok" }
await db.stats();  // server statistics object

Released under the MIT License.