Documentation
Customization/Context Providers

Context Providers

Context providers are a fundamental component of ThinkCode's AI capabilities, supplying the AI with rich, structured information about your codebase, development environment, and work context. This guide explains how to create and optimize custom context providers to enhance ThinkCode's understanding of your specific development scenarios.

Understanding Context Providers

What is a Context Provider?

A context provider is a component that captures, processes, and delivers contextual information to ThinkCode's AI system. This context helps the AI make more informed decisions and provide more relevant assistance.

The Context System Architecture

ThinkCode uses a layered context system:

  1. Source Layer: Raw data from various sources (files, git, APIs, etc.)
  2. Processing Layer: Transforms raw data into structured information
  3. Delivery Layer: Packages and delivers context to the AI system
  4. Feedback Layer: Improves context quality based on usage

Types of Context

ThinkCode can utilize various types of context:

  • Code Context: Information about code structure, dependencies, and patterns
  • Project Context: Information about project configuration, architecture, and standards
  • Team Context: Information about team practices, conventions, and history
  • Domain Context: Information about the business domain and requirements
  • User Context: Information about the developer's preferences and work patterns

Creating a Custom Context Provider

Setting Up Your Environment

Before creating a custom context provider, ensure you have:

  • ThinkCode Enterprise or Professional Edition (v1.2+)
  • ThinkCode Extension Development Kit installed
  • A basic understanding of the ExMCP extension system

Basic Context Provider Structure

A context provider consists of three main components:

  1. Provider Definition: Metadata about the provider
  2. Context Extraction Logic: Code that extracts context from sources
  3. Context Transformation Logic: Code that formats context for the AI

Example: Simple File Pattern Provider

Here's an example of a context provider that identifies file patterns in your project:

import { ContextProvider, ContextType } from 'thinkcode-extension-api';
import * as fs from 'fs';
import * as path from 'path';
import * as glob from 'glob';
 
export class FilePatternProvider implements ContextProvider {
  id = 'custom.file.patterns';
  name = 'File Pattern Provider';
  
  async getContext(params: { workspacePath: string }): Promise<ContextType> {
    const { workspacePath } = params;
    
    // Find all files in the workspace
    const files = glob.sync('**/*', { 
      cwd: workspacePath, 
      nodir: true,
      ignore: ['**/node_modules/**', '**/.git/**']
    });
    
    // Analyze file patterns
    const extensions = new Map<string, number>();
    files.forEach(file => {
      const ext = path.extname(file);
      if (ext) {
        extensions.set(ext, (extensions.get(ext) || 0) + 1);
      }
    });
    
    // Create structured context
    return {
      type: 'project.filePatterns',
      data: {
        total: files.length,
        extensions: Object.fromEntries(extensions),
        timestamp: Date.now()
      },
      priority: 'medium'
    };
  }
}

Registering Your Context Provider

To register your context provider with ThinkCode, include it in your extension's activation function:

import { registerExtension } from 'thinkcode-extension-api';
import { FilePatternProvider } from './providers/file-pattern-provider';
 
export function activate(context: any) {
  // Register the extension with the new provider
  registerExtension({
    id: 'my.file.pattern.extension',
    name: 'File Pattern Extension',
    version: '1.0.0',
    providers: [new FilePatternProvider()]
  });
}

Advanced Context Provider Techniques

Real-time Context Updates

To provide real-time context updates:

import { ContextProvider, events } from 'thinkcode-extension-api';
 
export class LiveContextProvider implements ContextProvider {
  id = 'custom.live.context';
  name = 'Live Context Provider';
  
  constructor() {
    // Listen for file system changes
    events.on('workspace.fileChanged', this.onFileChanged.bind(this));
  }
  
  private onFileChanged(event: any) {
    // Update context when files change
    events.emit('context.updated', {
      providerId: this.id,
      changes: {
        // Updated context information
      }
    });
  }
  
  async getContext(params: any): Promise<any> {
    // Initial context
    return {
      type: 'custom.live',
      data: {
        // Live context data
      }
    };
  }
}

Context Caching

Improve performance with context caching:

export class CachedContextProvider implements ContextProvider {
  id = 'custom.cached';
  private cache: any = null;
  private lastUpdate: number = 0;
  private TTL = 60000; // 1 minute cache lifetime
  
  async getContext(params: any): Promise<any> {
    const now = Date.now();
    
    // Return cached data if still valid
    if (this.cache && (now - this.lastUpdate < this.TTL)) {
      return this.cache;
    }
    
    // Generate new context
    const newContext = {
      type: 'custom.cached',
      data: {
        // Expensive operation to generate context
        generatedAt: now
      }
    };
    
    // Update cache
    this.cache = newContext;
    this.lastUpdate = now;
    
    return newContext;
  }
}

Context Priorities and Weighting

Control how your context influences the AI system:

async getContext(params: any): Promise<any> {
  return {
    type: 'custom.weighted',
    data: {
      // Context data
    },
    metadata: {
      priority: 'high',      // 'low', 'medium', 'high'
      confidence: 0.95,      // 0.0 to 1.0
      relevance: {
        coding: 0.8,         // Relevance to coding tasks
        documentation: 0.3,  // Relevance to documentation tasks
        debugging: 0.9       // Relevance to debugging tasks
      }
    }
  };
}

Context Optimization

Performance Considerations

When developing context providers, consider:

  • Resource Usage: Minimize CPU and memory usage
  • Response Time: Keep context generation fast (< 100ms if possible)
  • Data Volume: Provide concise, relevant context rather than overwhelming detail
  • Asynchronous Processing: Use background processing for expensive operations

Context Quality Guidelines

High-quality context is:

  • Relevant: Directly applicable to the current development task
  • Timely: Current and up-to-date
  • Structured: Well-organized and easy for the AI to process
  • Concise: Focused on essential information
  • Accurate: Free from errors or misleading information

Testing Context Providers

ThinkCode provides tools for testing context providers:

  1. Context Inspector: View and analyze the context your provider generates

    • Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
    • Select "ThinkCode: Open Context Inspector"
    • Choose your provider from the list
  2. Context Simulation: Test how your context affects AI responses

    • Open the ThinkCode Developer Console
    • Use the simulateContext() function with your context data

Advanced Topics

Multi-source Context Integration

Combine data from multiple sources:

async getContext(params: any): Promise<any> {
  // Get code metrics
  const codeMetrics = await this.getCodeMetrics();
  
  // Get team information
  const teamInfo = await this.getTeamInfo();
  
  // Get project standards
  const standards = await this.getProjectStandards();
  
  // Integrate all sources
  return {
    type: 'integrated.context',
    data: {
      metrics: codeMetrics,
      team: teamInfo,
      standards: standards,
      correlations: this.findCorrelations(codeMetrics, teamInfo, standards)
    }
  };
}

Domain-Specific Context

Create context providers specialized for specific domains:

// Example for a web application context provider
export class WebAppContextProvider implements ContextProvider {
  id = 'domain.webapp';
  
  async getContext(params: any): Promise<any> {
    return {
      type: 'domain.webapp',
      data: {
        frontend: {
          framework: this.detectFramework(),
          routes: this.extractRoutes(),
          components: this.analyzeComponents()
        },
        backend: {
          api: this.mapApiEndpoints(),
          database: this.analyzeDataModels()
        }
      }
    };
  }
  
  // Implementation of the analysis methods...
}

Troubleshooting

Common issues and solutions:

  • Context Not Appearing: Check registration and error handling
  • Performance Issues: Implement caching and optimize data processing
  • Incorrect Context: Validate data sources and transformation logic
  • Memory Leaks: Ensure proper cleanup of resources

Resources

Next Steps

After mastering context providers, consider exploring: