TypeScript SDK
Learn how to install and configure the TraceMem TypeScript SDK to enable decision tracking and traceability within your AI agents and automation systems.
Overview
The @tracemem/ts-sdk package provides a powerful interface to TraceMem's API, enabling you to:
- Track decisions made by your AI agents or automation scripts
- Automatically map actions to standardized intents for consistent decision tracking
- Add context to decisions with safe, sanitized logs
- Evaluate policies against your decision context
- Protect sensitive data with automatic secret redaction and sanitization
This SDK is designed for TypeScript and Node.js environments, making it ideal for backend services, CLI tools, and AI agent implementations.
Prerequisites
Before installing the SDK, ensure you have:
- Node.js - Version 18.0.0 or higher
- A TraceMem account - Sign up at app.tracemem.com
- An Agent API key - Generate one from your TraceMem project settings
Installation
Install the SDK using npm:
npm install @tracemem/ts-sdk
Configuration
Basic Configuration
The SDK requires only an API key to get started. You can pass it directly to the constructor:
import { TraceMemClient } from '@tracemem/ts-sdk';
const client = new TraceMemClient({
apiKey: process.env.TRACEMEM_API_KEY!,
});
Advanced Configuration
You can customize the client behavior with additional options:
const client = new TraceMemClient({
apiKey: process.env.TRACEMEM_API_KEY!,
mcpUrl: 'https://mcp.tracemem.com', // Custom MCP URL
timeoutMs: 30000, // Request timeout in ms (default: 30000)
sanitize: true, // Enable/disable data sanitization (default: true)
defaultActor: 'my-agent', // Default actor for decisions
defaultAutomationMode: 'propose', // Default mode for decisions
});
Recommended Workflow
The SDK provides a fluent API for managing the decision lifecycle. Here's a typical pattern:
1. Open a Decision
Start by opening a decision envelope. You can use a high-level action (like 'refactor') which automatically maps to a TraceMem intent:
const decision = await client.open('refactor', {
automationMode: 'propose',
});
2. Add Context
Document the decision-making process by adding notes and context:
await decision.note({
kind: 'info',
message: 'Starting refactoring work',
data: { file: 'user.ts' }
});
3. Read Decision Data
Retrieve necessary context from data products:
const context = await decision.read('pg_customers_v1', 'order_validation', {
query: { customer_id: '123' }
});
4. Evaluate Policies
Check if your proposed actions comply with defined policies:
const evaluation = await decision.evaluate('discount_policy', {
inputs: { discount: 0.15 }
});
5. Request Approval (if needed)
If an evaluation fails or policy dictates, request human approval:
if (evaluation.requiresApproval) {
await decision.requestApproval({
kind: 'policy_override',
message: 'Requesting exception for discount'
});
}
6. Write Changes
Record mutations or changes:
await decision.write('pg_orders_v1', 'create_order', {
operation: 'insert',
records: [...]
});
7. Close the Decision
Complete the lifecycle by closing the decision with an outcome:
await decision.close({
outcome: 'commit',
reason: 'Refactoring completed successfully',
});
Auto-Intent Mapping
The client.open() method automatically maps common actions to standardized TraceMem intents, simplifying your code:
| Action | Intent |
|---|---|
edit_files | code.change.apply |
refactor | code.refactor.execute |
run_command | ops.command.execute |
deploy | deploy.release.execute |
secrets | secrets.change.propose |
db_change | data.change.apply |
review | code.review.assist |
If you provide an action not in this list, it will be used as-is.
Available Methods
The SDK provides methods organized by the objects they belong to:
Client Methods (client.*)
open(action, options)- Open a new decision with automatic intent mappingcreateDecision(intent, options)- Create a new decision with a specific intentproducts.list(filter?)- List available data productsproducts.get(name)- Get details for a specific data product
Decision Methods (decision.*)
These methods are available on the decision object returned by open() or createDecision():
note(note)- Add a context note to the decisionread(product, purpose, options)- Read from a data productevaluate(policy, options)- Evaluate a policy against inputsrequestApproval(request)- Request human approvalwrite(product, creation, mutation, options)- Write data/mutationstrace()- Retrieve the full trace of the decisionreceipt()- Get a summary receipt of the decisionclose(outcome)- Close the decision
Security
Secret Redaction
By default, the SDK automatically sanitizes all data sent to TraceMem. This includes:
- Redacting Secrets: Keys matching
password,key,token,secret,auth, etc., have their values replaced with[redacted]. - Truncating Data: Large strings (>1000 chars), arrays (>100 items), and deep objects (>10 levels) are truncated to prevent payload bloat.
To disable this (not recommended): set sanitize: false in the client constructor.
Example Workflow
Here is a complete example of a refactoring workflow:
import { TraceMemClient } from '@tracemem/ts-sdk';
async function runRefactor() {
const client = new TraceMemClient({
apiKey: process.env.TRACEMEM_API_KEY!
});
// 1. Open decision
const decision = await client.open('refactor', {
automationMode: 'propose',
metadata: { file: 'src/utils.ts' }
});
try {
// 2. Add context
await decision.note({
kind: 'info',
message: 'Analyzing dependency graph'
});
// 3. Perform work (simulated)
// ... analyzing code ...
// 4. Record the outcome
await decision.close({
outcome: 'commit',
reason: 'Extracted helpers to shared module'
});
console.log(`Decision ${decision.decisionId} completed.`);
} catch (error) {
// Handle errors (network, validation, etc.)
console.error('Decision failed:', error);
// Attempt to close as aborted if possible
await decision.close({
outcome: 'abort',
reason: error.message
}).catch(console.error);
}
}
Error Handling
The SDK exports typed error classes for precise error handling:
TraceMemError: Base class for all SDK errorsTraceMemNetworkError: Connectivity issuesTraceMemValidationError: Invalid inputs or parametersTraceMemTimeoutError: Request timeout
import { TraceMemNetworkError } from '@tracemem/ts-sdk';
try {
await client.open('refactor');
} catch (err) {
if (err instanceof TraceMemNetworkError) {
console.log('Check your internet connection');
}
}