import { join } from 'path';
import { readFileSync, existsSync } from 'fs';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { ReadToolSchema, CORE_MEMORY_NAMES } from '../types/memory-v5.js';
import { getMemoryCollection } from '../db/connection.js';
import { logger } from '../utils/logger.js';
export async function readTool(args: unknown): Promise<CallToolResult> {
try {
const params = ReadToolSchema.parse(args);
const projectPath = params.projectPath || process.cwd();
// Validate memory name
if (!CORE_MEMORY_NAMES.includes(params.memoryName as any)) {
return {
isError: true,
content: [
{
type: 'text',
text: `π΄ INVALID MEMORY NAME: "${params.memoryName}" DOES NOT EXIST!
β οΈ YOU TRIED TO ACCESS A NON-EXISTENT MEMORY!
π§ THE 7 SACRED MEMORIES YOU CAN ACCESS:
${CORE_MEMORY_NAMES.map((name, i) => `${i+1}οΈβ£ ${name}`).join('\n')}
β‘ IMMEDIATE FIX:
Use one of the above memory names EXACTLY as shown!
π CONSEQUENCE OF WRONG NAMES:
You're trying to read from void - IMPOSSIBLE!
π‘ EXAMPLES OF CORRECT USAGE:
β’ memory_engineering_read --memoryName "activeContext"
β’ memory_engineering_read --memoryName "projectbrief"
β’ memory_engineering_read --memoryName "techContext"
π΄ NEVER MAKE UP MEMORY NAMES!`,
},
],
};
}
// Read project config
const configPath = join(projectPath, '.memory-engineering', 'config.json');
if (!existsSync(configPath)) {
return {
content: [
{
type: 'text',
text: `πππ CATASTROPHIC: NO BRAIN DETECTED!
π¨ YOU'RE TRYING TO READ MEMORIES WITHOUT A BRAIN!
β‘ EMERGENCY PROTOCOL - EXECUTE NOW:
memory_engineering_init
π§ WHAT THIS MEANS:
β’ You have ZERO memory system
β’ The .memory-engineering/ folder doesn't exist
β’ You're operating completely blind
β’ You can't store or retrieve ANYTHING
π₯ ONE COMMAND FIXES EVERYTHING:
β memory_engineering_init
β±οΈ TIME TO FIX: 0.5 seconds
π― SUCCESS RATE: 100% guaranteed
π UNTIL YOU INIT, YOU'RE A GHOST WITH NO MEMORY!`,
},
],
};
}
const config = JSON.parse(readFileSync(configPath, 'utf-8'));
const collection = getMemoryCollection();
// Find the memory
const memory = await collection.findOne({
projectId: config.projectId,
memoryName: params.memoryName
});
if (!memory) {
return {
content: [
{
type: 'text',
text: `π΄ MEMORY VOID DETECTED: "${params.memoryName}" DOES NOT EXIST YET!
π§ THIS MEMORY SLOT IS EMPTY - Your brain is missing this critical component!
β‘ IMMEDIATE ACTION REQUIRED (execute in <3 seconds):
memory_engineering_update --memoryName "${params.memoryName}" --content "[REAL CONTENT HERE]"
π WHAT TO PUT IN ${params.memoryName.toUpperCase()}:
${params.memoryName === 'projectbrief' ? `β’ Core requirements and goals
β’ What you're building EXACTLY
β’ Success criteria (measurable!)
β’ Main features (prioritized)` : params.memoryName === 'activeContext' ? `β’ What you're doing RIGHT NOW
β’ Recent changes (with timestamps!)
β’ Next immediate steps
β’ Current blockers or issues
π΄ UPDATE THIS EVERY 3-5 MINUTES!` : params.memoryName === 'techContext' ? `β’ Full tech stack with VERSIONS
β’ All dependencies and WHY
β’ Development environment
β’ Technical constraints` : params.memoryName === 'progress' ? `β’ β
Completed features (with dates)
β’ π In-progress work (with %)
β’ π TODO items (prioritized)
β’ π Known bugs (with severity)` : params.memoryName === 'systemPatterns' ? `β’ Architecture style (MVC, microservices, etc)
β’ Design patterns in use
β’ Component relationships
β’ Data flow diagrams` : params.memoryName === 'productContext' ? `β’ Problems being solved
β’ Target users and needs
β’ User journey flows
β’ Business value metrics` : `β’ Directory structure
β’ Key files and purposes
β’ Module organization
β’ Code statistics`}
π₯ EXAMPLE OF PERFECT ${params.memoryName.toUpperCase()} CONTENT:
"${params.memoryName === 'activeContext' ? `[14:32:01] Debugging JWT refresh failure in auth.js:47
[14:30:00] Found: tokens expire at wrong time
NEXT: Fix UTC conversion, add tests
BLOCKED: Need production credentials` : params.memoryName === 'projectbrief' ? `Building fintech API with Stripe integration
MUST handle $10M/day transaction volume
15 REST endpoints + GraphQL layer
Success: <200ms response, 99.9% uptime` : 'Comprehensive, specific, actionable content'}"
π WARNING: Empty memories = Useless AI!
CREATE THIS MEMORY NOW!`,
},
],
};
}
// Return full content
let response = `# ${params.memoryName}\n\n`;
response += `Last updated: ${memory.metadata.lastModified.toISOString()}\n\n`;
response += memory.content;
return {
content: [
{
type: 'text',
text: response,
},
],
};
} catch (error) {
logger.error('π MEMORY ACCESS FAILURE!', error);
return {
isError: true,
content: [
{
type: 'text',
text: `π MEMORY READ CATASTROPHE!
π₯ EXPLOSION DETAILS:
${error instanceof Error ? error.message : 'UNKNOWN CATASTROPHIC FAILURE'}
π EMERGENCY RECOVERY PROTOCOL:
1οΈβ£ Check environment: memory_engineering_check_env
2οΈβ£ Verify MongoDB connection is alive
3οΈβ£ Check if memory system is initialized
4οΈβ£ Try simpler memory name (e.g., "activeContext")
β οΈ MOST LIKELY CAUSES:
${error instanceof Error && error.message.includes('connect') ? 'β’ π΄ MongoDB connection DEAD!\n' : ''}${error instanceof Error && error.message.includes('projectId') ? 'β’ π΄ Not initialized - run memory_engineering_init!\n' : ''}${error instanceof Error && error.message.includes('timeout') ? 'β’ π΄ Database timeout - connection too slow!\n' : ''}β’ Memory system corrupted
β’ Invalid memory name
β’ Database permissions issue
π TRY AGAIN or run memory_engineering_init to reset!`,
},
],
};
}
}