Skip to content

TypeScript

The xmemory npm package is a lightweight TypeScript client for the xmemory API. Zero dependencies — it uses native fetch only.

For MCP-based integration, see the MCP guide. For framework-specific setup, see Mastra AI.

API key: To use xmemory APIs or integrations, you need an API key. Please register your interest at https://xmemory.ai and we will reach out to give access. Copy and securely store the key. Never share your API key publicly.


Terminal window
npm install xmemory

import { xmemoryInstance, SchemaType } from "xmemory";
// Connect (reads XMEM_API_URL and XMEM_AUTH_TOKEN from env)
const mem = await xmemoryInstance({ token: "your-token" });
// Create a memory instance
await mem.createInstance(schemaYml, SchemaType.YML);
// The instanceId is saved on the client automatically.
// Write some information
await mem.write("Alice Johnson works at Acme Corp. Her email is alice@acme.com.");
await mem.write("Bob Lee is a designer at Globex. He joined last Monday.");
// Read it back
const result = await mem.read("What is Alice's email?");
console.log(result.reader_result?.answer);
// → "alice@acme.com"

Once you have an instanceId, skip instance creation on subsequent runs:

const mem = await xmemoryInstance({ token: "your-token" });
mem.instanceId = "your-saved-instance-id";

Three options, depending on whether you want a health check:

import { XmemoryClient, xmemoryInstance } from "xmemory";
// Factory function — runs a health check automatically
const mem = await xmemoryInstance({ url: "https://api.xmemory.ai", token: "..." });
// Static method — same behavior
const mem = await XmemoryClient.create({ url: "https://api.xmemory.ai", token: "..." });
// Constructor — no health check, no env var resolution
const mem = new XmemoryClient({ url: "https://api.xmemory.ai", token: "..." });
OptionEnv varDefaultDescription
tokenXMEM_AUTH_TOKENundefinedBearer token for authentication
urlXMEM_API_URLhttp://0.0.0.0:8000API base URL
timeoutMs60000Default request timeout in milliseconds

Environment variables are resolved by xmemoryInstance() and XmemoryClient.create(). The plain constructor does not read env vars.


Send free-form text — xmemory extracts structured objects according to your schema and merges them into the knowledge graph.

const resp = await mem.write("Carol is a senior engineer at Initech.");
console.log(resp.status); // "ok" or "error"

Control the speed/accuracy tradeoff:

await mem.write("...", { extractionLogic: "fast" });
ValueWhen to use
"deep"Important or complex information (default)
"regular"Balanced speed and accuracy
"fast"High-volume, low-stakes writes

For latency-sensitive code, enqueue a write and return immediately:

const { write_id } = await mem.writeAsync("Dave manages the London office.");
console.log(write_id); // use this to poll for completion

Then check the status:

const status = await mem.writeStatus(write_id);
console.log(status.write_status);
// → "queued" | "processing" | "completed" | "failed" | "not_found"

Do not call read immediately after writeAsync — the data may not be committed yet. Poll with writeStatus until "completed", or use write (synchronous) when you need to read right after.


Ask questions in natural language:

const resp = await mem.read("Who works at Acme Corp?");
console.log(resp.reader_result?.answer);

All errors throw XmemoryAPIError with an optional .status property containing the HTTP status code.

import { XmemoryAPIError } from "xmemory";
try {
await mem.write("...");
} catch (e) {
if (e instanceof XmemoryAPIError) {
console.error(`Error (HTTP ${e.status}): ${e.message}`);
}
}

All methods are async and return Promises.

MethodReturnsDescription
createInstance(schemaText, schemaType, timeoutMs?)Promise<boolean>Create a new instance; auto-saves instanceId on success
write(text, options?)Promise<WriteResponse>Extract and persist objects from text
writeAsync(text, options?)Promise<AsyncWriteResponse>Enqueue a write; returns write_id immediately
writeStatus(writeId, options?)Promise<WriteStatusResponse>Poll the status of an async write
read(query, options?)Promise<ReadResponse>Query the instance in natural language
type ExtractionLogic = "fast" | "regular" | "deep";
type WriteQueueStatus = "queued" | "processing" | "completed" | "failed" | "not_found";
const SchemaType = { YML: 0, JSON: 1 } as const;