create_memory
Store structured AI memories with vector embeddings, supporting episodic, semantic, procedural, or strategic types for persistent knowledge retention and retrieval.
Instructions
Create a new memory with optional type-specific metadata
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| type | Yes | Type of memory to create | |
| content | Yes | The main content/text of the memory | |
| embedding | Yes | Vector embedding for the memory content | |
| importance | No | Importance score (0.0 to 1.0) | |
| metadata | No | Type-specific metadata (action_taken, context, confidence, etc.) |
Implementation Reference
- mcp.js:29-60 (registration)Tool registration and input schema definition for create_memory. Defines the tool name, description, and JSON schema with properties for type, content, embedding, importance, and metadata.
name: "create_memory", description: "Create a new memory with optional type-specific metadata", inputSchema: { type: "object", properties: { type: { type: "string", enum: ["episodic", "semantic", "procedural", "strategic"], description: "Type of memory to create" }, content: { type: "string", description: "The main content/text of the memory" }, embedding: { type: "array", items: { type: "number" }, description: "Vector embedding for the memory content" }, importance: { type: "number", description: "Importance score (0.0 to 1.0)", default: 0.0 }, metadata: { type: "object", description: "Type-specific metadata (action_taken, context, confidence, etc.)", default: {} } }, required: ["type", "content", "embedding"] } - mcp.js:536-544 (handler)MCP request handler for create_memory. Extracts arguments and calls memoryManager.createMemory() with type, content, embedding, importance, and metadata, then returns the created memory as JSON.
case "create_memory": const memory = await memoryManager.createMemory( args.type, args.content, args.embedding, args.importance || 0.0, args.metadata || {} ); return { content: [{ type: "text", text: JSON.stringify(memory, null, 2) }] }; - src/memory-manager.js:20-90 (handler)Core implementation of createMemory method in MemoryManager class. Handles transaction to insert main memory record and type-specific details (episodic, semantic, procedural, strategic) with their respective metadata fields.
async createMemory(type, content, embedding, importance = 0.0, metadata = {}) { try { // Start transaction const result = await this.db.transaction(async (tx) => { // Insert main memory record const [memory] = await tx.insert(schema.memories).values({ type, content, embedding: embedding, importance, decayRate: metadata.decayRate || 0.01 }).returning(); // Insert type-specific details switch (type) { case 'episodic': await tx.insert(schema.episodicMemories).values({ memoryId: memory.id, actionTaken: metadata.action_taken || null, context: metadata.context || null, result: metadata.result || null, emotionalValence: metadata.emotional_valence || 0.0, eventTime: metadata.event_time || new Date(), verificationStatus: metadata.verification_status || null }); break; case 'semantic': await tx.insert(schema.semanticMemories).values({ memoryId: memory.id, confidence: metadata.confidence || 0.8, category: metadata.category || [], relatedConcepts: metadata.related_concepts || [], sourceReferences: metadata.source_references || null, contradictions: metadata.contradictions || null }); break; case 'procedural': await tx.insert(schema.proceduralMemories).values({ memoryId: memory.id, steps: metadata.steps || {}, prerequisites: metadata.prerequisites || {}, successCount: metadata.success_count || 0, totalAttempts: metadata.total_attempts || 0, failurePoints: metadata.failure_points || null }); break; case 'strategic': await tx.insert(schema.strategicMemories).values({ memoryId: memory.id, patternDescription: metadata.pattern_description || content, confidenceScore: metadata.confidence_score || 0.7, supportingEvidence: metadata.supporting_evidence || null, successMetrics: metadata.success_metrics || null, adaptationHistory: metadata.adaptation_history || null, contextApplicability: metadata.context_applicability || null }); break; } return memory; }); return result; } catch (error) { console.error('Error creating memory:', error); throw error; } } - src/db/schema.js:9-27 (schema)Main memories table schema definition. Defines the core memory structure with id, type, status, content, embedding, importance, access tracking, and relevance score calculation.
export const memories = pgTable("memories", { id: uuid().defaultRandom().primaryKey().notNull(), createdAt: timestamp("created_at", { withTimezone: true, mode: 'string' }).default(sql`CURRENT_TIMESTAMP`), updatedAt: timestamp("updated_at", { withTimezone: true, mode: 'string' }).default(sql`CURRENT_TIMESTAMP`), type: memoryType().notNull(), status: memoryStatus().default('active'), content: text().notNull(), embedding: vector({ dimensions: 1536 }).notNull(), importance: doublePrecision().default(0), accessCount: integer("access_count").default(0), lastAccessed: timestamp("last_accessed", { withTimezone: true, mode: 'string' }), decayRate: doublePrecision("decay_rate").default(0.01), relevanceScore: doublePrecision("relevance_score").generatedAlwaysAs(sql`(importance * exp(((- decay_rate) * age_in_days(created_at))))`), }, (table) => [ index("memories_content_idx").using("gin", table.content.asc().nullsLast().op("gin_trgm_ops")), index("memories_embedding_idx").using("ivfflat", table.embedding.asc().nullsLast().op("vector_cosine_ops")), index("memories_relevance_score_idx").using("btree", table.relevanceScore.desc().nullsFirst().op("float8_ops")).where(sql`(status = 'active'::memory_status)`), index("memories_status_idx").using("btree", table.status.asc().nullsLast().op("enum_ops")), ]); - src/db/schema.js:58-140 (schema)Type-specific memory table schemas (episodic, semantic, procedural, strategic). Each extends the main memory with specialized metadata fields like emotional valence, confidence, success metrics, etc.
export const episodicMemories = pgTable("episodic_memories", { memoryId: uuid("memory_id").primaryKey().notNull(), actionTaken: jsonb("action_taken"), context: jsonb(), result: jsonb(), emotionalValence: doublePrecision("emotional_valence"), verificationStatus: boolean("verification_status"), eventTime: timestamp("event_time", { withTimezone: true, mode: 'string' }), }, (table) => [ foreignKey({ columns: [table.memoryId], foreignColumns: [memories.id], name: "episodic_memories_memory_id_fkey" }), check("valid_emotion", sql`(emotional_valence >= ('-1'::integer)::double precision) AND (emotional_valence <= (1)::double precision)`), ]); export const clusterActivationHistory = pgTable("cluster_activation_history", { id: uuid().defaultRandom().primaryKey().notNull(), clusterId: uuid("cluster_id"), activatedAt: timestamp("activated_at", { withTimezone: true, mode: 'string' }).default(sql`CURRENT_TIMESTAMP`), activationContext: text("activation_context"), activationStrength: doublePrecision("activation_strength"), coActivatedClusters: uuid("co_activated_clusters").array(), resultingInsights: jsonb("resulting_insights"), }, (table) => [ foreignKey({ columns: [table.clusterId], foreignColumns: [memoryClusters.id], name: "cluster_activation_history_cluster_id_fkey" }), ]); export const semanticMemories = pgTable("semantic_memories", { memoryId: uuid("memory_id").primaryKey().notNull(), confidence: doublePrecision().notNull(), lastValidated: timestamp("last_validated", { withTimezone: true, mode: 'string' }), sourceReferences: jsonb("source_references"), contradictions: jsonb(), category: text().array(), relatedConcepts: text("related_concepts").array(), }, (table) => [ foreignKey({ columns: [table.memoryId], foreignColumns: [memories.id], name: "semantic_memories_memory_id_fkey" }), check("valid_confidence", sql`(confidence >= (0)::double precision) AND (confidence <= (1)::double precision)`), ]); export const proceduralMemories = pgTable("procedural_memories", { memoryId: uuid("memory_id").primaryKey().notNull(), steps: jsonb().notNull(), prerequisites: jsonb(), successCount: integer("success_count").default(0), totalAttempts: integer("total_attempts").default(0), successRate: doublePrecision("success_rate").generatedAlwaysAs(sql` CASE WHEN (total_attempts > 0) THEN ((success_count)::double precision / (total_attempts)::double precision) ELSE (0)::double precision END`), averageDuration: interval("average_duration"), failurePoints: jsonb("failure_points"), }, (table) => [ foreignKey({ columns: [table.memoryId], foreignColumns: [memories.id], name: "procedural_memories_memory_id_fkey" }), ]); export const strategicMemories = pgTable("strategic_memories", { memoryId: uuid("memory_id").primaryKey().notNull(), patternDescription: text("pattern_description").notNull(), supportingEvidence: jsonb("supporting_evidence"), confidenceScore: doublePrecision("confidence_score"), successMetrics: jsonb("success_metrics"), adaptationHistory: jsonb("adaptation_history"), contextApplicability: jsonb("context_applicability"), }, (table) => [ foreignKey({ columns: [table.memoryId], foreignColumns: [memories.id],