Skip to main content
Glama

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
NameRequiredDescriptionDefault
typeYesType of memory to create
contentYesThe main content/text of the memory
embeddingYesVector embedding for the memory content
importanceNoImportance score (0.0 to 1.0)
metadataNoType-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) }] };
  • 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;
      }
    }
  • 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")),
    ]);
  • 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],

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it states this is a creation operation, it doesn't mention whether this requires specific permissions, what happens on success/failure, whether duplicates are allowed, or any rate limits. For a mutation tool with zero annotation coverage, this leaves significant behavioral gaps for an AI agent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that gets straight to the point. It's appropriately sized for the tool's complexity and front-loads the essential information. There's no wasted language or unnecessary elaboration.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mutation tool with 5 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't address behavioral aspects like error conditions, permission requirements, or what the tool returns. While the schema covers parameters well, the description fails to provide the broader operational context needed for effective tool use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 5 parameters thoroughly. The description adds minimal value beyond what's in the schema - it mentions 'optional type-specific metadata' which aligns with the schema's metadata parameter description. No additional semantic context is provided about how parameters interact or their practical significance.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('create a new memory') and resource ('memory'), making the purpose immediately understandable. It distinguishes this from sibling tools like 'create_memory_cluster' or 'create_working_memory' by focusing on individual memory creation rather than clusters or working memory. However, it doesn't explicitly differentiate from 'create_memory_relationship', which might create some ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With sibling tools like 'create_memory_cluster', 'create_working_memory', and 'create_memory_relationship', there's no indication of which tool to choose for different scenarios. The mention of 'optional type-specific metadata' hints at some context but doesn't constitute usage guidelines.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.