How to Use Header Overrides for MemoryCore Context
MemoryCore extracts execution context identifiers from HTTP headers (x-tdai-*) when they are not present in the request body, allowing you to override context values at the HTTP layer without modifying the JSON payload.
The TencentDB-Agent-Memory repository implements a priority-based context resolution system that inspects the request body first, then falls back to specific HTTP headers for critical identifiers. This architecture enables API gateways, reverse proxies, and load balancers to inject tenant isolation, user authentication, and session management data without parsing or rewriting the request payload. Mastering MemoryCore header overrides is essential for production deployments requiring multi-tenant routing and centralized authentication.
How MemoryCore Resolves Context Identifiers
MemoryCore employs a cascading resolution strategy defined in the gateway layer. The resolveIsolation helper in MemoryCore/src/gateway/v2-schemas.ts (lines 369–382) checks for context fields within the JSON body. When a field is absent, the system immediately inspects the incoming HTTP headers for a corresponding x-tdai-* value. This header fallback mechanism guarantees that infrastructure components can assert identity and routing information even when the upstream client cannot modify the request body.
The resolution order is strict: body values take precedence, but headers override when body fields are missing. This design ensures backward compatibility while supporting modern gateway patterns where headers carry trusted metadata injected by authentication proxies.
Supported Header Overrides
MemoryCore recognizes seven distinct headers for context construction and authentication:
x-tdai-team-id– Identifies the tenant or team namespace for isolationx-tdai-user-id– Specifies the end-user identifier for memory retrievalx-tdai-agent-id– Targets a specific AI agent instance within the teamx-tdai-session-id– Maintains conversation continuity across requestsx-tdai-task-id– Correlates related operations within a workflowx-tdai-user-key– Supplies the authentication credential (validated inauth.ts)x-tdai-service-id– Indicates the specific service instance (validated ininstance.ts)
When present, these headers override any defaults and are forwarded to downstream services for processing.
Gateway Implementation Details
Context Extraction in v2-schemas.ts
The core logic resides in MemoryCore/src/gateway/v2-schemas.ts within the resolveIsolation function (lines 369–382). This TypeScript implementation parses the incoming request, first extracting identifiers from the parsed JSON payload. If the payload lacks a teamId, userId, agentId, sessionId, or taskId, the function searches the header object for the corresponding x-tdai-* header. The extracted values are then normalized and passed to the execution context builder.
Request Routing in v2-router.ts
After extraction, MemoryCore/src/gateway/v2-router.ts (lines 140–150) routes the request to the appropriate handler. The router ensures that the resolved context—whether sourced from body or headers—is propagated consistently to the memory retrieval and storage layers. This guarantees that header-injected identifiers function identically to body-supplied values throughout the request lifecycle.
Authentication Header Resolution
Two additional files handle security-specific headers:
MemoryCore/src/metadata/router/auth.ts(lines 38–39): Validates thex-tdai-user-keyheader against registered API keysMemoryCore/src/metadata/router/instance.ts(lines 28–29): Extracts thex-tdai-service-idheader to route requests to specific service instances
These low-level helpers enable zero-trust architectures where authentication and service discovery occur entirely at the edge.
Practical Implementation Examples
cURL with Header Overrides
Send a chat request where the user and session are defined entirely via headers, leaving the body clean:
curl -X POST https://memory-core.mycompany.com/v2/chat \
-H "Content-Type: application/json" \
-H "x-tdai-user-id: 12345" \
-H "x-tdai-session-id: abcde-67890" \
-H "x-tdai-user-key: secret-key" \
-d '{"messages":[{"role":"user","content":"Hello!"}]}'
The x-tdai-user-id and x-tdai-session-id headers establish the execution context, while x-tdai-user-key handles authentication.
Node.js fetch Implementation
const response = await fetch('https://memory-core.mycompany.com/v2/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-tdai-team-id': 'team-42',
'x-tdai-user-id': 'user-99',
'x-tdai-agent-id': 'agent-7',
'x-tdai-session-id': 'sess-abc123',
},
body: JSON.stringify({
messages: [{ role: 'user', content: 'Explain header overrides.' }],
}),
});
const data = await response.json();
console.log(data);
This pattern is ideal for server-side middleware that injects tenant context after verifying JWT tokens.
Python requests Usage
import requests
headers = {
"Content-Type": "application/json",
"x-tdai-team-id": "team-42",
"x-tdai-user-id": "user-99",
"x-tdai-agent-id": "agent-7",
"x-tdai-session-id": "sess-abc123",
}
payload = {"messages": [{"role": "user", "content": "Hi"}]}
r = requests.post(
"https://memory-core.mycompany.com/v2/chat",
json=payload,
headers=headers,
)
print(r.json())
All three examples demonstrate how MemoryCore accepts context via HTTP headers, enabling clean separation between application logic and infrastructure concerns.
Summary
- Priority resolution: MemoryCore checks the request body first, then falls back to
x-tdai-*HTTP headers for missing identifiers - Seven override headers:
x-tdai-team-id,x-tdai-user-id,x-tdai-agent-id,x-tdai-session-id,x-tdai-task-id,x-tdai-user-key, andx-tdai-service-id - Gateway implementation: Context extraction occurs in
v2-schemas.ts(lines 369–382), routing inv2-router.ts(lines 140–150), and authentication inauth.tsandinstance.ts - Infrastructure-friendly: Header overrides allow API gateways and reverse proxies to manage multi-tenant contexts without modifying request payloads
Frequently Asked Questions
What happens if both the body and headers contain the same identifier?
MemoryCore prioritizes values present in the JSON request body. Headers act strictly as a fallback mechanism. If userId exists in the body, the x-tdai-user-id header is ignored for that specific field.
Which headers are required for authentication?
According to the source code in MemoryCore/src/metadata/router/auth.ts, the x-tdai-user-key header supplies the primary authentication credential. Additionally, x-tdai-service-id (handled in instance.ts) may be required for service-instance routing in multi-instance deployments.
Can header overrides be used with all MemoryCore API versions?
The provided source analysis covers the v2 gateway implementation (v2-schemas.ts and v2-router.ts). While the header override pattern is standard in modern versions, verify the specific schema version in MemoryCore/v3-api-memorycore-doc.md for the exact API contract you are targeting.
How does MemoryCore handle completely missing context identifiers?
If an identifier is absent from both the body and the corresponding x-tdai-* header, MemoryCore either applies a default value (if configured) or returns a validation error, depending on whether the field is required for the specific operation. The resolveIsolation function in v2-schemas.ts explicitly manages these fallback chains.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →