@ooples/token-optimizer-mcp
Version:
Intelligent context window optimization for Claude Code - store content externally via caching and compression, freeing up your context window for what matters
350 lines • 11.6 kB
TypeScript
/**
* Smart Database - Database Query Optimizer with 83% Token Reduction
*
* Features:
* - Query execution with intelligent result caching
* - Query plan analysis (EXPLAIN)
* - Index usage detection and recommendations
* - Query optimization suggestions
* - Slow query detection and bottleneck analysis
* - Connection pooling information
* - Query performance tracking
*
* Token Reduction Strategy:
* - Cached queries: Row count only (95% reduction)
* - EXPLAIN analysis: Plan summary (85% reduction)
* - Query execution: Top 10 rows (80% reduction)
* - Analysis only: Query info + suggestions (90% reduction)
* - Average: 83% reduction
*/
import { CacheEngine } from '../../core/cache-engine.js';
import { TokenCounter } from '../../core/token-counter.js';
import { MetricsCollector } from '../../core/metrics.js';
export type DatabaseAction = 'query' | 'explain' | 'analyze' | 'optimize' | 'health' | 'pool' | 'slow' | 'batch';
export type DatabaseEngine = 'postgresql' | 'mysql' | 'sqlite' | 'mongodb' | 'redis' | 'generic';
export type QueryType = 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'DDL' | 'UNKNOWN';
export interface SmartDatabaseOptions {
action?: DatabaseAction;
engine?: DatabaseEngine;
connectionString?: string;
host?: string;
port?: number;
database?: string;
user?: string;
password?: string;
query?: string;
queries?: string[];
params?: any[];
timeout?: number;
limit?: number;
includeMetadata?: boolean;
explain?: boolean;
poolSize?: number;
maxPoolSize?: number;
minPoolSize?: number;
connectionTimeout?: number;
idleTimeout?: number;
enableCache?: boolean;
ttl?: number;
force?: boolean;
enableRetry?: boolean;
maxRetries?: number;
slowQueryThreshold?: number;
analyzeIndexUsage?: boolean;
detectN1?: boolean;
enableCircuitBreaker?: boolean;
circuitBreakerThreshold?: number;
circuitBreakerTimeout?: number;
batchSize?: number;
parallelBatches?: number;
}
export interface QueryResult {
rows: any[];
rowCount: number;
fields?: FieldInfo[];
affectedRows?: number;
insertId?: string | number;
}
export interface FieldInfo {
name: string;
type: string;
nullable: boolean;
isPrimaryKey?: boolean;
isForeignKey?: boolean;
}
export interface QueryPlan {
planType: string;
estimatedCost: number;
estimatedRows: number;
actualCost?: number;
actualRows?: number;
executionTime: number;
steps: QueryPlanStep[];
}
export interface QueryPlanStep {
stepNumber: number;
operation: string;
table?: string;
indexUsed?: string;
rowsScanned: number;
rowsReturned: number;
cost: number;
description: string;
}
export interface QueryAnalysis {
queryType: QueryType;
complexity: 'low' | 'medium' | 'high' | 'critical';
estimatedDuration: number;
tablesAccessed: string[];
indexesUsed: string[];
missingIndexes: MissingIndex[];
optimizations: Optimization[];
warnings: string[];
score: number;
}
export interface MissingIndex {
table: string;
columns: string[];
reason: string;
impact: 'low' | 'medium' | 'high' | 'critical';
estimatedImprovement: string;
}
export interface Optimization {
type: 'index' | 'rewrite' | 'join' | 'subquery' | 'limit' | 'cache' | 'partition';
priority: 'low' | 'medium' | 'high' | 'critical';
description: string;
suggestedQuery?: string;
estimatedImprovement: string;
}
export interface HealthMetrics {
status: 'healthy' | 'degraded' | 'unhealthy';
uptime: number;
activeConnections: number;
maxConnections: number;
queryRate: number;
avgQueryTime: number;
slowQueries: number;
errors: number;
lastError?: string;
lastErrorTime?: number;
diskUsage?: {
total: number;
used: number;
available: number;
percentUsed: number;
};
memoryUsage?: {
total: number;
used: number;
cached: number;
buffers: number;
};
}
export interface PoolInfo {
totalConnections: number;
activeConnections: number;
idleConnections: number;
waitingClients: number;
totalRequests: number;
avgWaitTime: number;
maxWaitTime: number;
poolEfficiency: number;
recommendations: string[];
}
export interface SlowQuery {
query: string;
executionTime: number;
timestamp: number;
rowsExamined: number;
rowsReturned: number;
lockTime?: number;
database?: string;
user?: string;
}
export interface BatchResult {
totalQueries: number;
successful: number;
failed: number;
totalTime: number;
averageTime: number;
results: QueryResult[];
errors: Array<{
index: number;
error: string;
}>;
}
export interface SmartDatabaseResult {
success: boolean;
action: string;
result?: QueryResult;
plan?: QueryPlan;
analysis?: QueryAnalysis;
health?: HealthMetrics;
pool?: PoolInfo;
slowQueries?: SlowQuery[];
batch?: BatchResult;
cached?: boolean;
executionTime?: number;
retries?: number;
timestamp?: number;
error?: string;
}
export interface SmartDatabaseOutput {
result: string;
tokens: {
baseline: number;
actual: number;
saved: number;
reduction: number;
};
cached: boolean;
executionTime: number;
}
export declare class SmartDatabase {
private cache;
private tokenCounter;
private metrics;
private pool;
private circuitBreaker;
private slowQueries;
private queryHistory;
constructor(cache: CacheEngine, tokenCounter: TokenCounter, metrics: MetricsCollector);
run(options: SmartDatabaseOptions): Promise<SmartDatabaseOutput>;
private validateOptions;
private executeDatabaseAction;
private executeQuery;
private executeQueryInternal;
private explainQuery;
private analyzeQuery;
private optimizeQuery;
private getHealthMetrics;
private getPoolInfo;
private getSlowQueries;
private executeBatch;
private shouldUsePool;
private shouldCache;
private initializePool;
private detectQueryType;
private extractTables;
private calculateComplexity;
private calculateQueryScore;
private sleep;
private generateCacheKey;
private getCachedResult;
private cacheResult;
private transformOutput;
private formatVerboseOutput;
private formatCachedOutput;
private formatPlanOutput;
private formatAnalysisOutput;
private formatResultOutput;
private formatHealthOutput;
private formatPoolOutput;
private formatSlowQueriesOutput;
private formatBatchOutput;
close(): Promise<void>;
}
export declare function getSmartDatabase(cache: CacheEngine, tokenCounter: TokenCounter, metrics: MetricsCollector): SmartDatabase;
export declare function runSmartDatabase(options: SmartDatabaseOptions): Promise<string>;
export declare const SMART_DATABASE_TOOL_DEFINITION: {
readonly name: "smart_database";
readonly description: "Database query optimizer with connection pooling, circuit breaking, and 83% token reduction. Supports query execution, EXPLAIN analysis, performance optimization, health monitoring, slow query detection, and batch operations.";
readonly inputSchema: {
readonly type: "object";
readonly properties: {
readonly action: {
readonly type: "string";
readonly enum: readonly ["query", "explain", "analyze", "optimize", "health", "pool", "slow", "batch"];
readonly description: "Action to perform (default: query)";
readonly default: "query";
};
readonly engine: {
readonly type: "string";
readonly enum: readonly ["postgresql", "mysql", "sqlite", "mongodb", "redis", "generic"];
readonly description: "Database engine (default: generic)";
readonly default: "generic";
};
readonly query: {
readonly type: "string";
readonly description: "SQL query to execute (required for query/explain/analyze/optimize)";
};
readonly queries: {
readonly type: "array";
readonly items: {
readonly type: "string";
};
readonly description: "Array of queries for batch execution";
};
readonly params: {
readonly type: "array";
readonly description: "Query parameters for prepared statements";
};
readonly timeout: {
readonly type: "number";
readonly description: "Query timeout in milliseconds (default: 30000)";
readonly default: 30000;
};
readonly limit: {
readonly type: "number";
readonly description: "Maximum rows to return (default: 10)";
readonly default: 10;
};
readonly poolSize: {
readonly type: "number";
readonly description: "Connection pool size (default: 10)";
readonly default: 10;
};
readonly maxPoolSize: {
readonly type: "number";
readonly description: "Maximum pool size (default: 20)";
readonly default: 20;
};
readonly enableCache: {
readonly type: "boolean";
readonly description: "Enable query result caching (default: true)";
readonly default: true;
};
readonly ttl: {
readonly type: "number";
readonly description: "Cache TTL in seconds (default: 300)";
readonly default: 300;
};
readonly force: {
readonly type: "boolean";
readonly description: "Force fresh query, bypassing cache (default: false)";
readonly default: false;
};
readonly enableRetry: {
readonly type: "boolean";
readonly description: "Enable automatic retry on failure (default: true)";
readonly default: true;
};
readonly maxRetries: {
readonly type: "number";
readonly description: "Maximum retry attempts (default: 3)";
readonly default: 3;
};
readonly slowQueryThreshold: {
readonly type: "number";
readonly description: "Slow query threshold in milliseconds (default: 1000)";
readonly default: 1000;
};
readonly enableCircuitBreaker: {
readonly type: "boolean";
readonly description: "Enable circuit breaker pattern (default: true)";
readonly default: true;
};
readonly batchSize: {
readonly type: "number";
readonly description: "Batch size for batch operations (default: 100)";
readonly default: 100;
};
readonly parallelBatches: {
readonly type: "number";
readonly description: "Number of parallel batch operations (default: 4)";
readonly default: 4;
};
};
};
};
//# sourceMappingURL=smart-database.d.ts.map