code-auditor-mcp
Version:
Multi-language code quality auditor with MCP server - Analyze TypeScript, JavaScript, and Go code for SOLID principles, DRY violations, security patterns, and more
744 lines • 20.9 kB
TypeScript
/**
* Type definitions for the code auditor
* Generic types that work with any TypeScript/JavaScript project
*/
export type Severity = 'critical' | 'warning' | 'suggestion';
export type ReportFormat = 'html' | 'json' | 'csv';
export type RenderType = 'client' | 'server' | 'unknown';
export type DataFetchingMethod = 'server' | 'client' | 'none';
export interface QueryInfo {
type: string;
tables: string[];
line: number;
hasJoins?: boolean;
complexity?: 'simple' | 'moderate' | 'complex';
hasOrganizationFilter?: boolean;
}
export interface SecurityViolation extends Violation {
type: 'security';
category: string;
}
export interface ArchitectureViolation extends Violation {
type: 'architecture';
category: string;
}
export interface Violation {
file: string;
line?: number;
column?: number;
severity: Severity;
message: string;
details?: string | Record<string, any>;
snippet?: string;
suggestion?: string;
[key: string]: any;
}
export interface AnalyzerResult {
violations: Violation[];
filesProcessed: number;
executionTime: number;
errors?: Array<{
file: string;
error: string;
}>;
analyzerName?: string;
[key: string]: any;
}
export interface AuditOptions {
includePaths?: string[];
excludePaths?: string[];
fileExtensions?: string[];
minSeverity?: Severity;
enabledAnalyzers?: string[];
outputFormats?: ReportFormat[];
outputDir?: string;
failOnCritical?: boolean;
duplicateThreshold?: number;
verbose?: boolean;
configFile?: string;
thresholds?: {
maxCritical?: number;
maxWarnings?: number;
maxSuggestions?: number;
minHealthScore?: number;
};
unusedImportsConfig?: {
checkLevel?: 'function' | 'file';
includeTypeOnlyImports?: boolean;
ignorePatterns?: string[];
};
}
export interface ProgressCallback {
(progress: {
current: number;
total: number;
analyzer: string;
file?: string;
phase?: string;
}): void;
}
export type AnalyzerFunction = (files: string[], config: any, options?: AuditOptions, progressCallback?: ProgressCallback) => Promise<AnalyzerResult>;
export interface AnalyzerDefinition {
name: string;
analyze: AnalyzerFunction;
defaultConfig?: any;
description?: string;
category?: string;
}
export interface AuditSummary {
totalFiles: number;
totalViolations: number;
criticalIssues: number;
warnings: number;
suggestions: number;
violationsByCategory: Record<string, number>;
topIssues: Array<{
type: string;
count: number;
}>;
}
export interface AuditResult {
timestamp: Date;
summary: AuditSummary;
analyzerResults: Record<string, AnalyzerResult>;
recommendations: Recommendation[];
metadata: {
auditDuration: number;
filesAnalyzed: number;
analyzersRun: string[];
configUsed?: AuditOptions;
collectedFunctions?: FunctionMetadata[];
fileToFunctionsMap?: Record<string, FunctionMetadata[]>;
};
}
export interface ComponentAnalysis {
filePath: string;
renderType: RenderType;
hasErrorBoundary: boolean;
dataFetchingMethod?: DataFetchingMethod;
violations: Violation[];
suggestions: string[];
imports: string[];
exports: string[];
hasAppShell?: boolean;
hasPageHeader?: boolean;
}
export interface SecurityAnalysis {
filePath: string;
httpMethods: string[];
authPattern?: string;
authWrapper?: string;
rateLimiting?: boolean;
hasErrorHandling: boolean;
usesStandardResponses?: boolean;
organizationFiltering?: boolean;
violations: Violation[];
}
export interface SOLIDViolation extends Violation {
principle: 'single-responsibility' | 'open-closed' | 'liskov-substitution' | 'interface-segregation' | 'dependency-inversion';
className?: string;
methodName?: string;
}
export interface DRYViolation extends Violation {
type: 'exact-duplicate' | 'pattern-duplication' | 'similar-logic';
similarity?: number;
locations?: Array<{
file: string;
line: number;
}>;
metrics?: {
duplicateLines: number;
totalLines: number;
};
}
export interface DataAccessPattern {
source: 'component' | 'api' | 'service';
filePath: string;
database?: string;
databaseType?: string;
tables: string[];
queries: QueryInfo[];
performanceRisk: 'low' | 'medium' | 'high';
hasOrganizationFilter?: boolean;
hasSqlInjectionRisk?: boolean;
}
export interface DataAccessViolation extends Violation {
pattern: 'raw-sql' | 'missing-validation' | 'no-pooling' | 'performance-issue';
query?: string;
risk?: 'sql-injection' | 'performance' | 'security' | 'data-leak';
}
export interface SecurityPatternIssue extends Violation {
pattern: 'missing-auth' | 'inconsistent-auth' | 'missing-validation' | 'security-bypass';
expectedPattern?: string;
}
export interface ReportGenerator {
generate(result: AuditResult, format: ReportFormat): string;
}
export interface Recommendation {
title: string;
description: string;
priority: 'high' | 'medium' | 'low';
effort: 'small' | 'medium' | 'large';
category: string;
affectedFiles: string[];
exampleImplementation?: string;
}
export interface AuditConfig {
includePaths?: string[];
excludePaths?: string[];
enabledAnalyzers?: string[];
outputFormats?: ReportFormat[];
outputDir?: string;
outputDirectory?: string;
minSeverity?: Severity;
failOnCritical?: boolean;
showProgress?: boolean;
parallel?: boolean;
thresholds?: {
maxCritical?: number;
maxWarnings?: number;
maxSuggestions?: number;
minHealthScore?: number;
};
analyzerOptions?: Record<string, any>;
}
export type PageAnalysis = ComponentAnalysis;
export type RouteAnalysis = SecurityAnalysis;
export type AuthWrapper = string;
export type AuthPatternIssue = SecurityPatternIssue;
export type DatabaseType = string;
export type SeverityLevel = Severity;
export type RecommendationPriority = 'high' | 'medium' | 'low';
export interface AuditMetadata {
auditDuration: number;
filesAnalyzed: number;
analyzersRun: string[];
configUsed?: AuditOptions;
reports?: string[];
}
export interface BaseAnalyzerOptions {
verbose?: boolean;
configFile?: string;
}
export interface FileInfo {
path: string;
size: number;
lastModified: Date;
}
export interface ImportInfo {
moduleSpecifier: string;
importedNames: string[];
isTypeOnly: boolean;
line: number;
}
export interface ExportInfo {
name: string;
isDefault: boolean;
isTypeOnly: boolean;
line: number;
}
export interface AuditProgress {
current: number;
total: number;
analyzer: string;
file?: string;
phase?: string;
message?: string;
}
export interface AnalyzerConfigDocument {
$loki?: number;
meta?: any;
analyzerName: string;
projectPath?: string | null;
config: Record<string, any>;
isGlobal: boolean;
version?: string;
createdAt: Date;
updatedAt: Date;
createdBy: 'system' | 'user';
metadata?: {
description?: string;
category?: string;
dependencies?: string[];
};
}
export interface AuditRunnerOptions extends AuditOptions {
progressCallback?: (progress: AuditProgress) => void;
errorCallback?: (error: Error, context: string) => void;
outputDirectory?: string;
configName?: string;
projectRoot?: string;
analyzerConfigs?: Record<string, any>;
indexFunctions?: boolean;
}
export interface FunctionMetadata {
name: string;
filePath: string;
lineNumber?: number;
startLine?: number;
endLine?: number;
language?: string;
dependencies: string[];
purpose: string;
context: string;
metadata?: Record<string, any>;
}
export interface EnhancedFunctionMetadata extends FunctionMetadata {
signature: string;
parameters: Array<{
name: string;
type?: string;
description?: string;
optional?: boolean;
defaultValue?: string;
}>;
returnType?: string;
jsDoc?: {
description?: string;
examples?: string[];
tags?: Record<string, string[]>;
};
typeInfo?: {
generics?: string[];
interfaces?: string[];
types?: string[];
};
complexity?: number;
tokens?: string[];
tokenizedName?: string;
lastModified?: Date;
body?: string;
metadata?: {
entityType?: 'function' | 'component';
componentType?: 'functional' | 'class' | 'memo' | 'forwardRef';
hooks?: HookUsage[];
props?: PropDefinition[];
functionCalls?: string[];
calledBy?: string[];
usedImports?: string[];
unusedImports?: string[];
importUsage?: ImportUsageInfo[];
dependencyDepth?: number;
body?: string;
contentMatches?: Array<{
term: string;
line: number;
column: number;
}>;
matchContexts?: Array<{
match: {
term: string;
line: number;
column: number;
};
context: {
before: string[];
line: string;
after: string[];
};
}>;
};
}
export interface ParsedQuery {
terms: string[];
originalTerms?: string[];
phrases: string[];
excludedTerms: string[];
filters: {
filePath?: string;
fileType?: string;
language?: string;
hasJsDoc?: boolean;
complexity?: {
min?: number;
max?: number;
};
dateRange?: {
start?: Date;
end?: Date;
};
metadata?: {
entityType?: string;
componentType?: string;
hasHook?: string;
hasProp?: string;
usesDependency?: string;
callsFunction?: string;
calledByFunction?: string;
dependsOnModule?: string;
hasUnusedImports?: boolean;
};
};
searchFields?: Array<'name' | 'signature' | 'jsDoc' | 'parameters' | 'returnType' | 'purpose' | 'context'>;
fuzzy?: boolean;
stemming?: boolean;
}
export interface SearchOptions {
query?: string;
parsedQuery?: ParsedQuery;
filters?: {
language?: string;
filePath?: string;
hasAnyDependency?: string[];
fileType?: string;
hasJsDoc?: boolean;
complexity?: {
min?: number;
max?: number;
};
dateRange?: {
start?: Date;
end?: Date;
};
metadata?: {
entityType?: string;
componentType?: string;
hasHook?: string;
hasProp?: string;
usesDependency?: string;
callsFunction?: string;
calledByFunction?: string;
dependsOnModule?: string;
hasUnusedImports?: boolean;
};
};
searchStrategy?: 'exact' | 'fuzzy' | 'semantic';
searchFields?: Array<'name' | 'signature' | 'jsDoc' | 'parameters' | 'returnType' | 'purpose' | 'context'>;
searchMode?: 'metadata' | 'content' | 'both';
scoringWeights?: {
nameMatch?: number;
signatureMatch?: number;
jsDocMatch?: number;
parameterMatch?: number;
purposeMatch?: number;
contextMatch?: number;
};
limit?: number;
offset?: number;
includeSnippets?: boolean;
highlightMatches?: boolean;
}
export interface RegisterResult {
success: boolean;
registered: number;
failed: number;
errors?: Array<{
function: string;
error: string;
}>;
}
export interface SearchResult {
functions: Array<EnhancedFunctionMetadata & {
score: number;
highlights?: {
name?: string[];
signature?: string[];
jsDoc?: string[];
parameters?: string[];
purpose?: string[];
context?: string[];
};
matchedFields?: string[];
contentMatches?: Array<{
term: string;
line: number;
column: number;
}>;
matchContexts?: Array<{
match: {
term: string;
line: number;
column: number;
};
context: {
before: string[];
line: string;
after: string[];
};
}>;
}>;
totalCount: number;
query?: string;
parsedQuery?: ParsedQuery;
executionTime: number;
facets?: {
languages?: Record<string, number>;
fileTypes?: Record<string, number>;
complexityRanges?: Record<string, number>;
};
suggestions?: string[];
}
export interface IndexStats {
totalFunctions: number;
languages: Record<string, number>;
topDependencies: Array<{
name: string;
count: number;
}>;
filesIndexed: number;
lastUpdated: Date;
}
export interface ComponentMetadata extends FunctionMetadata {
entityType: 'component';
componentType: 'functional' | 'class' | 'memo' | 'forwardRef';
props?: PropDefinition[];
hooks?: HookUsage[];
jsxElements?: string[];
imports?: ComponentImport[];
hasErrorBoundary?: boolean;
complexity?: number;
isExported: boolean;
}
export interface PropDefinition {
name: string;
type?: string;
required: boolean;
hasDefault: boolean;
}
export interface HookUsage {
name: string;
line: number;
customHook: boolean;
}
export interface ComponentImport {
name: string;
path: string;
isDefault: boolean;
}
export declare enum ResponsibilityType {
DataFetching = "data-fetching",
FormHandling = "form-handling",
UIState = "ui-state",
BusinessLogic = "business-logic",
SideEffects = "side-effects",
EventHandling = "event-handling",
Routing = "routing",
Authentication = "authentication",
Layout = "layout-styling",
DataTransformation = "data-transformation",
Subscriptions = "subscriptions",
ErrorHandling = "error-handling",
StateManagement = "state-management"
}
export interface ComponentResponsibility {
type: ResponsibilityType;
indicators: string[];
severity: 'related' | 'unrelated' | 'mixed';
line?: number;
column?: number;
details?: string;
}
export interface ComponentPattern {
name: string;
indicators: PatternIndicator[];
allowedResponsibilities: ResponsibilityType[];
relatedResponsibilities?: ResponsibilityType[][];
complexityMultiplier: number;
description: string;
}
export interface PatternIndicator {
type: 'name' | 'path' | 'hooks' | 'props' | 'imports';
pattern: RegExp | string;
weight?: number;
}
export interface ComponentPatternConfig {
patterns: ComponentPattern[];
customPatterns?: ComponentPattern[];
enablePatternDetection: boolean;
}
export interface RefactoringSuggestion {
pattern: 'extract-hook' | 'split-component' | 'container-presenter' | 'compose-components' | 'extract-service';
description: string;
example?: string;
relatedResponsibilities: ResponsibilityType[];
}
export interface ComponentRelationship {
parentComponent: string;
childComponent: string;
usageCount: number;
importPath: string;
}
export interface ReactViolation extends Violation {
componentName?: string;
violationType: 'missing-props' | 'hooks-violation' | 'no-error-boundary' | 'complexity' | 'performance' | 'accessibility';
}
export interface ReactAnalyzerConfig {
detectFunctionalComponents: boolean;
detectClassComponents: boolean;
detectMemoComponents: boolean;
requirePropTypes: boolean;
requireErrorBoundaries: boolean;
checkHooksRules: boolean;
maxComponentComplexity: number;
checkUnnecessaryRerenders: boolean;
requireMemoization: boolean;
checkAccessibility: boolean;
preventDirectDOMAccess: boolean;
requireKeyProps: boolean;
}
export interface ComponentScanResult {
filePath: string;
components: ComponentMetadata[];
imports: ComponentImport[];
fileHash?: string;
parseErrors?: string[];
}
export interface FunctionCall {
callee: string;
callType: 'direct' | 'method' | 'dynamic';
line: number;
column: number;
arguments?: number;
}
export interface ImportMapping {
localName: string;
importedName: string;
modulePath: string;
importType: 'named' | 'default' | 'namespace';
isTypeOnly: boolean;
}
export interface DependencyInfo {
imports: ImportMapping[];
functionCalls: FunctionCall[];
identifierUsage: Map<string, UsageInfo>;
}
export interface UsageInfo {
usageType: 'direct' | 'type' | 'reexport';
usageCount: number;
lineNumbers: number[];
}
export interface ImportUsageInfo {
importPath: string;
usageType: 'direct' | 'type' | 'reexport';
usageCount: number;
lineNumbers: number[];
}
export interface SchemaColumn {
name: string;
type: string;
nullable?: boolean;
primaryKey?: boolean;
defaultValue?: string | number | boolean | null;
unique?: boolean;
indexed?: boolean;
length?: number;
precision?: number;
scale?: number;
description?: string;
enum?: string[];
}
export interface SchemaReference {
foreignKey: string;
referencedTable: string;
referencedColumn: string;
onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
onUpdate?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
description?: string;
}
export interface SchemaIndex {
name: string;
columns: string[];
unique?: boolean;
type?: 'btree' | 'hash' | 'gin' | 'gist' | 'text' | 'compound';
description?: string;
}
export interface SchemaTable {
name: string;
type: 'table' | 'collection' | 'view';
database?: string;
schema?: string;
columns: SchemaColumn[];
references: SchemaReference[];
indexes?: SchemaIndex[];
constraints?: string[];
description?: string;
tags?: string[];
estimatedRows?: number;
isTemporary?: boolean;
partitionKey?: string;
}
export interface DatabaseSchema {
name: string;
type: 'postgresql' | 'mysql' | 'mongodb' | 'sqlite' | 'redis' | 'dynamodb' | 'other';
version?: string;
host?: string;
port?: number;
database?: string;
schemas?: string[];
tables: SchemaTable[];
relationships?: SchemaRelationship[];
description?: string;
createdAt?: Date;
updatedAt?: Date;
metadata?: {
environment?: 'development' | 'staging' | 'production';
migrations?: string[];
seeds?: string[];
backupFrequency?: string;
};
}
export interface SchemaRelationship {
id: string;
type: 'one-to-one' | 'one-to-many' | 'many-to-many';
fromTable: string;
toTable: string;
fromColumn: string;
toColumn: string;
description?: string;
bidirectional?: boolean;
}
export interface SchemaDefinition {
version: string;
name: string;
description?: string;
databases: DatabaseSchema[];
globalReferences?: SchemaReference[];
metadata?: {
author?: string;
createdAt?: Date;
updatedAt?: Date;
tags?: string[];
environment?: string;
};
}
export interface SchemaViolation extends Violation {
schemaType: 'missing-reference' | 'orphaned-table' | 'naming-convention' | 'missing-index' | 'circular-dependency';
tableName?: string;
columnName?: string;
expectedSchema?: string;
actualSchema?: string;
}
export interface SchemaPattern {
pattern: 'entity-table' | 'junction-table' | 'audit-table' | 'lookup-table' | 'temporal-table';
tableNames: string[];
confidence: number;
description: string;
}
export interface SchemaUsage {
tableName: string;
filePath: string;
functionName: string;
usageType: 'query' | 'insert' | 'update' | 'delete' | 'reference';
line: number;
column?: number;
rawQuery?: string;
parameters?: string[];
}
export interface SchemaIndexMetadata {
schemaId: string;
schemaName: string;
indexedAt: Date;
tableCount: number;
relationshipCount: number;
usagePatterns: SchemaUsage[];
discoveredPatterns: SchemaPattern[];
violations: SchemaViolation[];
lastAnalyzed?: Date;
}
export interface SchemaAwareFunctionMetadata extends EnhancedFunctionMetadata {
schemaUsage?: SchemaUsage[];
affectedTables?: string[];
schemaPatterns?: string[];
}
export * from './types/whitelist.js';
//# sourceMappingURL=types.d.ts.map