TypeScript SDK API Reference

The shape of `@neo4j-labs/agent-memory’s public surface, with deep links into the auto-generated TypeDoc reference for each symbol.

Full method-level reference lives in the TypeDoc-generated site at neo4j-labs.github.io/agent-memory/typescript/. That site has every parameter, every property, every overload. This page is the map — what the SDK exposes and which TypeDoc symbol to open.

The TypeDoc site is regenerated on every typescript-v* tag (see .github/workflows/docs-typedoc.yml) and on every push to main that touches typescript/src/**.

Installation

npm install @neo4j-labs/agent-memory
# pnpm add @neo4j-labs/agent-memory
# bun add @neo4j-labs/agent-memory

Requires Node.js 20+. Works in Bun, Deno, Cloudflare Workers, and Vercel Edge — the transport is fetch-only.

MemoryClient

The root class. Holds five subclients (shortTerm, longTerm, reasoning, query, auth) and the underlying Transport.

import { MemoryClient } from "@neo4j-labs/agent-memory";

// Zero-config: reads MEMORY_API_KEY from environment, targets hosted NAMS.
const memory = new MemoryClient();

// With options
const memory = new MemoryClient({
  endpoint: "https://memory.neo4jlabs.com/v1",
  apiKey: process.env.MEMORY_API_KEY,
  timeout: 30_000,
  headers: { "X-Trace-Id": traceId },
  logger: (event) => console.log(event),
});

MemoryClientOptions

Field Type Description Default

endpoint

string

The NAMS REST endpoint. Auto-selects REST transport when ending in /v\d+.

https://memory.neo4jlabs.com/v1

apiKey

string

Bearer token for Authorization header.

process.env.MEMORY_API_KEY

tokenProvider

() ⇒ string | Promise<string>

Dynamic token source (OAuth refresh, AWS STS, etc.). Overrides apiKey.

transport

"auto" | "bridge" | "rest"

Force the wire protocol. "auto" selects based on endpoint shape.

"auto"

timeout

number

Per-request timeout in milliseconds.

30000

headers

Record<string, string>

Extra request headers (User-Agent, trace headers, etc.).

logger

(event: LogEvent) ⇒ void

Receives request / response / error events for observability.

client.shortTerm — short-term memory

Conversations, messages, three-tier context.

Method Purpose

addMessage(sessionId, role, content, options?)

Append a message to a conversation. Returns the persisted Message.

getConversation(sessionId, options?)

Fetch a conversation by id, with its messages.

searchMessages(query, options?)

Semantic + filter search across stored messages.

listSessions(options?)

Enumerate session ids (with message counts and timestamps).

deleteMessage(messageId)

Remove a single message.

clearSession(sessionId)

Delete the whole conversation.

createConversation(options) (hosted)

Explicitly create a conversation with metadata (title, userId, workspace).

listConversations(options?) (hosted)

Enumerate full conversation objects.

getConversationMetadata(conversationId) (hosted)

Conversation header without the message list.

deleteConversation(conversationId) (hosted)

Delete an entire conversation.

getContext(conversationId) (hosted)

Three-tier window: reflections, observations, recent messages — designed to be dropped into an LLM prompt.

bulkAddMessages(conversationId, messages) (hosted)

Persist many messages in one HTTP round-trip.

getObservations(conversationId, options?) (hosted)

Inline observations extracted from the conversation so far.

getReflections(conversationId) (hosted)

Higher-level reflections generated when accumulated context crosses the compression threshold.

Returned types: Message, Conversation, ConversationContext, SessionInfo, Observation, Reflection.

Hosted vs bridge: methods marked (hosted) require a NAMS REST endpoint (default). The bridge transport (for TCK conformance) raises NotSupportedError for these.

TypeDoc: ShortTermMemory

client.longTerm — long-term memory

Entities (POLE+O), preferences, facts, relationships.

Method Purpose

addEntity(name, entityType, options?)

Create an entity. Returns the persisted Entity.

addPreference(category, preference, options?)

Record a preference (food, communication, dietary, etc.).

addFact(subject, predicate, object)

Store a typed subject-predicate-object triple.

searchEntities(query, options?)

Semantic search over entities, with optional type filter and topK.

searchPreferences(query, options?)

Semantic search over preferences, with optional category filter.

getEntityByName(name)

Look up an entity by exact name (returns null if not found).

getRelatedEntities(entityId, options?)

Walk relationships outward from a given entity.

addRelationship(sourceId, targetId, relationshipType, options?)

Create a typed relationship between two entities.

mergeDuplicateEntities(sourceId, targetId, options?)

Merge source into target; aliases the source name onto target.

listEntities(options?) (hosted)

Enumerate entities, optionally filtered by type, with pagination.

getEntity(entityId) (hosted)

Fetch an entity by id.

updateEntity(entityId, options) (hosted)

Patch an entity’s description, type, or metadata.

deleteEntity(entityId) (hosted)

Remove an entity.

setEntityFeedback(entityId, options) (hosted)

Record positive/negative feedback that signals dedup/merge intent.

getEntityHistory(entityId) (hosted)

Audit log of changes to an entity.

mergeEntities(sourceId, targetId) (hosted)

Server-side merge with conflict resolution.

getEntityGraph() (hosted)

Snapshot of the entity graph (nodes + edges) for visualization.

Returned types: Entity, Preference, Fact, Relationship, EntityHistory, EntityGraph.

Entity types: hosted service uses lowercase strings — "person", "organization", "location", "concept", "tool", "custom". The bridge protocol uses POLE+O uppercase — "PERSON", "ORGANIZATION", "LOCATION", "EVENT", "OBJECT". The SDK normalizes both directions.

TypeDoc: LongTermMemory

client.reasoning — reasoning memory

Reasoning traces, steps, tool calls.

Method Purpose

startTrace(sessionId, task)

Begin a reasoning trace. Returns a ReasoningTrace with a traceId.

addStep(traceId, options?)

Add a step (thought / action / observation) to a trace.

recordToolCall(stepId, toolName, args, options?)

Persist a tool call: name, arguments, result, status, duration.

completeTrace(traceId, options?)

Mark the trace finished with an outcome and success: boolean.

getTraceWithSteps(traceId)

Fetch a trace including its steps and tool calls.

listTraces(options?)

Enumerate traces (filter by session, success, time range).

getToolStats(toolName?)

Per-tool aggregate stats: success rate, average duration.

getSimilarTraces(task, options?)

"What did I do last time I tried something like this?" Semantic search over past traces.

recordStep(input) (hosted)

Record a "step" event for the hosted agent-trace surface.

listSteps(conversationId) (hosted)

All steps recorded against a conversation.

explainStep(stepId) (hosted)

Server-generated explanation of why an agent did what it did.

getTraceByConversation(conversationId) (hosted)

Pull the full reasoning trace tied to a conversation.

getEntityProvenance(entityId) (hosted)

"Which reasoning steps touched this entity?" — audit query.

Returned types: ReasoningTrace, ReasoningStep, ToolCall, ToolStats, AgentStep, ConversationTrace, EntityProvenance.

Status values for ToolCall: "pending", "success", "failure", "error", "timeout", "cancelled".

TypeDoc: ReasoningMemory

client.query — read-only Cypher (hosted only)

Method Purpose

cypher({ cypher, params? })

Run a read-only Cypher query against the NAMS-managed graph. Returns { columns, rows, stats? }. Write queries are rejected server-side.

TypeDoc: QueryConsole

client.auth — API key + OAuth (hosted only)

Method Purpose

listApiKeys(workspaceId)

Enumerate keys in a workspace.

createApiKey(input)

Mint a new key. The plaintext key is only returned at creation — store it then.

revokeApiKey(keyId)

Permanently revoke a key.

revealApiKey(keyId, workspaceId)

Re-reveal a stored key (one-time, if your account has the scope).

refreshAccessToken(refreshToken)

Exchange a refresh token for a fresh access token pair.

TypeDoc: AuthClient

Errors

Every error extends MemoryError and carries an optional requestId for correlation with server logs.

Class Raised when

MemoryError

Base class. Catch this if you want everything.

ConnectionError

Network failure — DNS, refused, TLS handshake. Wraps the underlying fetch error.

AuthenticationError

HTTP 401 / 403. Missing, expired, or scope-restricted API key.

NotFoundError

HTTP 404. Conversation, entity, or trace id does not exist.

ValidationError

HTTP 400. Required field missing or value out of range. details carries the server’s per-field complaint.

TransportError

HTTP 5xx after retries exhausted, OR any non-mapped status. Carries statusCode and responseBody.

RateLimitError

HTTP 429 after retries exhausted. Honors Retry-After header during retry.

NotSupportedError

Method exists on the SDK but the current transport doesn’t implement it (e.g., calling hosted-only methods over a TCK bridge).

import {
  MemoryClient,
  MemoryError,
  AuthenticationError,
  RateLimitError,
} from "@neo4j-labs/agent-memory";

try {
  await memory.shortTerm.addMessage(sessionId, "user", text);
} catch (err) {
  if (err instanceof AuthenticationError) {
    // rotate the key
  } else if (err instanceof RateLimitError) {
    // back off; err.retryAfter is in seconds
  } else if (err instanceof MemoryError) {
    console.error("memory failure", { requestId: err.requestId, err });
  }
}

TypeDoc: MemoryError and subclasses

Subpath exports

The package exposes six subpath exports beyond the root. Each is independently importable to keep tree-shaking honest on edge runtimes.

Import Exports Use it for

@neo4j-labs/agent-memory

MemoryClient, types, errors, VERSION

Standard application code.

@neo4j-labs/agent-memory/middleware/vercel-ai

agentMemoryMiddleware, AgentMemoryLanguageModelMiddleware

Wire memory into a Vercel AI SDK generateText / streamText call. See Vercel AI SDK middleware.

@neo4j-labs/agent-memory/mcp

createMemoryTools, handleMemoryToolCall, McpToolDefinition

Register the 12 standard memory tools with an MCP server. See MCP tools.

@neo4j-labs/agent-memory/integrations/langchain

Neo4jChatMessageHistory, Neo4jEntityRetriever

LangChain JS — duck-typed against BaseChatMessageHistory and BaseRetriever. See LangChain JS.

@neo4j-labs/agent-memory/integrations/mastra

Neo4jMastraMemory

Mastra agent framework. See Mastra.

@neo4j-labs/agent-memory/integrations/strands

Neo4jSessionStorage, Neo4jConversationManager, registerReasoningHooks, connectMemoryToAgent

AWS Strands Agents SDK (JS). See Strands.

@neo4j-labs/agent-memory/testing

BridgeTransport, BridgeTransportOptions

TCK conformance testing against a local bridge server. Production code should not import from here.

TypeDoc: each subpath’s exports are listed under the matching module in the TypeDoc index.

Observability

The logger constructor option receives typed `LogEvent`s for every transport call:

import { MemoryClient, type LogEvent } from "@neo4j-labs/agent-memory";

const memory = new MemoryClient({
  logger: (event: LogEvent) => {
    if (event.kind === "error") {
      console.error("memory.error", event);
    }
  },
});
event.kind Fields

"request"

method, url, httpMethod?

"response"

method, url, status, requestId?, durationMs

"error"

method, url, status?, requestId?, durationMs, message

See How-to: enable observability for the full pattern including OpenTelemetry forwarding.

Versioning

The TypeScript SDK follows SemVer:

  • Major — backwards-incompatible API change (rare; expect a migration guide).

  • Minor — new methods, new options. Existing code keeps working.

  • Patch — bug fixes, no API change.

Release tags are namespaced typescript-v<X.Y.Z> so they don’t collide with the Python SDK’s python-v<X.Y.Z> tags. The current published version is in typescript/CHANGELOG.md.

See also