# How to Initialize the TypeScript MemoryClient for TencentDB Agent Memory

> Learn to initialize the TypeScript MemoryClient for TencentDB Agent Memory. Pass V3MemoryClientConfig with endpoint, API key, service ID, and isolation identifiers for seamless integration.

- Repository: [Tencent Cloud/TencentDB-Agent-Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory)
- Tags: how-to-guide
- Published: 2026-08-27

---

**Initialize the TypeScript MemoryClient by passing a `V3MemoryClientConfig` object containing your endpoint, API key, service ID, and isolation identifiers (`teamId`, `agentId`, `userId`) to the constructor, or provide a custom `Transport` implementation for advanced testing scenarios.**

The `MemoryClient` class in the TencentDB-Agent-Memory repository serves as the primary gateway to the TencentDB memory service v3 API. Instantiating this client establishes your authentication context, configures the HTTP transport layer, and enforces isolation boundaries required for team-based agent deployments.

## Construction Modes for MemoryClient

The `MemoryClient` class defined in [`sdk/memory-core/typescript/src/v3/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/client.ts) supports two distinct initialization patterns depending on your architectural needs.

### Config-Based Initialization (Typical Usage)

Use this approach for standard application code where you need to connect to the TencentDB memory service using endpoint credentials and isolation identifiers. The constructor accepts a `V3MemoryClientConfig` object (defined in [`sdk/memory-core/typescript/src/v3/types.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/types.ts)) containing your connection parameters.

Required parameters include:
- `endpoint`: The HTTPS endpoint for the memory service
- `apiKey`: Your authentication key for API access
- `serviceId`: Identifier for the memory service (typically `"memory"`)
- `teamId`: Non-empty string identifying your team scope
- `agentId`: Non-empty string identifying the specific agent
- `userId`: Non-empty string identifying the end user

Optional parameters include `sessionId`, `taskId`, `userKey`, `timeout`, and `rejectUnauthorized`.

During construction, the client validates that `teamId`, `agentId`, and `userId` are non-empty strings and creates an internal `IsolationContext`. It then instantiates a `V3HttpTransport` (implemented in [`sdk/memory-core/typescript/src/v3/http.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/http.ts)) to handle HTTP request construction and response parsing.

### Transport-Based Initialization (Advanced Use Cases)

For scenarios requiring custom HTTP handling—such as unit testing with mocked fetch implementations or proxying through corporate gateways—you can initialize `MemoryClient` with a pre-configured `Transport` instance and an explicit isolation context object.

This constructor accepts:
- A `Transport` implementation (typically `V3HttpTransport` or your custom wrapper)
- An isolation context object containing `team_id`, `agent_id`, `user_id`, and optional `session_id` and `task_id`

## Step-by-Step Initialization Examples

### Standard Configuration Pattern

```typescript
import { MemoryClient } from '@tencentcloud/memory-core/typescript';

// Initialize with configuration object
const client = new MemoryClient({
  endpoint: 'https://memory.tencentcloudapi.com',
  apiKey: process.env.TENCENT_API_KEY,    // Keep secrets out of source control
  serviceId: 'memory',
  teamId: 'team-123',
  agentId: 'agent-abc',
  userId: 'user-xyz',
  sessionId: 'session-001',               // Required for write operations
  timeout: 30000,                         // Optional: 30 second timeout
});

// Execute API methods
await client.addConversation({
  session_id: 'session-001',
  messages: [{ role: 'user', content: 'Hello' }],
});

```

### Custom Transport for Testing

```typescript
import { MemoryClient } from '@tencentcloud/memory-core/typescript';
import { V3HttpTransport } from '@tencentcloud/memory-core/typescript';

// Create transport pointing to local test server
const mockTransport = new V3HttpTransport({
  endpoint: 'http://localhost:3000',
  apiKey: 'test-api-key',
  serviceId: 'memory',
});

// Define explicit isolation context
const isolation = {
  team_id: 'team-123',
  agent_id: 'agent-abc',
  user_id: 'user-xyz',
};

// Initialize client with transport injection
const client = new MemoryClient(mockTransport, isolation);

// Query without session (read-only operation)
const conversations = await client.queryConversation({ limit: 10 });

```

### Asset-Level Operations

```typescript
// Clear specific memory assets using initialized client
await client.clearChatMemory({
  memory_ids: ['memory-001', 'memory-002'],
});

```

## Understanding IsolationContext Validation

When you initialize the TypeScript MemoryClient, the constructor enforces strict validation rules on the isolation context:

- **Required Identifiers**: `teamId`, `agentId`, and `userId` must be non-empty strings. The client throws a validation error if any are missing or empty.
- **Session Requirements**: While `sessionId` is optional during client initialization, it is **required** for write operations such as `addConversation`. Read-only operations like `queryConversation` can execute without a session identifier.
- **Scope Inheritance**: All subsequent method calls automatically merge the isolation context into the request payload, ensuring every API call carries the proper tenant boundaries.

## Configuration Parameters Reference

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `endpoint` | string | Yes | HTTPS URL for the TencentDB memory service API |
| `apiKey` | string | Yes | Authentication key for API access |
| `serviceId` | string | Yes | Service identifier (typically `"memory"`) |
| `teamId` | string | Yes | Team scope identifier (non-empty) |
| `agentId` | string | Yes | Agent scope identifier (non-empty) |
| `userId` | string | Yes | User scope identifier (non-empty) |
| `sessionId` | string | No | Conversation session identifier (required for writes) |
| `taskId` | string | No | Optional task identifier for grouping operations |
| `userKey` | string | No | Additional user-specific encryption key |
| `timeout` | number | No | Request timeout in milliseconds |
| `rejectUnauthorized` | boolean | No | Whether to reject invalid SSL certificates |

## Summary

- The `MemoryClient` class in [`sdk/memory-core/typescript/src/v3/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/client.ts) provides two initialization patterns: config-based for standard usage and transport-based for advanced scenarios.
- Required isolation parameters (`teamId`, `agentId`, `userId`) must be non-empty strings and are validated during construction.
- The client automatically creates a `V3HttpTransport` instance that handles HTTP request construction and injects authentication headers.
- `sessionId` is required for write operations like `addConversation` but optional for read-only queries.
- All API methods merge the internal `IsolationContext` into request payloads to enforce multi-tenant boundaries.

## Frequently Asked Questions

### What is the minimum configuration required to initialize the TypeScript MemoryClient?

You must provide the `endpoint`, `apiKey`, `serviceId`, and the three isolation identifiers: `teamId`, `agentId`, and `userId`. These parameters establish both the connection to TencentDB and the security context for your requests. According to the source code in [`sdk/memory-core/typescript/src/v3/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/client.ts), missing or empty isolation strings trigger validation errors immediately upon construction.

### Can I use the MemoryClient without a sessionId?

Yes, but only for read-only operations. When you initialize the client without a `sessionId`, you can still execute queries like `queryConversation` or `queryAtomic`. However, write operations such as `addConversation` require a valid `sessionId` in the isolation context. The source enforces this requirement during request payload construction in the transport layer.

### How do I test code that uses MemoryClient without hitting the live API?

Use transport-based initialization with a custom `V3HttpTransport` pointing to a local mock server. Import `V3HttpTransport` from [`sdk/memory-core/typescript/src/v3/http.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/http.ts), configure it with a localhost endpoint and test API key, then pass this transport instance along with your test isolation context to the `MemoryClient` constructor. This pattern allows you to intercept requests and return mock responses without modifying your application logic.

### Where are the TypeScript types for the configuration object defined?

The `V3MemoryClientConfig` interface and related type definitions reside in [`sdk/memory-core/typescript/src/v3/types.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/types.ts). This file contains the complete TypeScript definitions for all configuration options, request payloads, and response structures used by the `MemoryClient` class, enabling full type safety during initialization and method calls.