mongodb-memory-bank-mcp-v2
Version:
MongoDB-powered Memory Bank MCP server with hybrid search capabilities for AI assistants
182 lines (169 loc) ⢠7 kB
JavaScript
import { join } from 'path';
import { readFileSync, existsSync } from 'fs';
import { SyncToolSchema } from '../types/memory.js';
import { getMemoryCollection } from '../db/connection.js';
import { generateEmbeddings } from '../embeddings/voyage.js';
import { logger } from '../utils/logger.js';
export async function syncTool(args) {
try {
const params = SyncToolSchema.parse(args);
const projectPath = params.projectPath || process.cwd();
// Read project config
const configPath = join(projectPath, '.memory-bank', 'config.json');
if (!existsSync(configPath)) {
return {
content: [
{
type: 'text',
text: 'Memory bank not initialized for this project. Run memory_bank/init first.',
},
],
};
}
const config = JSON.parse(readFileSync(configPath, 'utf-8'));
const collection = getMemoryCollection();
// Find documents that need embedding generation
const query = params.forceRegenerate
? { projectId: config.projectId }
: {
projectId: config.projectId,
contentVector: { $exists: false },
};
const documents = await collection.find(query).toArray();
if (documents.length === 0) {
return {
content: [
{
type: 'text',
text: `ā
All memory files are already synced!
Your MongoDB-powered Memory Bank is READY for action:
- š Hybrid search is active
- š§ Vector embeddings are current
- š Text indexes are built
š” QUICK ACTIONS:
1. Search your knowledge: memory_bank/search --query "any topic"
2. Find patterns: memory_bank/search --query "pattern"
3. Update memories: memory_bank/update --fileName "activeContext.md"
š Force regeneration? Use: memory_bank/sync --forceRegenerate true`,
},
],
};
}
logger.info(`Syncing ${documents.length} memory files for project: ${config.projectId}`);
// Batch generate embeddings
const contents = documents.map((doc) => doc.content);
const embeddings = await generateEmbeddings(contents);
// Update documents with embeddings
const bulkOps = documents.map((doc, index) => ({
updateOne: {
filter: { _id: doc._id },
update: {
$set: {
contentVector: embeddings[index],
'metadata.lastUpdated': new Date(),
},
},
},
}));
const result = await collection.bulkWrite(bulkOps);
logger.info(`Sync completed: ${result.modifiedCount} documents updated`);
// Ensure search indexes exist
try {
// Check for vector search index
const vectorIndexes = await collection.listSearchIndexes('memory_vector_index').toArray();
if (vectorIndexes.length === 0) {
await collection.createSearchIndex({
name: 'memory_vector_index',
type: 'vectorSearch',
definition: {
fields: [
{
type: 'vector',
numDimensions: 1024,
path: 'contentVector',
similarity: 'cosine',
},
{
type: 'filter',
path: 'projectId',
},
],
},
});
logger.info('Vector search index created');
}
// Check for Atlas Search index for text search
const textIndexes = await collection.listSearchIndexes('memory_text_index').toArray();
if (textIndexes.length === 0) {
await collection.createSearchIndex({
name: 'memory_text_index',
type: 'search',
definition: {
mappings: {
dynamic: true,
fields: {
content: {
type: 'string',
analyzer: 'lucene.standard',
},
fileName: {
type: 'string',
analyzer: 'lucene.standard',
},
projectId: {
type: 'string',
},
},
},
},
});
logger.info('Atlas Search index for text search created');
}
}
catch (error) {
logger.debug('Search index creation error (may already exist):', error);
}
return {
content: [
{
type: 'text',
text: `⨠Memory Bank Synchronized - MongoDB Magic Activated!
š SYNC STATISTICS:
- Files synced: ${documents.length}
- Embeddings generated: ${result.modifiedCount}
- Vector model: Voyage AI 'voyage-3' (1024 dimensions)
- Storage: MongoDB Atlas with native vector support
š YOUR KNOWLEDGE IS NOW SUPERCHARGED!
š MongoDB $rankFusion Hybrid Search - The CROWN JEWEL:
- š§ 70% Semantic Understanding (what concepts mean)
- š 30% Keyword Matching (exact words you type)
- š Reciprocal Rank Fusion combines both intelligently!
š WHAT YOU CAN DO NOW:
1. š DISCOVER PATTERNS:
memory_bank/search --query "authentication" --searchType "hybrid"
ā Finds BOTH similar concepts AND exact matches!
2. šÆ FIND PATTERNS:
memory_bank/search --query "user"
ā Discovers all user-related patterns instantly!
3. š EXPLORE YOUR KNOWLEDGE:
memory_bank/search --query "validation gates"
ā See how Context Engineering patterns connect!
š MONGODB ADVANTAGE - ONE Database for EVERYTHING:
- š Operational data (your memory files)
- š§ Vector embeddings (semantic understanding)
- š Full-text search (keyword matching)
- š Version history (track changes)
- š References (auto-discovered connections)
š” PRO TIP: The more you use Memory Bank, the smarter it gets!
Every search, every blueprint, every update makes future development FASTER!
š NO EXTERNAL VECTOR DB NEEDED - MongoDB does it ALL!`,
},
],
};
}
catch (error) {
logger.error('Sync tool error:', error);
throw error;
}
}
//# sourceMappingURL=sync.js.map