TypeScript SDK API reference
The shape of the public surface of @neo4j-labs/agent-memory, with deep links into the auto-generated TypeDoc reference for each symbol.
|
This map describes the released A source manifest or a generated page does not prove that an API has shipped in an npm artifact. Verify the installed package’s exports/types before adopting new APIs. Source-checkout tutorials build the in-tree SDK explicitly. |
|
Full method-level reference is bundled with these docs as the TypeDoc-generated site at the TypeDoc API reference. It has every parameter, every property, every overload. This page is the map — what the SDK exposes and which TypeDoc symbol to open. The TypeDoc pages are regenerated into
|
Installation
npm install @neo4j-labs/[email protected]
# pnpm add @neo4j-labs/[email protected]
# bun add @neo4j-labs/[email protected]
Requires Node.js 22+. The core REST transport uses fetch; pass credentials explicitly where environment access differs. Framework adapters retain their own runtime and peer requirements.
MemoryClient
The root class. Holds six subclients (shortTerm, longTerm, reasoning, query, auth, ontology) 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();
// Alternatively, construct a client with options.
const configuredMemory = new MemoryClient({
endpoint: "https://memory.neo4jlabs.com/v1",
apiKey: process.env.MEMORY_API_KEY,
timeout: 30_000,
headers: { "X-Trace-Id": "example-trace-id" },
logger: (event) => console.log(event),
});
new MemoryClient(options) selects a transport; a supplied Transport is also
accepted for tests/adapters. Construction makes no HTTP request. Ordinary calls
connect lazily; await client.connect() performs an optional explicit probe.
await client.close() closes client resources and does not delete stored data.
MemoryClientOptions
| Field | Type | Description | Default |
|---|---|---|---|
|
|
The NAMS REST endpoint. Auto-selects REST when the endpoint contains a version path matching |
|
|
|
Bearer token for |
|
|
|
NAMS workspace id, sent as the |
|
|
|
Dynamic token source (OAuth refresh, AWS STS, etc.). Overrides |
— |
|
|
Force the wire protocol. |
|
|
|
Per-request timeout in milliseconds. |
|
|
|
Extra request headers (User-Agent, trace headers, etc.). |
— |
|
|
Accepted but currently unused; does not scope requests or isolate entities. |
— |
|
|
Receives |
— |
TypeDoc: MemoryClient · MemoryClientOptions
client.shortTerm — short-term memory
Conversations, messages, three-tier context. On REST, create a conversation first
and reuse its returned id. userId is metadata and a supported list filter, not
a substitute for a conversation id or an authorization policy.
| Method | Purpose |
|---|---|
|
Append a message to a conversation. Returns the persisted |
|
Fetch a conversation by id, with its messages oldest first. On REST these are at most the newest 200 messages; the service lists them newest first and the client reverses them. |
|
Semantic + filter search within the required |
|
Enumerate session ids (with message counts and timestamps). |
|
Bridge only. REST raises |
|
Delete the whole conversation. |
|
Create a conversation with required |
|
Enumerate full conversation objects, most recently updated first. The service serves at most 200 per page; the client follows its |
|
Conversation header without the message list. |
|
Delete an entire conversation. |
|
Three-tier window: reflections, observations, recent messages — designed to be dropped into an LLM prompt. |
|
Persist up to 100 messages in one HTTP round-trip. More than 100 raises a plain |
|
Inline observations extracted from the conversation so far. |
|
Higher-level reflections generated when accumulated context crosses the compression threshold. |
Options and scope: addMessage accepts metadata; getConversation accepts
limit, which REST sends as 200 when omitted and clamps to 200 (the service’s maximum). Both, and clearSession, accept an options
conversationId alias when the positional sessionId is undefined; the
positional id wins if both exist. Missing both raises ValidationError.
searchMessages accepts sessionId / conversationId, limit (10) and
threshold (0.7). On REST, missing both ids raises a pre-request TransportError
for the required path parameter. listSessions defaults its limit to 100.
listConversations accepts userId and limit (default 100; REST pages past 200); getObservations accepts
limit, with an omitted value left to the server.
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 and graph views on REST. The compatibility operations marked bridge only
raise NotSupportedError on REST. They are not substitutes for hosted entity APIs.
| Method | Purpose |
|---|---|
|
Create an entity. On the hosted service, a sufficiently similar existing entity can cause the create to auto-merge onto it instead of creating a new record; the returned |
|
Record a preference (food, communication, dietary, etc.). |
|
Store a typed subject-predicate-object triple. |
|
Semantic search over entities, with optional |
|
Semantic search over preferences, with optional category filter. |
|
Look up an entity by exact name (returns |
|
Walk relationships outward from a given entity. |
|
Create a typed relationship between two entities. |
|
Merge |
|
Enumerate entities with optional |
|
Fetch an entity by id. |
|
Patch an entity’s |
|
Remove an entity. |
|
Record positive/negative feedback that signals dedup/merge intent. |
|
Audit log of changes to an entity. |
|
Server-side merge with conflict resolution. |
|
Snapshot of the workspace entity graph (nodes + edges) for visualization. |
|
Expand around a graph node, excluding already loaded ids (default |
|
Poll |
Hosted entity auto-merge: NAMS resolves-before-create. When the name passed to
addEntity is a sufficiently close match to an existing entity, the hosted service
responds {id, resolution: "merged", merged_into, confidence} instead of a
full entity record — with no name/type at all. The client detects
resolution === "merged" and follows up with GET /entities/{id} (using
merged_into, falling back to the response’s own id) to fetch the
canonical merged-into entity, and that is what addEntity returns — so the
resulting name and type can differ from what was passed in. If that
follow-up GET 404s, or comes back with no name, the client falls back to a
locally constructed Entity (the request’s name, a lowercased
entityType, and a client-generated createdAt); other transport errors
propagate, and a malformed canonical response (a missing id/type, or a field
of the wrong shape) throws ValidationError. Either way, Entity.metadata
(Record<string, unknown>) gains an added nams_resolution object:
| Field | Meaning |
|---|---|
|
Always |
|
Id of the canonical entity the create resolved onto. |
|
Present only when the service reported a match confidence. Does not populate |
|
|
Null normalization: optional fields that arrive over the wire as null —
on Entity, EntityRelationshipRef, Preference, Fact and
EntityMention — are normalized to undefined, so every optional property
is T | undefined at runtime, matching its declared type.
Returned types: Entity, Preference, Fact, Relationship, EntityHistory, EntityGraph.
Readiness options for waitForExtraction:
| Option | Type | Default/constraint |
|---|---|---|
|
|
First expected name when omitted; empty string for a predicate-only check. |
|
|
Case-insensitive names that must all appear. |
|
|
Takes precedence over expected names/count when supplied. |
|
|
1; used when neither a predicate nor expected names is supplied. |
|
|
10; effective search limit is at least the minimum count and expected-name count. |
|
|
30,000; bounded polling returns |
|
|
1,000 between unsuccessful polls. |
waitForExtraction requires query, expectedNames or predicate.
Defaults are 30,000 ms timeout, 1,000 ms interval and minResults: 1; the search
limit defaults to 10 and is raised to at least minResults and the number of
expected names. Prefer a
predicate or case-insensitive expectedNames for this ingestion: unrelated
nearest-neighbor results can satisfy a mere count. Returns false on timeout;
validation and transport failures propagate. Both this helper and graph
expansion ship in 0.5.0.
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 |
|---|---|
|
Begin a reasoning trace. Returns a |
|
Add a step (thought / action / observation) to a trace. |
|
Persist a tool call: name, arguments, result, status, duration. |
|
Mark the trace finished with an outcome and |
|
Fetch a trace including its steps and tool calls. |
|
Enumerate traces with |
|
Per-tool aggregate stats: success rate, average duration. |
|
"What did I do last time I tried something like this?" Semantic search over past traces. |
|
Record a "step" event for the hosted agent-trace surface. |
|
All steps recorded against a conversation. |
|
Read the recorded step together with its tool calls and influenced entities. This is a provenance view, not hidden model reasoning. |
|
Pull the full reasoning trace tied to a conversation. |
|
"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 |
|---|---|
|
Run a read-only Cypher query against the NAMS-managed graph. Returns |
TypeDoc: QueryConsole
client.auth — API key + OAuth (hosted only)
| Method | Purpose |
|---|---|
|
Enumerate keys in a workspace. |
|
Mint a new key. The plaintext key is only returned at creation — store it then. |
|
Permanently revoke a key. |
|
Request plaintext for a stored key in the workspace, where authorized by the service. |
|
Mint a replacement key and revoke the old one. |
|
Exchange a refresh token for a fresh access token pair. |
TypeDoc: AuthClient
client.ontology — domain ontologies (hosted only)
Typed, versioned, validated domain schemas. See Ontology API and Use ontologies.
| Method | Purpose |
|---|---|
|
System templates + workspace-owned ontologies (active flagged). |
|
One ontology with its full revision history. |
|
Active parsed document plus |
|
Editable workspace copy of a system template (rev 1). |
|
New workspace ontology from a schema document. |
|
New immutable revision. |
|
Bind the version to the workspace. Validation enforcement is a service behavior, separate from successful activation. |
|
Delete a workspace-owned ontology. |
|
Convert an external graph/ontology document into a non-persisted draft ( |
|
Structural diff between two revisions ( |
|
Enqueue an async label-rename migration; returns a |
|
Poll a migration job’s status/progress. |
Errors
The classes below describe SDK errors. Not all thrown values extend
MemoryError: client guards, token providers, response parsing and fetch aborts
can throw ordinary errors. A server correlation id is optional and appears only
when captured from a response header.
| Class | Current REST behavior |
|---|---|
|
Base class of the SDK’s named errors; does not cover every failure. |
|
Wraps fetch |
|
HTTP 401 or 403. |
|
Other non-success statuses, including 400, 404, 429 and 5xx on ordinary requests; carries |
|
Selected client-side argument checks. Has no |
|
Exported compatibility class; ordinary REST 404 responses use |
|
No implementation on the selected transport; raised before HTTP. |
The client makes one attempt per ordinary request. It does not automatically
retry, expose RateLimitError, or honor Retry-After for retries. A normal
request timeout can propagate a DOMException named TimeoutError; it is not
always a ConnectionError. See handling errors
for a bounded retry of an idempotent read.
import { MemoryClient, AuthenticationError, MemoryError, TransportError } from "@neo4j-labs/agent-memory";
const client = new MemoryClient();
try {
await client.shortTerm.listConversations({ limit: 5 });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Check credentials and workspace access", error.requestId);
} else if (error instanceof TransportError) {
console.error("HTTP failure", error.statusCode, error.requestId);
} else if (error instanceof MemoryError) {
console.error(error.message, error.requestId);
}
throw error; // Preserve non-SDK errors too.
} finally {
await client.close();
}
TypeDoc: MemoryError and subclasses
Subpath exports
The package exposes seven subpath exports beyond the root. Each is independently importable to keep tree-shaking honest on edge runtimes.
| Import | Exports | Use it for |
|---|---|---|
|
|
Standard application code. |
|
|
Wire memory into a Vercel AI SDK |
|
|
The 12-tool memory surface as JSON Schema plus a dispatcher, for the low-level MCP |
|
|
Register the same 12 tools on a high-level |
|
|
LangChain JS — duck-typed against |
|
|
A thin thread-and-message-history adapter in Mastra’s vocabulary — not a Mastra |
|
|
AWS Strands Agents SDK (JS). Requires the optional |
|
|
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 module index.
Related package: @neo4j-labs/nams-ai-provider
is a separate npm package, not a subpath of this one, that wraps this SDK for
the Vercel AI SDK with additional retrieval and persistence policies —
cross-session search, graph expansion, explicit memory tools, and lifecycle
hooks across four selectable modes. See
its API reference.
Observability
The logger constructor option receives typed `LogEvent`s for supported HTTP calls. Pre-request validation and some raw failures have no complete event pair:
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 |
|---|---|
|
|
|
|
|
|
See enable request logging for the full pattern including OpenTelemetry forwarding.
Versioning
The SDK has its own package version; NAMS itself is continuously shipped and
/v1 is the service API path. The current release is 0.5.0 (2026-09-22).
Release tags are namespaced per package: typescript-v<X.Y.Z> publishes
@neo4j-labs/agent-memory itself, separately from Python’s python-v* tags;
nams-ai-provider-v<X.Y.Z> publishes the separate
@neo4j-labs/nams-ai-provider package. The source manifest and
changelog
record repository development; an [Unreleased] entry does not prove an npm
release — verify the installed package before treating it as shipped. This
Neo4j Labs project provides no backward-compatibility or
scheduled-deprecation guarantee.
See also
-
TypeScript SDK landing page — install + quickstart
-
NAMS REST API — the wire-level contract the SDK implements
-
Cross-Agent Memory Sharing — how this SDK interoperates with the Python SDK
-
TypeDoc — method-level reference
-
Source on GitHub —
typescript/src/