UNPKG

cognitive-framework-mcp-server

Version:

MCP Server for Advanced Cognitive Framework - Provides sophisticated AI reasoning capabilities through standardized protocol

572 lines (510 loc) 17.7 kB
#!/usr/bin/env node /** * Advanced Cognitive Framework MCP Server * Provides sophisticated AI reasoning capabilities through Model Context Protocol */ import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { FrameworkParser } from './parsers/framework-parser.js'; import { CognitiveReasoningEngine } from './engines/cognitive-reasoning-engine.js'; import { CognitiveRequest, CognitiveOptions } from './types/cognitive-framework.js'; import winston from 'winston'; import path from 'path'; // Configure logging const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json() ), transports: [ new winston.transports.File({ filename: 'cognitive-framework-mcp.log' }), new winston.transports.Console({ format: winston.format.simple() }) ] }); class CognitiveFrameworkMCPServer { private server: Server; private parser: FrameworkParser; private reasoningEngine: CognitiveReasoningEngine | null = null; private frameworkPath: string; constructor() { this.frameworkPath = process.env.FRAMEWORK_PATH || '/home/zrald/test/improve context'; this.parser = new FrameworkParser(this.frameworkPath); this.server = new Server( { name: 'cognitive-framework-mcp-server', version: '1.0.0', }, { capabilities: { resources: {}, tools: {}, prompts: {}, }, } ); this.setupHandlers(); } private setupHandlers(): void { // List available resources this.server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: 'cognitive-framework://framework', name: 'Advanced Cognitive Framework', description: 'Complete cognitive framework with meta-cognitive capabilities', mimeType: 'application/json', }, { uri: 'cognitive-framework://principles', name: 'Cognitive Principles', description: 'Core cognitive principles for reasoning', mimeType: 'application/json', }, { uri: 'cognitive-framework://heuristics', name: 'Cognitive Heuristics', description: 'Problem-solving heuristics and patterns', mimeType: 'application/json', }, { uri: 'cognitive-framework://workflows', name: 'Predefined Workflows', description: 'Available cognitive workflows', mimeType: 'application/json', }, { uri: 'cognitive-framework://stats', name: 'Framework Statistics', description: 'Framework usage and performance statistics', mimeType: 'application/json', } ], }; }); // Read specific resources this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => { const uri = request.params.uri; if (!this.reasoningEngine) { await this.initializeFramework(); } switch (uri) { case 'cognitive-framework://framework': return { contents: [ { uri, mimeType: 'application/json', text: JSON.stringify(this.parser.getFramework(), null, 2), }, ], }; case 'cognitive-framework://principles': return { contents: [ { uri, mimeType: 'application/json', text: JSON.stringify(this.parser.getFramework().principles, null, 2), }, ], }; case 'cognitive-framework://heuristics': return { contents: [ { uri, mimeType: 'application/json', text: JSON.stringify(this.parser.getFramework().heuristics, null, 2), }, ], }; case 'cognitive-framework://workflows': return { contents: [ { uri, mimeType: 'application/json', text: JSON.stringify(this.parser.getFramework().workflows, null, 2), }, ], }; case 'cognitive-framework://stats': const stats = { framework: this.parser.getFrameworkStats(), reasoning: this.reasoningEngine?.getFrameworkInfo(), cache: this.reasoningEngine?.getCacheStats() }; return { contents: [ { uri, mimeType: 'application/json', text: JSON.stringify(stats, null, 2), }, ], }; default: throw new Error(`Unknown resource: ${uri}`); } }); // List available tools this.server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: 'cognitive_reasoning', description: 'Apply advanced cognitive reasoning to analyze and solve problems', inputSchema: { type: 'object', properties: { input: { type: 'string', description: 'The problem or question to analyze', }, type: { type: 'string', enum: ['reasoning', 'workflow', 'context', 'analysis'], description: 'Type of cognitive processing to apply', default: 'reasoning', }, context: { type: 'object', description: 'Additional context information', }, options: { type: 'object', properties: { workflow: { type: 'string', enum: ['express', 'holistic', 'adaptive'], description: 'Workflow to use for processing', default: 'adaptive', }, complexity: { type: 'string', enum: ['express', 'holistic', 'adaptive'], description: 'Complexity level for processing', default: 'adaptive', }, domain: { type: 'string', description: 'Specific domain for specialized processing', }, confidenceThreshold: { type: 'number', minimum: 0, maximum: 1, description: 'Minimum confidence threshold', default: 0.7, }, biasChecking: { type: 'boolean', description: 'Enable systematic bias checking', default: true, }, creativityLevel: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Level of creative thinking to apply', default: 'medium', }, }, }, }, required: ['input'], }, }, { name: 'framework_info', description: 'Get information about the cognitive framework capabilities', inputSchema: { type: 'object', properties: { section: { type: 'string', enum: ['all', 'identity', 'principles', 'heuristics', 'workflows', 'stats'], description: 'Specific section to retrieve information about', default: 'all', }, }, }, }, { name: 'validate_framework', description: 'Validate the cognitive framework structure and integrity', inputSchema: { type: 'object', properties: {}, }, }, ], }; }); // Handle tool calls this.server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { if (!this.reasoningEngine) { await this.initializeFramework(); } switch (name) { case 'cognitive_reasoning': return await this.handleCognitiveReasoning(args); case 'framework_info': return await this.handleFrameworkInfo(args); case 'validate_framework': return await this.handleValidateFramework(); default: throw new Error(`Unknown tool: ${name}`); } } catch (error) { logger.error('Tool execution error:', error); throw error; } }); // List available prompts this.server.setRequestHandler(ListPromptsRequestSchema, async () => { return { prompts: [ { name: 'cognitive_analysis', description: 'Structured cognitive analysis prompt using the framework', arguments: [ { name: 'problem', description: 'The problem to analyze', required: true, }, { name: 'context', description: 'Additional context for the analysis', required: false, }, ], }, { name: 'bias_check', description: 'Systematic bias checking prompt', arguments: [ { name: 'decision', description: 'The decision or conclusion to check for biases', required: true, }, ], }, { name: 'uncertainty_assessment', description: 'Uncertainty quantification and confidence assessment', arguments: [ { name: 'assessment', description: 'The assessment to evaluate for uncertainty', required: true, }, ], }, ], }; }); // Handle prompt requests this.server.setRequestHandler(GetPromptRequestSchema, async (request) => { const { name, arguments: args } = request.params; switch (name) { case 'cognitive_analysis': return { description: 'Structured cognitive analysis using the Advanced Cognitive Framework', messages: [ { role: 'user', content: { type: 'text', text: this.generateCognitiveAnalysisPrompt(args?.problem || '', args?.context), }, }, ], }; case 'bias_check': return { description: 'Systematic bias checking protocol', messages: [ { role: 'user', content: { type: 'text', text: this.generateBiasCheckPrompt(args?.decision || ''), }, }, ], }; case 'uncertainty_assessment': return { description: 'Uncertainty quantification and confidence assessment', messages: [ { role: 'user', content: { type: 'text', text: this.generateUncertaintyAssessmentPrompt(args?.assessment || ''), }, }, ], }; default: throw new Error(`Unknown prompt: ${name}`); } }); } private async initializeFramework(): Promise<void> { try { logger.info('Initializing cognitive framework...'); const framework = await this.parser.parseFramework(); if (!this.parser.validateFramework()) { throw new Error('Framework validation failed'); } this.reasoningEngine = new CognitiveReasoningEngine(framework); logger.info('Cognitive framework initialized successfully'); } catch (error) { logger.error('Failed to initialize framework:', error); throw error; } } private async handleCognitiveReasoning(args: any): Promise<any> { if (!this.reasoningEngine) { throw new Error('Reasoning engine not initialized'); } const request: CognitiveRequest = { type: args.type || 'reasoning', input: args.input, context: args.context || {}, options: args.options as CognitiveOptions || {} }; const response = await this.reasoningEngine.processRequest(request); return { content: [ { type: 'text', text: JSON.stringify(response, null, 2), }, ], }; } private async handleFrameworkInfo(args: any): Promise<any> { const section = args?.section || 'all'; const framework = this.parser.getFramework(); let info: any; switch (section) { case 'identity': info = framework.identity; break; case 'principles': info = framework.principles; break; case 'heuristics': info = framework.heuristics; break; case 'workflows': info = framework.workflows; break; case 'stats': info = { framework: this.parser.getFrameworkStats(), reasoning: this.reasoningEngine?.getFrameworkInfo() }; break; default: info = framework; } return { content: [ { type: 'text', text: JSON.stringify(info, null, 2), }, ], }; } private async handleValidateFramework(): Promise<any> { const isValid = this.parser.validateFramework(); const stats = this.parser.getFrameworkStats(); return { content: [ { type: 'text', text: JSON.stringify({ valid: isValid, statistics: stats, timestamp: new Date().toISOString() }, null, 2), }, ], }; } private generateCognitiveAnalysisPrompt(problem: string, context?: string): string { return `Apply the Advanced Cognitive Framework to analyze the following problem: **Problem:** ${problem} ${context ? `**Context:** ${context}` : ''} Please apply the following cognitive approach: 1. **Meta-Cognitive Priming**: Engage in structured internal reasoning 2. **Optimal Complexity**: Balance minimum necessary complexity with robustness 3. **Bias Awareness**: Check for cognitive biases systematically 4. **Uncertainty Quantification**: Explicitly state confidence levels 5. **Multi-Perspective Reasoning**: Consider multiple viewpoints 6. **Predictive Intelligence**: Anticipate potential issues and consequences Provide your analysis with explicit reasoning steps, confidence assessment, and bias checks.`; } private generateBiasCheckPrompt(decision: string): string { return `Apply systematic bias checking to the following decision or conclusion: **Decision/Conclusion:** ${decision} Please check for the following biases: 1. **Confirmation Bias**: Have I sought information that contradicts this conclusion? 2. **Anchoring Bias**: Am I overly influenced by initial information? 3. **Availability Bias**: Am I overweighting recent or memorable examples? 4. **Overconfidence Bias**: What could I be wrong about? What are my key uncertainties? 5. **Cultural Bias**: Are my assumptions culturally or contextually biased? 6. **Alternative Perspectives**: How would someone with different background view this? Provide specific bias checks and mitigation strategies.`; } private generateUncertaintyAssessmentPrompt(assessment: string): string { return `Perform uncertainty quantification and confidence assessment for: **Assessment:** ${assessment} Please provide: 1. **Confidence Level**: Rate confidence from 0-100% with justification 2. **Key Uncertainties**: Identify main sources of uncertainty 3. **Evidence Quality**: Assess strength and reliability of supporting evidence 4. **Assumptions**: List critical assumptions and their validity 5. **Sensitivity Analysis**: How sensitive is the conclusion to key assumptions? 6. **Confidence Intervals**: Where applicable, provide ranges rather than point estimates Use probabilistic thinking and acknowledge limitations in knowledge or data.`; } async run(): Promise<void> { try { await this.initializeFramework(); const transport = new StdioServerTransport(); await this.server.connect(transport); logger.info('Cognitive Framework MCP Server started successfully'); } catch (error) { logger.error('Failed to start server:', error); process.exit(1); } } } // Start the server const server = new CognitiveFrameworkMCPServer(); server.run().catch((error) => { console.error('Server startup failed:', error); process.exit(1); });