How to Query Atomic Memories by Type Using the TypeScript SDK

Use the MemoryClient.queryAtomic() method from the @tencentdb/memory-core package to filter atomic memories by passing a type string in the V3AtomicQueryRequest payload.

The TencentDB Agent Memory platform stores individual notes as atomic memories (L1 layer) tagged with arbitrary type strings for categorization. When building applications with the TypeScript SDK, you retrieve specific memory categories using the queryAtomic method, which sends a POST /v3/atomic/query request and automatically handles session isolation. This guide demonstrates the exact implementation details found in the TencentCloud/TencentDB-Agent-Memory repository.

Initializing the Client and Querying by Type

The MemoryClient class in sdk/memory-core/typescript/src/v3/client.ts provides the queryAtomic method as the primary entry point for retrieving filtered atomic memories. According to the source code at lines 79-88, the method accepts a V3AtomicQueryRequest object, automatically injects the current session_id for session isolation, and removes undefined fields before transmission.

To filter by type, populate the type field with your specific tag string:

import { MemoryClient, V3AtomicQueryRequest } from '@tencentdb/memory-core';

// Initialise the client – assumes you have set up credentials elsewhere.
const memClient = new MemoryClient({
  baseUrl: 'https://api.tencentyun.com',
  credential: { secretId: 'YOUR_ID', secretKey: 'YOUR_KEY' },
});

// Example: fetch the first 20 atomic memories of type "meeting-notes".
async function fetchMeetingNotes() {
  const query: V3AtomicQueryRequest = {
    type: 'meeting-notes',   // ← filter by atomic memory type
    limit: 20,               // pagination: max items per page
    offset: 0,               // start from the first result
  };

  const result = await memClient.queryAtomic(query);
  console.log('Total matches:', result.total);
  result.items.forEach(item => {
    console.log(`- ${item.id}: ${item.content}`);
  });
}

fetchMeetingNotes().catch(console.error);

Request Schema and Available Parameters

The request payload structure is defined in sdk/memory-core/typescript/src/v3/types.ts at lines 111-119. The V3AtomicQueryRequest interface includes:

  • type: The arbitrary string tag filtering criterion (e.g., "todo", "meeting-notes")
  • limit and offset: Pagination controls
  • time_start and time_end: Optional ISO 8601 timestamps for time-window filtering

Because the SDK is written in TypeScript, the interface provides compile-time safety for these parameters before the request reaches the transport layer.

Server-Side Validation and Routing

When the SDK transmits the request, the TencentDB Agent Memory gateway validates the payload using Zod schemas. The core gateway registers the endpoint in MemoryCore/src/gateway/v2-router.ts at line 159, while the strict validation schema resides in MemoryCore/src/gateway/generated/schemas.ts at line 131.

This validation ensures that malformed type strings or incorrect date formats are rejected before the database query executes, returning a typed error response that the SDK propagates back through the HttpTransport layer defined in http.ts.

Advanced Filtering with Time Windows

Combine the type filter with temporal constraints to retrieve recent memories. The following example queries for "todo" items created within the last seven days:

// Advanced: combine type filter with a time window (last 7 days)
import { subDays } from 'date-fns';

async function recentTodoItems() {
  const now = new Date();
  const weekAgo = subDays(now, 7);
  const query = {
    type: 'todo',
    time_start: weekAgo.toISOString(),
    time_end: now.toISOString(),
    limit: 50,
  };

  const { total, items } = await memClient.queryAtomic(query);
  console.log(`Found ${total} todo items from the past week.`);
}

The server returns a V3AtomicQueryData object containing the total count and the items array of matching atomic memories.

Summary

  • Use MemoryClient.queryAtomic() to execute filtered queries against the atomic memory layer.
  • Specify the type parameter in V3AtomicQueryRequest to categorize results by arbitrary string tags.
  • Leverage automatic session isolation—the SDK injects session_id in client.ts (lines 79-88) without manual configuration.
  • Combine filters by adding pagination (limit, offset) or time range (time_start, time_end) parameters defined in types.ts.
  • Trust server-side validation via Zod schemas in MemoryCore/src/gateway/generated/schemas.ts to enforce data integrity.

Frequently Asked Questions

What string values are valid for the type parameter?

The type field accepts any arbitrary string tag you define when creating atomic memories. Common examples include "todo", "meeting-notes", or custom application-specific identifiers. The server treats this as an exact match filter without predefined enum constraints.

Does the SDK automatically handle pagination for large result sets?

No, the SDK returns a single page of results based on the limit and offset values you provide in V3AtomicQueryRequest. You must implement client-side pagination logic by incrementing offset and making subsequent calls until you've retrieved the total count indicated in V3AtomicQueryData.

How does the SDK maintain session isolation during queries?

The queryAtomic implementation in sdk/memory-core/typescript/src/v3/client.ts automatically extracts the current session_id from the client's internal state and injects it into the request payload. This ensures that queries only return atomic memories belonging to the active user session without requiring manual session configuration.

What error response format does the SDK return for invalid type queries?

When the gateway validation fails—defined in MemoryCore/src/gateway/generated/schemas.ts—or the transport layer encounters network issues, the SDK throws standard JavaScript Error objects with descriptive messages. For schema validation failures specifically, the error includes details about which V3AtomicQueryRequest fields violated the Zod constraints, allowing precise debugging of malformed type strings or invalid date formats.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →