npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@onshoreoutsourcing/ai-traceability-sdk

v1.1.0

Published

AI Traceability TypeScript SDK for comprehensive activity tracking and MCP integration

Readme

AI Traceability TypeScript SDK

TypeScript SDK for comprehensive AI activity tracking with full feature parity to the Python SDK.

Features

  • Complete Type Safety - Full TypeScript type definitions
  • Async/Promise Support - Native async/await patterns
  • Automatic Batching - Configurable batch processing
  • Retry Logic - Exponential backoff with configurable retries
  • Session Management - Context managers for activity grouping
  • Complete Tool Call Tracking - All 25+ fields supported
  • File Tracking & Security - Epic 4 file operation monitoring
  • MCP Integration - Claude/Cursor IDE support
  • Browser & Node.js - Isomorphic JavaScript support
  • Error Handling - Comprehensive error types and handling

Installation

npm install @onshoreoutsourcing/ai-traceability-sdk

Quick Start

import { AITraceabilityClient } from '@onshoreoutsourcing/ai-traceability-sdk';

// Initialize client
const client = new AITraceabilityClient({
  apiKey: 'your-api-key',
  serviceUrl: 'https://api.ai-traceability.com'
});

// Use with session context
await client.withSession({
  agentType: 'my-agent',
  userId: 'user123'
}, async (session) => {
  // Log a chat message
  await session.logChat('user', 'Hello, how can I help?');
  
  // Log tool usage with complete tracking
  await session.logToolCall({
    toolName: 'web_search',
    toolCategory: 'research',
    requestParams: { query: 'AI news' },
    responseData: { results: ['...'] },
    durationMs: 150,
    estimatedCostCents: 5,
    mcpServerName: 'my-mcp-server',
    status: 'completed'
  });
  
  // Log AI decision
  await session.logDecision({
    name: 'search_strategy',
    reasoningSteps: [
      'Analyzed user query',
      'Selected web search tool',
      'Formatted search parameters'
    ],
    confidenceScore: 0.9,
    selectedOption: { strategy: 'web_search' },
    alternativesConsidered: [
      { strategy: 'knowledge_base' },
      { strategy: 'direct_answer' }
    ]
  });
});

// Close client
await client.close();

Advanced Usage

Manual Session Management

const session = client.createSession({
  agentType: 'my-agent',
  sessionId: 'custom-session-123'
});

await session.start();

try {
  await session.logActivity('processing', {
    content: 'Processing user request',
    metadata: { requestId: '123' }
  });
  
  // ... more activities
} finally {
  await session.end();
}

Complete Tool Call Tracking

await client.logToolCall('session-id', {
  // Core fields
  toolName: 'database_query',
  toolCategory: 'data',
  toolVersion: '2.1.0',
  
  // MCP server fields
  mcpServerName: 'claude-desktop',
  mcpServerVersion: '1.5.0',
  
  // Request/Response
  requestParams: { table: 'users', filters: {} },
  responseData: { count: 150, rows: [] },
  
  // Performance tracking
  startTime: new Date('2024-01-01T10:00:00Z'),
  endTime: new Date('2024-01-01T10:00:00.150Z'),
  durationMs: 150,
  cpuMs: 45,
  memoryMb: 12,
  networkBytes: 2048,
  
  // Cost tracking
  estimatedCostCents: 3,
  billingModel: 'per-query',
  rateLimitConsumed: 1,
  
  // Status
  status: 'completed',
  retryCount: 0,
  
  // Data classification
  dataClassification: 'internal',
  containsPii: true,
  
  // Tracing
  correlationId: 'req-123',
  traceId: 'trace-456',
  
  // Context
  userAgent: 'MyApp/1.0',
  sourceLocation: 'handlers/user.ts:45',
  additionalMetadata: {
    queryComplexity: 'simple',
    cacheHit: false
  }
});

Configuration Options

const client = new AITraceabilityClient({
  apiKey: 'your-api-key',
  serviceUrl: 'https://api.ai-traceability.com',
  
  // Timeout configuration
  timeout: 30000, // 30 seconds
  
  // Retry configuration
  retryAttempts: 3,
  retryDelay: 1000, // 1 second base delay
  
  // Batching configuration
  batchSize: 100,
  batchTimeout: 5000, // 5 seconds
  autoFlush: true,
  
  // Debug mode
  debug: true,
  
  // SSL verification
  verifySSL: true
});

File Tracking & Security Analysis

The SDK provides comprehensive file operation tracking and security analysis capabilities:

import { 
  FileOperationType,
  FileOperationData,
  SecurityAnalysisData 
} from '@onshoreoutsourcing/ai-traceability-sdk';

// Track basic file operations
await client.logFileRead('session-id', {
  filePath: '/app/data/config.json',
  fileSize: 1024,
  partialRead: false,
  userId: '[email protected]',
  projectId: 'project-123'
});

await client.logFileWrite('session-id', {
  filePath: '/app/output/results.json',
  contentSize: 2048,
  operationType: 'write',
  contentHashBefore: 'abc123',
  contentHashAfter: 'def456',
  userId: '[email protected]',
  projectId: 'project-123'
});

// Track file moves and copies
await client.logFileMove('session-id', {
  sourcePath: '/old/location.txt',
  destinationPath: '/new/location.txt',
  fileSize: 1536,
  userId: '[email protected]'
});

// Security analysis
const securityResult = await client.analyzeFileSecurity('session-id', {
  filePath: '/suspicious/script.sh',
  operation: FileOperationType.WRITE,
  content: '#!/bin/bash\nrm -rf /',
  fileSize: 1024
});

console.log(`Risk Score: ${securityResult.riskScore}`);
console.log(`Threats: ${securityResult.threats.join(', ')}`);

// Anomaly detection
const anomalies = await client.detectFileAnomalies('session-id', {
  sessionId: 'session-id',
  timeWindowMinutes: 60
});

// Risk scoring
const riskScore = await client.calculateFileRiskScore('session-id', {
  filePath: '/system/critical.exe',
  operation: FileOperationType.DELETE,
  isSensitive: true,
  isExecutable: true,
  isSystem: true
});

// Batch file operations
await client.logFileOperationsBatch('session-id', [
  {
    operationType: FileOperationType.READ,
    sessionId: 'session-id',
    filePath: '/batch/file1.txt',
    fileSize: 1024
  },
  {
    operationType: FileOperationType.WRITE,
    sessionId: 'session-id', 
    filePath: '/batch/file2.txt',
    contentSize: 2048
  }
]);

Error Handling

import {
  AuthenticationError,
  RateLimitError,
  ValidationError,
  NetworkError,
  TimeoutError,
  ServerError
} from '@onshoreoutsourcing/ai-traceability-sdk';

try {
  await client.logActivity('session', 'chat', { content: 'test' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after: ${error.retryAfter} seconds`);
  } else if (error instanceof ValidationError) {
    console.error('Invalid request data');
  } else if (error instanceof NetworkError) {
    console.error('Network connectivity issue');
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out');
  } else if (error instanceof ServerError) {
    console.error(`Server error: ${error.statusCode}`);
  }
}

Browser Support

The SDK works in both Node.js and browser environments:

<script type="module">
import { AITraceabilityClient } from '@onshoreoutsourcing/ai-traceability-sdk';

const client = new AITraceabilityClient({
  apiKey: 'your-api-key'
});

// Use as normal...
</script>

Testing

# Run tests
npm test

# Run with coverage
npm run test:coverage

# Watch mode
npm run test:watch

Building

# Build TypeScript
npm run build

# Development watch mode
npm run dev

API Reference

Client Methods

Core Activity Tracking

  • logActivity(sessionId, activityType, data, activitySubtype?, durationMs?, tokenCount?) - Log an activity
  • logToolCall(sessionId, toolCall) - Log tool usage with complete schema
  • logDecision(sessionId, decision) - Log AI decision with reasoning

File Tracking & Security (Epic 4)

  • logFileRead(sessionId, operationData) - Track file read operations
  • logFileWrite(sessionId, operationData) - Track file write operations
  • logFileDelete(sessionId, operationData) - Track file deletion operations
  • logFileMove(sessionId, operationData) - Track file move/rename operations
  • logFileCopy(sessionId, operationData) - Track file copy operations
  • analyzeFileSecurity(sessionId, analysisData) - Perform comprehensive security analysis
  • detectFileAnomalies(sessionId, detectionData) - Detect anomalous file access patterns
  • calculateFileRiskScore(sessionId, riskData) - Calculate comprehensive risk scores
  • logFileOperationsBatch(sessionId, operations) - Process multiple file operations in batch

Session & Batch Management

  • flush() - Manually flush batch queue
  • withSession(config, callback) - Execute callback with session context
  • createSession(config) - Create manual session
  • getStats() - Get client statistics
  • close() - Close client and cleanup

Session Methods

  • start() - Start the session
  • end() - End the session
  • logActivity(type, data, ...) - Log activity in session
  • logToolCall(toolCall) - Log tool call in session
  • logDecision(decision) - Log decision in session
  • logChat(role, content, metadata?) - Convenience method for chat
  • getSessionId() - Get session ID
  • isActive() - Check if session is active

Error Types

  • TraceabilityClientError - Base error class
  • AuthenticationError - Invalid API key
  • RateLimitError - Rate limit exceeded
  • ValidationError - Invalid request data
  • NetworkError - Network connectivity issues
  • TimeoutError - Request timeout
  • ServerError - Server-side errors

License

MIT