Skip to main content
Glama

create_entities

Generate new entities, add observations, optional embeddings, and define relations for efficient knowledge storage and vector search within the MCP Memory LibSQL system.

Instructions

Create new entities with observations and optional embeddings

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entitiesYes

Implementation Reference

  • Core handler function that creates or updates entities with observations, generates embeddings if needed, manages database transactions, and handles relations.
    public static async createEntities(entities: EntityCreateParams[]): Promise<void> {
      try {
        const client = databaseService.getClient();
        
        for (const entity of entities) {
          // Validate entity
          if (!entity.name || typeof entity.name !== 'string' || entity.name.trim() === '') {
            throw new ValidationError('Entity name must be a non-empty string');
          }
    
          if (!entity.entityType || typeof entity.entityType !== 'string' || entity.entityType.trim() === '') {
            throw new ValidationError(`Invalid entity type for entity "${entity.name}"`);
          }
    
          if (!Array.isArray(entity.observations) || entity.observations.length === 0) {
            throw new ValidationError(`Entity "${entity.name}" must have at least one observation`);
          }
    
          // Generate embedding if not provided
          let embedding = entity.embedding;
          if (!embedding) {
            try {
              logger.info(`Generating embedding for entity: ${entity.name}`);
              const text = entity.observations.join(' ');
              embedding = await embeddingService.generateEmbedding(text);
            } catch (error) {
              logger.error(`Failed to generate embedding for entity "${entity.name}":`, error);
            }
          }
    
          // Use a transaction for entity and observations
          await databaseService.transaction(async (txn) => {
            const vectorString = arrayToVectorString(embedding);
            
            // First try to update
            const result = await txn.execute({
              sql: 'UPDATE entities SET entity_type = ?, embedding = vector32(?) WHERE name = ?',
              args: [entity.entityType, vectorString, entity.name],
            });
    
            // If no rows affected, do insert
            if (result.rowsAffected === 0) {
              await txn.execute({
                sql: 'INSERT INTO entities (name, entity_type, embedding) VALUES (?, ?, vector32(?))',
                args: [entity.name, entity.entityType, vectorString],
              });
            }
    
            // Clear old observations
            await txn.execute({
              sql: 'DELETE FROM observations WHERE entity_name = ?',
              args: [entity.name],
            });
    
            // Add new observations
            for (const observation of entity.observations) {
              await txn.execute({
                sql: 'INSERT INTO observations (entity_name, content) VALUES (?, ?)',
                args: [entity.name, observation],
              });
            }
          });
    
          // Handle relations if provided
          if (entity.relations && entity.relations.length > 0) {
            const relations = entity.relations.map(rel => ({
              from: entity.name,
              to: rel.target,
              relationType: rel.relationType
            }));
            
            await EntityService.createRelations(relations);
          }
        }
      } catch (error) {
        if (error instanceof Error && error.message.includes('SQLITE_CONSTRAINT')) {
          throw parseDatabaseError(error);
        }
        
        throw new DatabaseError(
          `Entity operation failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  • Input schema for the create_entities tool defining the expected structure of the entities array parameter.
    inputSchema: {
      type: 'object',
      properties: {
        entities: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              name: {
                type: 'string',
              },
              entityType: {
                type: 'string',
              },
              observations: {
                type: 'array',
                items: {
                  type: 'string',
                },
              },
              embedding: {
                type: 'array',
                items: {
                  type: 'number',
                },
                description: 'Optional vector embedding for similarity search',
              },
              relations: {
                type: 'array',
                items: {
                  type: 'object',
                  properties: {
                    target: {
                      type: 'string',
                    },
                    relationType: {
                      type: 'string',
                    },
                  },
                  required: [
                    'target',
                    'relationType',
                  ],
                },
                description: 'Optional relations to create with this entity',
              },
            },
            required: [
              'name',
              'entityType',
              'observations',
            ],
          },
        },
      },
      required: [
        'entities',
      ],
    },
  • src/index.ts:76-138 (registration)
    Tool registration in the listTools response, including name, description, and input schema.
    {
      name: 'create_entities',
      description: 'Create new entities with observations and optional embeddings',
      inputSchema: {
        type: 'object',
        properties: {
          entities: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                name: {
                  type: 'string',
                },
                entityType: {
                  type: 'string',
                },
                observations: {
                  type: 'array',
                  items: {
                    type: 'string',
                  },
                },
                embedding: {
                  type: 'array',
                  items: {
                    type: 'number',
                  },
                  description: 'Optional vector embedding for similarity search',
                },
                relations: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      target: {
                        type: 'string',
                      },
                      relationType: {
                        type: 'string',
                      },
                    },
                    required: [
                      'target',
                      'relationType',
                    ],
                  },
                  description: 'Optional relations to create with this entity',
                },
              },
              required: [
                'name',
                'entityType',
                'observations',
              ],
            },
          },
        },
        required: [
          'entities',
        ],
      },
    },
  • Dispatch handler in callTool request that validates arguments and invokes the createEntities implementation.
    case 'create_entities': {
      // Define the expected type for entities
      interface EntityInput {
        name: string;
        entityType: string;
        observations: string[];
        embedding?: number[];
        relations?: Array<{
          target: string;
          relationType: string;
        }>;
      }
      
      // Type assertion with proper interface
      const entities = args.entities as EntityInput[];
      await createEntities(entities);
      return {
        content: [
          {
            type: 'text',
            text: `Successfully processed ${entities.length} entities (created new or updated existing)`,
          },
        ],
      };
    }
  • Exports the static method as a convenience function for use in other modules.
    export const createEntities = EntityService.createEntities;
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states this is a creation operation, implying mutation, but doesn't cover critical aspects like permissions needed, whether it's idempotent, error handling, or rate limits. The mention of 'optional embeddings' hints at functionality but lacks depth on behavioral traits.

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 new entities') and adds key details ('with observations and optional embeddings'). There is no wasted wording, making it easy to parse quickly while conveying essential information.

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 tool's complexity (1 parameter with nested objects, no annotations, no output schema), the description is insufficient. It doesn't explain the return values, error conditions, or the full scope of parameters (e.g., 'relations'). For a creation tool with rich input structure, more context is needed to guide effective 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 0%, so the description must compensate. It mentions 'observations and optional embeddings', which partially maps to the schema's 'observations' and 'embedding' fields, but omits 'relations' and details on 'entityType' or 'name'. This adds some meaning but doesn't fully explain the single parameter's structure or all nested fields, leaving gaps.

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') and resource ('new entities'), specifying they include 'observations and optional embeddings'. This distinguishes it from siblings like 'create_relations' (which creates relationships) and 'delete_entity' (which removes entities). However, it doesn't explicitly mention the 'relations' parameter shown in the schema, leaving the purpose slightly incomplete.

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. It doesn't mention prerequisites (e.g., when entities should be created vs. updated), contrast with siblings like 'read_graph' or 'search_nodes', or specify scenarios where embeddings or relations are appropriate. This leaves the agent without contextual usage cues.

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

Related 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/joleyline/mcp-memory-libsql'

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