cognitive-framework-mcp-server
Version:
MCP Server for Advanced Cognitive Framework - Provides sophisticated AI reasoning capabilities through standardized protocol
548 lines (470 loc) • 15.8 kB
text/typescript
/**
* Advanced Cognitive Framework Parser
* Parses the XML-based cognitive framework into structured TypeScript objects
*/
import { readFileSync } from 'fs';
import { parseString } from 'xml2js';
import { promisify } from 'util';
import {
CognitiveFramework,
CognitiveIdentity,
ContextManagement,
CognitivePrinciples,
CognitiveHeuristics,
CognitiveProtocols,
PredefinedWorkflows,
OperationalLoop,
Principle,
Capability,
Heuristic,
Protocol,
Workflow
} from '../types/cognitive-framework.js';
const parseXML = promisify(parseString);
export class FrameworkParser {
private frameworkPath: string;
private parsedFramework: CognitiveFramework | null = null;
constructor(frameworkPath: string) {
this.frameworkPath = frameworkPath;
}
/**
* Parse the cognitive framework from the XML file
*/
async parseFramework(): Promise<CognitiveFramework> {
try {
const xmlContent = readFileSync(this.frameworkPath, 'utf-8');
const parsed = await parseXML(xmlContent) as any;
const framework = parsed.AdvancedCognitiveFramework;
if (!framework) {
throw new Error('Invalid framework structure: AdvancedCognitiveFramework root not found');
}
this.parsedFramework = {
identity: this.parseCognitiveIdentity(framework.CognitiveIdentity?.[0]),
contextManagement: this.parseContextManagement(framework.ContextManagement?.[0]),
principles: this.parseCognitivePrinciples(framework.CognitivePrinciples?.[0]),
heuristics: this.parseCognitiveHeuristics(framework.CognitiveHeuristics?.[0]),
protocols: this.parseCognitiveProtocols(framework.CognitiveProtocols?.[0]),
workflows: this.parsePredefinedWorkflows(framework.PredefinedWorkflows?.[0]),
operationalLoop: this.parseOperationalLoop(framework.OperationalLoop?.[0])
};
return this.parsedFramework;
} catch (error) {
throw new Error(`Failed to parse cognitive framework: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Get the parsed framework (must call parseFramework first)
*/
getFramework(): CognitiveFramework {
if (!this.parsedFramework) {
throw new Error('Framework not parsed yet. Call parseFramework() first.');
}
return this.parsedFramework;
}
/**
* Parse cognitive identity section
*/
private parseCognitiveIdentity(identity: any): CognitiveIdentity {
if (!identity) {
throw new Error('CognitiveIdentity section not found');
}
return {
coreMandate: this.extractText(identity.CoreMandate?.[0]),
cognitiveTraits: this.parseCognitiveTraits(identity.CognitiveTraits?.[0]),
metaCognitiveCapabilities: this.parseMetaCognitiveCapabilities(identity.MetaCognitiveCapabilities?.[0]),
cognitiveLoadManagement: this.parseCognitiveLoadManagement(identity.CognitiveLoadManagement?.[0]),
learningFromCognition: this.parseLearningFromCognition(identity.LearningFromCognition?.[0])
};
}
/**
* Parse cognitive traits
*/
private parseCognitiveTraits(traits: any): any[] {
if (!traits?.Trait) return [];
return traits.Trait.map((trait: any) => ({
name: trait.$.name || '',
description: this.extractText(trait)
}));
}
/**
* Parse meta-cognitive capabilities
*/
private parseMetaCognitiveCapabilities(capabilities: any): any[] {
if (!capabilities?.Capability) return [];
return capabilities.Capability.map((cap: any) => ({
name: cap.$.name || '',
description: this.extractText(cap)
}));
}
/**
* Parse cognitive load management
*/
private parseCognitiveLoadManagement(management: any): any {
if (!management) return { principles: [], metrics: [] };
return {
principles: this.parsePrinciples(management.Principle),
metrics: this.parseMetrics(management.Metric)
};
}
/**
* Parse learning from cognition
*/
private parseLearningFromCognition(learning: any): any {
if (!learning) return { capabilities: [], repositories: [] };
return {
capabilities: this.parseCapabilities(learning.Capability),
repositories: this.parseRepositories(learning.Repository)
};
}
/**
* Parse context management section
*/
private parseContextManagement(contextMgmt: any): ContextManagement {
if (!contextMgmt) {
throw new Error('ContextManagement section not found');
}
return {
dynamicContextEngine: this.parseDynamicContextEngine(contextMgmt.DynamicContextEngine?.[0]),
contextSources: this.parseContextSources(contextMgmt.ContextSources?.[0]),
semanticContextClustering: this.parseSemanticContextClustering(contextMgmt.SemanticContextClustering?.[0]),
predictiveContexting: this.parsePredictiveContexting(contextMgmt.PredictiveContexting?.[0]),
contextQualityAssurance: this.parseContextQualityAssurance(contextMgmt.ContextQualityAssurance?.[0]),
adaptiveIntelligence: this.parseAdaptiveIntelligence(contextMgmt.AdaptiveIntelligence?.[0])
};
}
/**
* Parse dynamic context engine
*/
private parseDynamicContextEngine(engine: any): any {
if (!engine) return { principles: [] };
return {
principles: this.parsePrinciples(engine.Principle)
};
}
/**
* Parse context sources
*/
private parseContextSources(sources: any): any[] {
if (!sources?.Source) return [];
return sources.Source.map((source: any) => ({
name: source.$.name || '',
priority: source.$.priority || 'medium',
description: this.extractText(source)
}));
}
/**
* Parse semantic context clustering
*/
private parseSemanticContextClustering(clustering: any): any {
if (!clustering) return { capabilities: [], structures: [], algorithms: [] };
return {
capabilities: this.parseCapabilities(clustering.Capability),
structures: this.parseStructures(clustering.Structure),
algorithms: this.parseAlgorithms(clustering.Algorithm)
};
}
/**
* Parse predictive contexting
*/
private parsePredictiveContexting(contexting: any): any {
if (!contexting) return { capabilities: [], predictors: [] };
return {
capabilities: this.parseCapabilities(contexting.Capability),
predictors: this.parsePredictors(contexting.Predictor)
};
}
/**
* Parse context quality assurance
*/
private parseContextQualityAssurance(qua: any): any {
if (!qua) return { metrics: [], validators: [], optimizers: [] };
return {
metrics: this.parseMetrics(qua.Metric),
validators: this.parseValidators(qua.Validator),
optimizers: this.parseOptimizers(qua.Optimizer)
};
}
/**
* Parse adaptive intelligence
*/
private parseAdaptiveIntelligence(intelligence: any): any {
if (!intelligence) return { capabilities: [] };
return {
capabilities: this.parseCapabilities(intelligence.Capability)
};
}
/**
* Parse cognitive principles section
*/
private parseCognitivePrinciples(principles: any): CognitivePrinciples {
if (!principles) {
throw new Error('CognitivePrinciples section not found');
}
return {
principles: this.parsePrinciples(principles.Principle)
};
}
/**
* Parse cognitive heuristics section
*/
private parseCognitiveHeuristics(heuristics: any): CognitiveHeuristics {
if (!heuristics) {
throw new Error('CognitiveHeuristics section not found');
}
return {
heuristics: this.parseHeuristics(heuristics.Heuristic)
};
}
/**
* Parse cognitive protocols section
*/
private parseCognitiveProtocols(protocols: any): CognitiveProtocols {
if (!protocols) {
throw new Error('CognitiveProtocols section not found');
}
return {
protocols: this.parseProtocols(protocols.Protocol)
};
}
/**
* Parse predefined workflows section
*/
private parsePredefinedWorkflows(workflows: any): PredefinedWorkflows {
if (!workflows) {
throw new Error('PredefinedWorkflows section not found');
}
return {
workflows: this.parseWorkflows(workflows.Workflow)
};
}
/**
* Parse operational loop section
*/
private parseOperationalLoop(loop: any): OperationalLoop {
if (!loop) {
throw new Error('OperationalLoop section not found');
}
// Parse the operational loop steps from the text content
const content = this.extractText(loop);
const steps = this.parseOperationalSteps(content);
return { steps };
}
/**
* Helper method to parse principles
*/
private parsePrinciples(principles: any[]): Principle[] {
if (!principles) return [];
return principles.map(principle => ({
name: principle.$.name || '',
description: this.extractText(principle),
nuances: this.parseNuances(principle.Nuance),
examples: this.parseExamples(principle.Example)
}));
}
/**
* Helper method to parse capabilities
*/
private parseCapabilities(capabilities: any[]): Capability[] {
if (!capabilities) return [];
return capabilities.map(cap => ({
name: cap.$.name || '',
description: this.extractText(cap)
}));
}
/**
* Helper method to parse heuristics
*/
private parseHeuristics(heuristics: any[]): Heuristic[] {
if (!heuristics) return [];
return heuristics.map(heuristic => ({
name: heuristic.$.name || '',
facilitates: heuristic.$.facilitates || '',
relatedTo: heuristic.$['related-to'],
description: this.extractText(heuristic)
}));
}
/**
* Helper method to parse protocols
*/
private parseProtocols(protocols: any[]): Protocol[] {
if (!protocols) return [];
return protocols.map(protocol => ({
name: protocol.$.name || '',
purpose: this.extractText(protocol.Purpose?.[0]),
usage: this.extractText(protocol.Usage?.[0]),
actions: this.parseActions(protocol.Action),
outputFormat: this.extractText(protocol.OutputFormat?.[0])
}));
}
/**
* Helper method to parse workflows
*/
private parseWorkflows(workflows: any[]): Workflow[] {
if (!workflows) return [];
return workflows.map(workflow => ({
name: workflow.$.name || '',
tags: workflow.$.tags ? workflow.$.tags.split(',') : [],
purpose: this.extractText(workflow.Purpose?.[0]),
throughline: this.extractText(workflow.Throughline?.[0]),
adaptiveCapabilities: this.parseAdaptiveCapabilities(workflow.AdaptiveCapabilities?.[0]),
stages: this.parseStages(workflow.Stage),
steps: this.parseSteps(workflow.Step)
}));
}
/**
* Helper methods for parsing various components
*/
private parseNuances(nuances: any[]): string[] {
if (!nuances) return [];
return nuances.map(nuance => this.extractText(nuance));
}
private parseExamples(examples: any[]): string[] {
if (!examples) return [];
return examples.map(example => this.extractText(example));
}
private parseActions(actions: any[]): string[] {
if (!actions) return [];
return actions.map(action => this.extractText(action));
}
private parseAdaptiveCapabilities(capabilities: any): any {
if (!capabilities) return { capabilities: [] };
return {
capabilities: this.parseCapabilities(capabilities.Capability)
};
}
private parseStages(stages: any[]): any[] {
if (!stages) return [];
return stages.map(stage => ({
name: stage.$.name || '',
objective: this.extractText(stage.Objective?.[0]),
guidance: this.extractText(stage.Guidance?.[0]),
steps: this.parseSteps(stage.Step)
}));
}
private parseSteps(steps: any[]): any[] {
if (!steps) return [];
return steps.map(step => ({
id: step.$.id || '',
description: this.extractText(step)
}));
}
private parseOperationalSteps(content: string): any[] {
// Parse numbered steps from the operational loop content
const steps: any[] = [];
const lines = content.split('\n').filter(line => line.trim());
let currentStep = 1;
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.match(/^\d+\./)) {
steps.push({
number: currentStep++,
description: trimmed,
details: []
});
} else if (trimmed.startsWith('*') || trimmed.startsWith('-')) {
if (steps.length > 0) {
steps[steps.length - 1].details.push(trimmed);
}
}
}
return steps;
}
// Additional helper methods for parsing other components
private parseMetrics(metrics: any[]): any[] {
if (!metrics) return [];
return metrics.map(metric => ({
name: metric.$.name || '',
description: this.extractText(metric)
}));
}
private parseRepositories(repositories: any[]): any[] {
if (!repositories) return [];
return repositories.map(repo => ({
name: repo.$.name || '',
description: this.extractText(repo)
}));
}
private parseStructures(structures: any[]): any[] {
if (!structures) return [];
return structures.map(structure => ({
name: structure.$.name || '',
description: this.extractText(structure)
}));
}
private parseAlgorithms(algorithms: any[]): any[] {
if (!algorithms) return [];
return algorithms.map(algorithm => ({
name: algorithm.$.name || '',
description: this.extractText(algorithm)
}));
}
private parsePredictors(predictors: any[]): any[] {
if (!predictors) return [];
return predictors.map(predictor => ({
name: predictor.$.name || '',
description: this.extractText(predictor)
}));
}
private parseValidators(validators: any[]): any[] {
if (!validators) return [];
return validators.map(validator => ({
name: validator.$.name || '',
description: this.extractText(validator)
}));
}
private parseOptimizers(optimizers: any[]): any[] {
if (!optimizers) return [];
return optimizers.map(optimizer => ({
name: optimizer.$.name || '',
description: this.extractText(optimizer)
}));
}
/**
* Extract text content from XML node, handling both string and object cases
*/
private extractText(node: any): string {
if (!node) return '';
if (typeof node === 'string') return node.trim();
if (node._) return node._.trim();
if (typeof node === 'object' && node.toString) return node.toString().trim();
return '';
}
/**
* Validate the parsed framework structure
*/
validateFramework(): boolean {
if (!this.parsedFramework) return false;
// Check required sections
const requiredSections = [
'identity',
'contextManagement',
'principles',
'heuristics',
'protocols',
'workflows',
'operationalLoop'
];
for (const section of requiredSections) {
if (!this.parsedFramework[section as keyof CognitiveFramework]) {
console.warn(`Missing required section: ${section}`);
return false;
}
}
return true;
}
/**
* Get framework statistics
*/
getFrameworkStats(): Record<string, number> {
if (!this.parsedFramework) return {};
return {
cognitiveTraits: this.parsedFramework.identity.cognitiveTraits.length,
metaCognitiveCapabilities: this.parsedFramework.identity.metaCognitiveCapabilities.length,
principles: this.parsedFramework.principles.principles.length,
heuristics: this.parsedFramework.heuristics.heuristics.length,
protocols: this.parsedFramework.protocols.protocols.length,
workflows: this.parsedFramework.workflows.workflows.length,
operationalSteps: this.parsedFramework.operationalLoop.steps.length
};
}
}