Documentation
Developer Reference/API Reference

API Reference

This reference documentation provides detailed information about ThinkCode's APIs for developers who want to extend, customize, or integrate with the platform. ThinkCode exposes several core APIs that enable powerful interactions with the editor, AI systems, and extension framework.

ExMCP API

The ExMCP (Extended Machine Comprehension Protocol) API is the foundation of ThinkCode's AI integration capabilities. It provides a standardized way to communicate context, actions, and responses between the editor and AI systems.

Core Concepts

ConceptDescription
Context ObjectContainer for all contextual information shared with AI systems
ProviderSource of contextual information (e.g., file system, git history)
Extension PointLocation where custom logic can be injected
MessageStructured communication unit between components

Key Interfaces

// Core ExMCP Interface
export interface ExMCPContext {
  version: string;
  timestamp: number;
  sources: ContextSource[];
  metadata: Record<string, any>;
}
 
// Context Source Interface
export interface ContextSource {
  id: string;
  type: string;
  priority: number;
  content: any;
  metadata: Record<string, any>;
}
 
// Message Interface
export interface ExMCPMessage {
  id: string;
  type: MessageType;
  payload: any;
  timestamp: number;
  metadata: Record<string, any>;
}

Context API

The Context API allows extensions to access and modify the context shared with AI systems:

// Get current context
const context = await thinkcode.exmcp.getContext();
 
// Register context provider
thinkcode.exmcp.registerContextProvider({
  id: 'my-provider',
  name: 'My Custom Provider',
  description: 'Provides custom context data',
  async provideContext(request) {
    // Generate context based on request
    return {
      type: 'custom-data',
      content: { /* your data */ },
      metadata: { /* metadata */ }
    };
  }
});
 
// Update context manually
await thinkcode.exmcp.updateContext({
  source: 'my-provider',
  data: { /* updated data */ }
});

Message API

The Message API enables communication between ThinkCode components:

// Send a message
await thinkcode.exmcp.sendMessage({
  type: 'request',
  recipient: 'ai-engine',
  payload: {
    action: 'generate-code',
    parameters: { /* parameters */ }
  }
});
 
// Listen for messages
thinkcode.exmcp.onMessage(message => {
  if (message.type === 'response' && message.source === 'ai-engine') {
    // Handle AI response
  }
});

Extension Points

ExMCP provides several extension points:

Extension PointDescription
context.providerRegister a new context provider
context.transformerTransform context before AI processing
message.interceptorIntercept and modify messages
response.handlerCustom handling of AI responses

VSCode Integration API

ThinkCode builds upon the VSCode API, extending it with additional capabilities while maintaining compatibility. This allows extensions to leverage both VSCode and ThinkCode-specific features.

Editor Integration

// Access the active editor
const editor = thinkcode.window.activeTextEditor;
 
// Insert text at the current cursor position
editor.edit(editBuilder => {
  editBuilder.insert(editor.selection.active, 'Hello, ThinkCode!');
});
 
// Get the selected text
const selection = editor.selection;
const selectedText = editor.document.getText(selection);
 
// Apply text edits
const edits = [
  new thinkcode.TextEdit(
    new thinkcode.Range(0, 0, 0, 0),
    '// Auto-generated code\n'
  )
];
await thinkcode.workspace.applyEdit(
  new thinkcode.WorkspaceEdit().set(document.uri, edits)
);

Document Management

// Open a document
const document = await thinkcode.workspace.openTextDocument(
  thinkcode.Uri.file('/path/to/file.ts')
);
await thinkcode.window.showTextDocument(document);
 
// Watch for file changes
const watcher = thinkcode.workspace.createFileSystemWatcher(
  '**/*.ts'
);
watcher.onDidChange(uri => {
  console.log(`File changed: ${uri.fsPath}`);
});
 
// Access workspace folders
const folders = thinkcode.workspace.workspaceFolders;

ThinkCode-Specific Extensions

ThinkCode extends the VSCode API with additional capabilities:

// Register a custom AI command
thinkcode.commands.registerAICommand('myExtension.generateCode', async (context) => {
  // Process AI-generated content
  return {
    code: '// Generated code',
    explanation: 'This code does X',
    metadata: { complexity: 'medium' }
  };
});
 
// Add custom context data to the current document
thinkcode.languages.setDocumentContext(document, {
  domain: 'e-commerce',
  architecture: 'microservices',
  patterns: ['repository', 'factory']
});

Think Engine API

The Think Engine API provides access to ThinkCode's AI capabilities, allowing extensions to leverage machine learning models for various tasks.

Model Access

// Access the AI model
const model = await thinkcode.ai.getModel('text-generation');
 
// Generate text with the model
const result = await model.generate({
  prompt: 'Write a function that calculates Fibonacci numbers',
  maxTokens: 500,
  temperature: 0.7,
  options: {
    format: 'typescript',
    includeComments: true
  }
});

AI Tools

// Use code analysis tool
const analysis = await thinkcode.ai.tools.analyzeCode({
  code: sourceCode,
  language: 'typescript',
  type: 'security'
});
 
// Generate tests
const tests = await thinkcode.ai.tools.generateTests({
  sourceFile: document.uri.fsPath,
  testFramework: 'jest'
});
 
// Explain code
const explanation = await thinkcode.ai.tools.explainCode({
  code: selectedCode,
  detailLevel: 'detailed',
  audience: 'intermediate'
});

Custom AI Workflows

// Define a custom AI workflow
const workflow = thinkcode.ai.createWorkflow('code-review');
 
// Add steps to the workflow
workflow.addStep({
  name: 'analyze',
  tool: 'code-analysis',
  parameters: { type: 'quality' }
});
 
workflow.addStep({
  name: 'suggest',
  tool: 'code-suggestion',
  parameters: {
    basedOn: 'analyze',
    maxSuggestions: 5
  }
});
 
// Execute the workflow
const results = await workflow.execute({
  targetFiles: ['src/main.ts', 'src/utils.ts']
});

AI Context Management

// Enhance context with domain-specific information
await thinkcode.ai.context.enhance({
  domain: 'financial',
  concepts: ['transaction', 'ledger', 'reconciliation'],
  terminology: {
    'reconciliation': 'The process of comparing transactions...'
  }
});
 
// Clear specific context categories
await thinkcode.ai.context.clear(['session-history']);

Event System

ThinkCode provides a comprehensive event system to react to editor and AI actions:

// Listen for AI-related events
thinkcode.ai.onWillGenerateCode(event => {
  // Modify generation parameters
  event.parameters.temperature = 0.8;
});
 
thinkcode.ai.onDidGenerateCode(result => {
  // Process generated code
  console.log(`Generated ${result.tokens} tokens`);
});
 
// Listen for context changes
thinkcode.exmcp.onContextChanged(change => {
  if (change.source === 'git-provider') {
    // React to git context changes
  }
});

Storage API

Extensions can persist data using ThinkCode's storage API:

// Extension storage
const storage = thinkcode.storage.getExtensionStorage('my-extension');
 
// Store data
await storage.set('preferences', {
  theme: 'dark',
  fontSize: 14
});
 
// Retrieve data
const preferences = await storage.get('preferences');
 
// Watch for changes
storage.onDidChange(key => {
  if (key === 'preferences') {
    // Handle preferences change
  }
});

Authentication and Security

// Request access to secure resources
const token = await thinkcode.security.getAccessToken({
  service: 'github',
  scopes: ['repo', 'user']
});
 
// Check permissions
const hasPermission = await thinkcode.security.checkPermission(
  'workspace.writeFiles'
);
 
// Encrypt sensitive data
const encrypted = await thinkcode.security.encrypt('sensitive-data');

API Versioning and Compatibility

ThinkCode APIs follow semantic versioning (SemVer) principles:

  • Major version changes (X.0.0): Include breaking changes that require code updates
  • Minor version changes (0.X.0): Add new features in a backward-compatible manner
  • Patch version changes (0.0.X): Include bug fixes and non-breaking improvements

You can check the current API version and register for compatibility modes:

// Get API version
const apiVersion = thinkcode.version;
 
// Register for specific API version compatibility
thinkcode.registerAPICompatibility('1.5.0');

Common API Patterns

Promise-Based APIs

Most ThinkCode APIs that perform I/O operations return Promises:

// Using async/await (recommended)
async function performOperation() {
  try {
    const result = await thinkcode.ai.generateCode({ /* params */ });
    // Handle result
  } catch (error) {
    // Handle error
  }
}
 
// Using Promise chains
thinkcode.ai.generateCode({ /* params */ })
  .then(result => {
    // Handle result
  })
  .catch(error => {
    // Handle error
  });

Disposables

Resources that need to be cleaned up implement the Disposable pattern:

// Register event listener and store the disposable
const disposable = thinkcode.ai.onDidGenerateCode(result => {
  // Handle event
});
 
// Clean up when no longer needed
disposable.dispose();
 
// Or use within a registered activation function
context.subscriptions.push(disposable);

API Limitations and Best Practices

  1. Respect Rate Limits: AI operations may have rate limits to prevent abuse
  2. Batch Operations: Group multiple operations when possible
  3. Context Size: Be mindful of the context size when providing data to AI models
  4. Error Handling: Always handle errors gracefully, especially for network operations
  5. User Consent: Request only necessary permissions and respect user privacy
  6. Performance: Cache results when appropriate to reduce API calls

Additional Resources