> ## Documentation Index
> Fetch the complete documentation index at: https://docs.memcontext.in/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Install and use the official MemContext TypeScript SDK.

`memcontext-sdk` is the official TypeScript SDK for the MemContext public API. It is a small typed wrapper around the REST API with API key auth, scope/project helpers, typed responses, and normalized API errors.

## Install

```bash theme={null}
npm install memcontext-sdk
```

## Quickstart

```typescript theme={null}
import { MemContextClient } from "memcontext-sdk";

const client = new MemContextClient({
  apiKey: process.env.MEMCONTEXT_API_KEY!,
});

const userMemory = client.withScope("user_123");
const projectMemory = userMemory.withProject("memcontext");

await projectMemory.save({
  content: "User prefers concise release notes",
  category: "preference",
});

const results = await projectMemory.search({
  query: "How should release notes be written?",
});
```

Use `withScope()` for the hard end-user or tenant boundary. Use `withProject()` only as a grouping filter inside that scope.

## Client Setup

```typescript theme={null}
const client = new MemContextClient({
  apiKey: process.env.MEMCONTEXT_API_KEY!,
  baseUrl: "https://api.memcontext.in",
  scope: "user_123",
  project: "memcontext",
});
```

| Option    | Required | Description                                               |
| --------- | -------- | --------------------------------------------------------- |
| `apiKey`  | Yes      | MemContext API key from the dashboard.                    |
| `baseUrl` | No       | API base URL. Defaults to `https://api.memcontext.in`.    |
| `scope`   | No       | Default hard isolation boundary for this client instance. |
| `project` | No       | Default project grouping inside the selected scope.       |
| `fetch`   | No       | Custom fetch implementation for tests or custom runtimes. |

## Scope Helpers

### `withScope(scope)`

Creates a new client with a default `scope`. Use this when one API key serves multiple app users, workspaces, organizations, or tenants.

```typescript theme={null}
const userMemory = client.withScope("user_123");
```

### `withProject(project)`

Creates a new client with a default `project`. Projects are soft grouping filters inside the current scope.

```typescript theme={null}
const projectMemory = userMemory.withProject("memcontext");
```

## Methods

### `save(request, options?)`

Saves durable memory. MemContext automatically handles embeddings, deduplication, relationship classification, and versioning. Larger notes may be accepted for asynchronous extraction into atomic memories.

```typescript theme={null}
await client.save({
  content: "User prefers TypeScript over JavaScript",
  category: "preference",
  scope: "user_123",
  project: "memcontext",
});
```

Returns a save result with `status` set to `saved`, `updated`, `extended`, `duplicate`, or `accepted`.

When `status` is `accepted`, the response includes a `jobId` and message for tracking extraction into atomic memories.

### `search(request)`

Searches memories using hybrid retrieval. Use full natural-language questions for best results.

```typescript theme={null}
const results = await client.search({
  query: "What language does the user prefer?",
  limit: 5,
  threshold: 0.6,
});
```

Returns `{ found, memories }`, where each memory includes content, category, scope, project, relevance, and `createdAt` as a `Date`.

### `list(request?)`

Lists current non-deleted memories with pagination and filters.

```typescript theme={null}
const page = await client.list({
  limit: 20,
  offset: 0,
  category: "fact",
  search: "release notes",
});
```

Returns `{ memories, total, hasMore }`.

### `get(memoryId, options?)`

Fetches one memory by ID. Pass `scope` when retrieving scoped memories from a base client.

```typescript theme={null}
const memory = await client.get("memory-id", {
  scope: "user_123",
});
```

### `update(memoryId, request, options?)`

Updates memory content, category, or project. Content updates may create relations or supersede related memories.

```typescript theme={null}
await client.update(
  "memory-id",
  { content: "User now prefers concise changelogs" },
  { scope: "user_123" },
);
```

### `delete(memoryId, options?)`

Removes a memory from future search and list results.

```typescript theme={null}
await client.delete("memory-id", {
  scope: "user_123",
});
```

### `forget(memoryId, options?)`

Endpoint-parity alias for `delete()`. Prefer `delete()` unless you specifically
want the `/forget` response shape.

```typescript theme={null}
await client.forget("memory-id", {
  scope: "user_123",
});
```

### `feedback(memoryId, request, options?)`

Records retrieval quality feedback. Feedback helps improve future ranking.

```typescript theme={null}
await client.feedback(
  "memory-id",
  {
    type: "helpful",
    context: "This memory answered the user's question directly.",
  },
  { scope: "user_123" },
);
```

Feedback `type` can be `helpful`, `not_helpful`, `outdated`, or `wrong`.

### `history(memoryId, options?)`

Returns the current memory and previous versions in its version chain.

```typescript theme={null}
const history = await client.history("memory-id", {
  scope: "user_123",
});
```

### `profile(options?)`

Returns pre-aggregated profile context split into stable and recent memory.

```typescript theme={null}
const profile = await client.profile({
  scope: "user_123",
  project: "memcontext",
});
```

Returns `{ static, dynamic }`.

### `graph(options?)`

Returns graph visualization data for memories in the selected scope.

```typescript theme={null}
const graph = await client.graph({
  scope: "user_123",
});
```

Returns `{ nodes, links, meta }`.

### `health(signal?)`

Checks API health.

```typescript theme={null}
const health = await client.health();
```

## Workspace Methods

Context Vault uses workspaces for shared knowledge. These methods require an API
key or dashboard session that belongs to the user.

### `listWorkspaces()`

Lists workspaces the current user belongs to.

```typescript theme={null}
const { workspaces } = await client.listWorkspaces();
```

### `createWorkspace(request)`

Creates a workspace and assigns the current user as owner.

```typescript theme={null}
const { workspace } = await client.createWorkspace({
  name: "Acme Support",
});
```

### `inviteWorkspaceMember(workspaceId, request)`

Sends an email invitation for another workspace member. Roles can be `admin`,
`member`, or `viewer`. The user is added only after accepting the invite.

```typescript theme={null}
const invite = await client.inviteWorkspaceMember(workspace.id, {
  email: "teammate@example.com",
  role: "member",
});
```

### `listWorkspaceTeam(workspaceId)`

Lists current members and pending invitations.

```typescript theme={null}
const team = await client.listWorkspaceTeam(workspace.id);
```

### `updateWorkspaceMember(workspaceId, memberId, request)`

Updates a member role. Owners cannot be changed through this method.

```typescript theme={null}
await client.updateWorkspaceMember(workspace.id, memberId, {
  role: "viewer",
});
```

### `removeWorkspaceMember(workspaceId, memberId)`

Removes a non-owner member from the workspace.

```typescript theme={null}
await client.removeWorkspaceMember(workspace.id, memberId);
```

### `revokeWorkspaceInvitation(workspaceId, invitationId)`

Revokes a pending invitation before it is accepted.

```typescript theme={null}
await client.revokeWorkspaceInvitation(workspace.id, invitationId);
```

### `acceptWorkspaceInvitation(request)`

Accepts a workspace invitation token.

```typescript theme={null}
await client.acceptWorkspaceInvitation({
  token: "invitation-token",
});
```

## Context Vault Methods

Context Vault methods let you add documents, list processing status, search
workspace knowledge, and collect feedback from your app.

### `ingestContextVaultDocument(request, options?)`

Adds extracted text, a public file URL, or a documentation URL to a workspace.

```typescript theme={null}
await client.ingestContextVaultDocument({
  workspaceId: workspace.id,
  title: "Product docs",
  uri: "https://docs.example.com",
  sourceType: "url",
  crawlSubpages: true,
  priorityPageLimit: 15,
  subpageTarget: ["api", "guides"],
});
```

For docs sites with `llms.txt`, MemContext uses the page map and ingests only
the top-priority pages. `priorityPageLimit` defaults to `15` and is capped at
`25`.

For public file URLs, pass the file type so the document can be parsed correctly:

```typescript theme={null}
await client.ingestContextVaultDocument({
  workspaceId: workspace.id,
  title: "Security report",
  uri: "https://example.com/security-report.pdf",
  sourceType: "pdf",
});
```

### `uploadContextVaultDocument(request, options?)`

Uploads a local file and adds it to Context Vault.

```typescript theme={null}
await client.uploadContextVaultDocument({
  workspaceId: workspace.id,
  title: "Employee handbook",
  file,
  filename: "handbook.pdf",
  sourceType: "pdf",
});
```

### `listContextVaultDocuments(workspaceId, options?)`

Lists workspace documents and their current status.

```typescript theme={null}
const docs = await client.listContextVaultDocuments(workspace.id);
```

### `cancelContextVaultDocument(documentId, options?)`

Stops a pending, retrying, or active document job.

```typescript theme={null}
await client.cancelContextVaultDocument("document-id");
```

### `deleteContextVaultDocument(documentId, options?)`

Deletes the document, chunks, citations, and any extracted memories that are
only backed by that document.

```typescript theme={null}
await client.deleteContextVaultDocument("document-id");
```

### `createContextVaultMemory(request, options?)`

Adds a curated company fact to a workspace. Use this for important company
context that is not documented yet.

```typescript theme={null}
await client.createContextVaultMemory({
  workspaceId: workspace.id,
  content: "Refund discounts are not offered after the trial period ends.",
  scope: "billing",
  project: "pricing",
  category: "fact",
});
```

### `deleteContextVaultMemory(workspaceId, memoryId, options?)`

Deletes a curated company fact from a workspace. Document-extracted memories are
removed by deleting their source document when they are not backed by any other
document.

```typescript theme={null}
await client.deleteContextVaultMemory(workspace.id, "memory-id");
```

### `searchContextVault(request, options?)`

Searches workspace knowledge in `documents`, `memories`, or `hybrid` mode.

```typescript theme={null}
const results = await client.searchContextVault({
  workspaceId: workspace.id,
  query: "How do refunds work?",
  mode: "hybrid",
  limit: 8,
});

// Source passages from files/docs.
console.log(results.chunks);

// Extracted atomic facts and curated company facts.
console.log(results.memories);
```

Hybrid mode keeps `chunks[]` and `memories[]` separate. For answer generation,
pass `chunks[]` as source document context and convert `memories[]` into a
second memory-context document. Curated company facts use
`memoryType: "company"` and may return with `evidence: []`.

### `listContextVaultMemories(request, options?)`

Browses extracted workspace memories.

```typescript theme={null}
const page = await client.listContextVaultMemories({
  workspaceId: workspace.id,
  limit: 20,
  search: "refund",
});
```

### `listContextVaultDocumentMemories(workspaceId, documentId, options?)`

Lists memories extracted from one document.

```typescript theme={null}
const extracted = await client.listContextVaultDocumentMemories(
  workspace.id,
  "document-id",
);
```

### `submitContextVaultMemoryFeedback(memoryId, request, options?)`

Records feedback on an extracted workspace memory.

```typescript theme={null}
await client.submitContextVaultMemoryFeedback("memory-id", {
  workspaceId: workspace.id,
  type: "helpful",
});
```

### `listContextVaultMemoryEvidence(workspaceId, memoryId, options?)`

Loads source chunks for an extracted memory.

```typescript theme={null}
const evidence = await client.listContextVaultMemoryEvidence(
  workspace.id,
  "memory-id",
);
```

### `getContextVaultHierarchy(workspaceId, options?)`

Returns scope/project counts for workspace memories.

```typescript theme={null}
const hierarchy = await client.getContextVaultHierarchy(workspace.id);
```

## Error Handling

Failed API responses throw `MemContextApiError`.

```typescript theme={null}
import { MemContextApiError } from "memcontext-sdk";

try {
  await client.get("missing-id");
} catch (error) {
  if (error instanceof MemContextApiError) {
    console.error(error.status, error.code, error.message);
  }
}
```

## Links

* Website: [memcontext.in](https://memcontext.in)
* Official docs: [docs.memcontext.in](https://docs.memcontext.in)
* API reference: [REST API](/api-reference/overview)
