/** * 0xRay Processor Pipeline MCP Server * * Advanced processor pipeline with codex validation, compliance monitoring, and framework enforcement */ import * as fs from "fs"; import { frameworkLogger } from "../core/framework-logger.js"; import { CodexLoader } from "../enforcement/loaders/codex-loader.js"; import type { RuleDefinition, RuleValidationContext } from "../enforcement/types.js"; import { XrayKnowledgeSkillBase } from "./shared/knowledge-skill-base.js"; interface PreProcessorArgs { content: string; context?: Record; validateCodex?: boolean; strictMode?: boolean; } interface PostProcessorArgs { content: string; results?: Record; enforceCompliance?: boolean; auditTrail?: boolean; } interface CodexValidationArgs { content: string; terms?: string[]; strict?: boolean; } interface ComplianceCheckArgs { content: string; operation: string; context?: Record; } interface CodexValidationResult { validations: string[]; warnings: string[]; violations: string[]; recommendations: string[]; compliance: number; blocked: boolean; reason: string; } interface CodexTermCheckResult { passed: boolean; reason: string; recommendation: string; critical: boolean; } interface SecurityCheckResult { warnings: string[]; } interface ComplianceEnforcementResult { compliance: string[]; recommendations: string[]; approved: boolean; } interface PostProcessResult { processed: string; compliance: string[]; auditEntries: string[]; recommendations: string[]; finalApproval: boolean; } interface QualityAssuranceResult { recommendations: string[]; } interface FrameworkComplianceResult { score: number; criticalIssues: string[]; warnings: string[]; actions: string[]; approved: boolean; } class XrayProcessorPipelineServer extends XrayKnowledgeSkillBase { private codexLoader: CodexLoader; private codexRules: RuleDefinition[] = []; private codexTerms: string[] = [ "Progressive Prod-Ready Code", "No Stubs/Patches", "Surgical Fixes", "Type Safety First", "Single Source of Truth", "Error Boundaries", "Performance Budget Enforcement", "Security by Design", "Test Coverage >85%", ]; constructor() { super("processor-pipeline", "3.1.0"); this.codexLoader = new CodexLoader(); this.tools = [ { name: "execute-pre-processors", description: "Run pre-execution processors on content with codex validation", inputSchema: { type: "object", properties: { content: { type: "string" }, context: { type: "object" }, validateCodex: { type: "boolean", default: true }, strictMode: { type: "boolean", default: false }, }, required: ["content"], }, }, { name: "execute-post-processors", description: "Run post-execution processors on results with compliance monitoring", inputSchema: { type: "object", properties: { content: { type: "string" }, results: { type: "object" }, enforceCompliance: { type: "boolean", default: true }, auditTrail: { type: "boolean", default: true }, }, required: ["content"], }, }, { name: "codex-validation", description: "Validate content against Universal Development Codex terms", inputSchema: { type: "object", properties: { content: { type: "string" }, terms: { type: "array", items: { type: "string" }, default: ["all"], }, strict: { type: "boolean", default: false }, }, required: ["content"], }, }, { name: "framework-compliance-check", description: "Check framework compliance and generate enforcement actions", inputSchema: { type: "object", properties: { content: { type: "string" }, operation: { type: "string" }, context: { type: "object" }, }, required: ["content", "operation"], }, }, ]; this.handlers = { "execute-pre-processors": async (args) => this.handlePreProcessors(args as PreProcessorArgs), "execute-post-processors": async (args) => this.handlePostProcessors(args as PostProcessorArgs), "codex-validation": async (args) => this.handleCodexValidation(args as CodexValidationArgs), "framework-compliance-check": async (args) => this.handleComplianceCheck(args as ComplianceCheckArgs), }; this.setupToolHandlers(); this.loadCodexRules(); // Server initialized silently - use frameworkLogger for important events } private async loadCodexRules(): Promise { try { if (await this.codexLoader.isAvailable()) { this.codexRules = await this.codexLoader.load(); await frameworkLogger.log( "mcps/processor-pipeline", "codex-rules-loaded", "success", { message: `Loaded ${this.codexRules.length} codex rules for MCP validation` } ); } } catch (error) { await frameworkLogger.log( "mcps/processor-pipeline", "codex-rules-load-failed", "warning", { message: `Failed to load codex rules: ${error instanceof Error ? error.message : String(error)}` } ); } } private async handlePreProcessors(args: PreProcessorArgs) { const content = args.content; const context = args.context || {}; const validateCodex = args.validateCodex !== false; const strictMode = args.strictMode || false; // Silent execution - no console output const results = { processed: content, validations: [] as string[], warnings: [] as string[], blocked: false, reason: "", }; try { // 1. Input sanitization results.processed = this.sanitizeInput(content); // 2. Codex validation (if enabled) if (validateCodex) { const codexResults = await this.validateAgainstCodex( results.processed, strictMode, ); results.validations.push(...codexResults.validations); results.warnings.push(...codexResults.warnings); if (codexResults.blocked) { results.blocked = true; results.reason = codexResults.reason; } } // 3. Context enrichment results.processed = this.enrichWithContext(results.processed, context); // 4. Security checks const securityResults = this.performSecurityChecks(results.processed); results.warnings.push(...securityResults.warnings); } catch (error) { results.blocked = true; results.reason = `Pre-processing error: ${error instanceof Error ? error.message : String(error)}`; } const response = `šŸ”„ Pre-Processor Results **Content Length:** ${results.processed.length} characters **Validations Passed:** ${results.validations.length} **Warnings:** ${results.warnings.length} ${results.warnings.length > 0 ? results.warnings.map((w: string) => `• āš ļø ${w}`).join("\n") : ""} **Status:** ${results.blocked ? `āŒ BLOCKED - ${results.reason}` : "āœ… APPROVED FOR EXECUTION"}`; return { content: [{ type: "text", text: response }], }; } private async handlePostProcessors(args: PostProcessorArgs) { const content = args.content; const results = args.results || {}; const enforceCompliance = args.enforceCompliance !== false; const auditTrail = args.auditTrail !== false; // Silent execution - no console output const postResults = { processed: content, compliance: [] as string[], auditEntries: [] as string[], recommendations: [] as string[], finalApproval: true, }; try { // 1. Result validation postResults.processed = this.validateResults(content, results); // 2. Compliance enforcement if (enforceCompliance) { const complianceResults = await this.enforceCompliance( postResults.processed, ); postResults.compliance.push(...complianceResults.compliance); postResults.recommendations.push(...complianceResults.recommendations); if (!complianceResults.approved) { postResults.finalApproval = false; } } // 3. Audit trail generation if (auditTrail) { postResults.auditEntries = this.generateAuditTrail( content, results, postResults, ); } // 4. Quality assurance const qaResults = this.performQualityAssurance(postResults.processed); postResults.recommendations.push(...qaResults.recommendations); } catch (error) { postResults.finalApproval = false; postResults.recommendations.push( `Post-processing error: ${error instanceof Error ? error.message : String(error)}`, ); } const response = `šŸ”„ Post-Processor Results **Final Approval:** ${postResults.finalApproval ? "āœ… APPROVED" : "āŒ REQUIRES REVIEW"} **Compliance Checks:** ${postResults.compliance.length} **Audit Entries:** ${postResults.auditEntries.length} **Recommendations:** ${postResults.recommendations.length} **Recommendations:** ${postResults.recommendations.length > 0 ? postResults.recommendations.map((r: string) => `• šŸ’” ${r}`).join("\n") : "None"} **Audit Summary:** ${postResults.auditEntries .slice(0, 3) .map((a) => `• šŸ“ ${a}`) .join("\n")}${postResults.auditEntries.length > 3 ? "\n• ..." : ""}`; return { content: [{ type: "text", text: response }], }; } private async handleCodexValidation(args: CodexValidationArgs) { const content = args.content; const terms = args.terms || ["all"]; const strict = args.strict || false; // Silent validation - no console output try { const validationResults = await this.validateAgainstCodex( content, strict, terms, ); return { content: [ { type: "text", text: `šŸ“š Codex Validation Results **Content Validated:** ${content.length} characters **Terms Checked:** ${terms.length === 1 && terms[0] === "all" ? "All 55-terms" : terms.length} **Compliance:** ${validationResults.compliance}% **Violations:** ${validationResults.violations.length} ${validationResults.violations.map((v: string) => `• āŒ ${v}`).join("\n") || "None"} **Warnings:** ${validationResults.warnings.length} ${validationResults.warnings.map((w: string) => `• āš ļø ${w}`).join("\n") || "None"} **Recommendations:** ${validationResults.recommendations.map((r: string) => `• šŸ’” ${r}`).join("\n") || "None"} **Status:** ${validationResults.blocked ? "āŒ BLOCKED" : "āœ… COMPLIANT"}`, }, ], }; } catch (error) { return { content: [ { type: "text", text: `āŒ Codex validation failed: ${error instanceof Error ? error.message : String(error)}`, }, ], }; } } private async handleComplianceCheck(args: ComplianceCheckArgs) { const content = args.content; const operation = args.operation; const context = args.context || {}; // Silent compliance check - no console output try { const complianceResults = await this.checkFrameworkCompliance( content, operation, context, ); return { content: [ { type: "text", text: `šŸ“‹ Framework Compliance Check **Operation:** ${operation} **Content Type:** ${this.detectContentType(content)} **Compliance Score:** ${complianceResults.score}/100 **Critical Issues:** ${complianceResults.criticalIssues.length} **Warnings:** ${complianceResults.warnings.length} **Critical Issues:** ${complianceResults.criticalIssues.map((i: string) => `• āŒ ${i}`).join("\n") || "None"} **Warnings:** ${complianceResults.warnings.map((w: string) => `• āš ļø ${w}`).join("\n") || "None"} **Enforcement Actions:** ${complianceResults.actions.map((a: string) => `• šŸ”§ ${a}`).join("\n") || "None required"} **Status:** ${complianceResults.approved ? "āœ… COMPLIANT" : "āŒ REQUIRES CORRECTION"}`, }, ], }; } catch (error) { return { content: [ { type: "text", text: `āŒ Compliance check failed: ${error instanceof Error ? error.message : String(error)}`, }, ], }; } } private sanitizeInput(content: string): string { // Basic input sanitization return content .replace( /)<[^<]*)*<\/script>/gi, "[SCRIPT REMOVED]", ) .replace(/javascript:/gi, "[JAVASCRIPT REMOVED]") .trim(); } private async validateAgainstCodex( content: string, strict: boolean, terms?: string[], ): Promise { const results: CodexValidationResult = { validations: [] as string[], warnings: [] as string[], violations: [] as string[], recommendations: [] as string[], compliance: 0, blocked: false, reason: "", }; // Use loaded codex rules if available, otherwise fall back to hardcoded terms if (this.codexRules.length > 0) { const termsToCheck = terms && terms.length > 0 && !terms.includes("all") ? terms : this.codexRules.map(r => r.name); let passed = 0; for (const rule of this.codexRules) { // Filter by requested terms if specified if (terms && terms.length > 0 && !terms.includes("all") && !terms.includes(rule.name)) { continue; } try { const context: RuleValidationContext = { newCode: content, operation: "write", files: [] }; const validationResult = await rule.validator(context); if (validationResult.passed) { passed++; results.validations.push(`${rule.name}: PASS`); } else { results.violations.push(`${rule.name}: ${validationResult.message}`); results.recommendations.push(...(validationResult.suggestions || [])); const isBlocking = rule.severity === "blocking" || rule.severity === "error"; if (strict || isBlocking) { results.blocked = true; results.reason = `Codex violation: ${rule.name}`; } } } catch (err) { results.warnings.push(`${rule.name}: Validation error - ${err instanceof Error ? err.message : String(err)}`); } } results.compliance = termsToCheck.length > 0 ? Math.round((passed / termsToCheck.length) * 100) : 100; return results; } // Fallback to hardcoded term checking (legacy behavior) const termsToCheck = terms && terms.length > 0 && !terms.includes("all") ? terms : this.codexTerms; let passed = 0; for (const term of termsToCheck) { const termResult = this.checkCodexTerm(content, term); if (termResult.passed) { passed++; results.validations.push(`${term}: PASS`); } else { results.violations.push(`${term}: ${termResult.reason}`); results.recommendations.push(termResult.recommendation); if (strict || termResult.critical) { results.blocked = true; results.reason = `Codex violation: ${term}`; } } } results.compliance = Math.round((passed / termsToCheck.length) * 100); return results; } private checkCodexTerm(content: string, term: string): CodexTermCheckResult { // Simplified codex term checking switch (term) { case "Type Safety First": return { passed: !content.includes("any") || content.includes("// @ts-ignore"), reason: "Type safety violations detected", recommendation: "Use proper TypeScript types instead of any", critical: false, }; case "No Stubs/Patches": return { passed: !content.includes("TODO") && !content.includes("FIXME"), reason: "Stub code or patches detected", recommendation: "Implement complete functionality or remove placeholder code", critical: true, }; case "Progressive Prod-Ready Code": return { passed: !content.includes("console.log") || content.includes("production"), reason: "Non-production ready code detected", recommendation: "Remove debug statements and ensure production readiness", critical: false, }; default: return { passed: true, reason: "", recommendation: "", critical: false, }; } } private enrichWithContext(content: string, context: Record): string { if (context.codex != null) { return `/* 0xRay Framework - Codex Compliant */\n${content}`; } return content; } private performSecurityChecks(content: string): SecurityCheckResult { const warnings = []; if (content.includes("eval(")) { warnings.push("Use of eval() detected - security risk"); } if (content.includes("innerHTML")) { warnings.push("Direct innerHTML manipulation detected - XSS risk"); } return { warnings }; } private validateResults(content: string, results: Record): string { if (results.error != null) { return `${content}\n/* ERROR: ${String(results.error)} */`; } return content; } private async enforceCompliance(content: string): Promise { const results = { compliance: [] as string[], recommendations: [] as string[], approved: true, }; // Check bundle size compliance (if applicable) if (content.includes("import") && content.length > 50000) { results.compliance.push( "Large module detected - consider code splitting", ); results.recommendations.push( "Implement lazy loading or split large modules", ); } // Check for performance issues if ( content.includes("for") && content.includes("length") && content.includes("i++") ) { results.recommendations.push( "Consider using for...of loops or array methods for better performance", ); } return results; } private generateAuditTrail( content: string, results: Record, postResults: PostProcessResult, ): string[] { const audit = [ `Operation completed at ${new Date().toISOString()}`, `Content length: ${content.length}`, `Processing time: ${String(results.duration ?? "unknown")}ms`, `Compliance status: ${postResults.finalApproval ? "approved" : "requires review"}`, ]; return audit; } private performQualityAssurance(content: string): QualityAssuranceResult { const recommendations = []; // Basic quality checks if (content.split("\n").length > 100) { recommendations.push( "Consider breaking down large files into smaller modules", ); } if (content.includes("function") && content.split("function").length > 10) { recommendations.push( "High function count - consider consolidating related functions", ); } return { recommendations }; } private detectContentType(content: string): string { if ( content.includes("function") || content.includes("const") || content.includes("let") ) { return "JavaScript/TypeScript"; } if (content.includes("class") || content.includes("def ")) { return "Python"; } if (content.includes("<") && content.includes(">")) { return "HTML/XML"; } return "Text"; } private async checkFrameworkCompliance( content: string, operation: string, context: Record, ): Promise { const results: FrameworkComplianceResult = { score: 100, criticalIssues: [] as string[], warnings: [] as string[], actions: [] as string[], approved: true, }; // Operation-specific compliance checks switch (operation) { case "code-review": if (!content.includes("function") && !content.includes("class")) { results.warnings.push( "No functions or classes detected in code review", ); } break; case "security-audit": if (!content.includes("auth") && !content.includes("security")) { results.warnings.push("Limited security-related content detected"); } break; case "testing": if (!content.includes("test") && !content.includes("spec")) { results.warnings.push("No test-related content detected"); } break; } // General compliance checks if (content.length > 10000) { results.score -= 10; results.warnings.push("Large content size - consider splitting"); } if (results.criticalIssues.length > 0) { results.approved = false; results.score -= 30; } return results; } } // Start the server if run directly if (import.meta.url === `file://${fs.realpathSync(process.argv[1]!)}`) { const server = new XrayProcessorPipelineServer(); server.run().catch((error) => frameworkLogger.log("mcps/processor-pipeline", "run", "error", { error: String(error) })); } export { XrayProcessorPipelineServer };