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],
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. It mentions 'optional type-specific metadata' but doesn't disclose critical behavioral traits such as whether this is a write operation (implied by 'Create'), what permissions are needed, if it's idempotent, or what happens on failure. For a creation tool with no annotation coverage, this is a significant gap in transparency.

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 front-loads the core action ('Create a new memory') and adds a concise qualifier ('with optional type-specific metadata'). There's no wasted verbiage, making it appropriately sized and easy to parse.

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?

Given the complexity of a creation tool with 5 parameters, no annotations, and no output schema, the description is incomplete. It lacks information on behavioral aspects (e.g., side effects, error handling) and doesn't explain what the tool returns, leaving the agent with insufficient context for reliable 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 fully documents all parameters. The description adds minimal value by hinting at 'optional type-specific metadata', but this is already covered in the schema's description for the 'metadata' parameter. With high schema coverage, the baseline is 3, as the description doesn't provide additional semantic context beyond what's in the structured data.

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 verb ('Create') and resource ('memory') with the qualifier 'new', making the purpose evident. However, it doesn't distinguish this tool from sibling tools like 'create_memory_cluster' or 'create_working_memory', which also create memory-related entities, so it doesn't fully differentiate from alternatives.

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 many sibling tools like 'create_memory_cluster' and 'create_working_memory', there's no indication of context, prerequisites, or exclusions, leaving the agent to guess based on tool names alone.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/randyandrade/agi-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server