Skip to main content
Glama

get_element_relationships

Retrieve semantic connections, verb-based links, and cross-element references for any persona, skill, template, agent, memory, or ensemble element in DollhouseMCP.

Instructions

Get all relationships for a specific element, including semantic similarities, verb-based connections, and cross-element references.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
element_nameYesName of the element to get relationships for
element_typeNoType of the element. If not specified, searches all types.
relationship_typesNoFilter by specific relationship types. If not specified, returns all types.

Implementation Reference

  • Core handler function executing the tool logic: validates inputs, normalizes element IDs, fetches relationships from EnhancedIndexManager, filters by type if specified, parses relationships, and formats a rich text response with icons and strength scores.
    async getElementRelationships(options: {
      elementName: string;
      elementType?: string;
      relationshipTypes?: string[];
    }) {
      try {
        // FIX: DMCP-SEC-004 - Normalize Unicode in user input
        const normalized = UnicodeValidator.normalize(options.elementName);
        if (!normalized.isValid) {
          throw new Error(`Invalid element name: ${normalized.detectedIssues?.join(', ')}`);
        }
        options.elementName = normalized.normalizedContent;
    
        if (options.elementType) {
          const normalizedType = UnicodeValidator.normalize(options.elementType);
          if (!normalizedType.isValid) {
            throw new Error(`Invalid element type: ${normalizedType.detectedIssues?.join(', ')}`);
          }
          options.elementType = normalizedType.normalizedContent;
        }
    
        // Get the index with error handling
        await this.enhancedIndexManager.getIndex().catch(async (error) => {
          logger.error('Failed to get Enhanced Index, attempting rebuild', error);
          return this.enhancedIndexManager.getIndex({ forceRebuild: true });
        });
    
        // FIX: DMCP-SEC-006 - Add security audit logging
        SecurityMonitor.logSecurityEvent({
          type: 'ELEMENT_CREATED',
          severity: 'LOW',
          source: 'EnhancedIndexHandler.getElementRelationships',
          details: `Relationship query performed for element: ${options.elementName}`,
          additionalData: {
            elementType: options.elementType,
            relationshipTypes: options.relationshipTypes
          }
        });
    
        // FIX: Use centralized element ID formatting
        // If no element type provided, use full element name as-is (may already include type)
        const elementId = options.elementType ?
          formatElementId(options.elementType, options.elementName) :
          options.elementName;
    
        const relationships = await this.enhancedIndexManager.getElementRelationships(elementId);
    
        // Filter by type if requested
        let filteredRelationships = relationships;
        if (options.relationshipTypes && options.relationshipTypes.length > 0) {
          filteredRelationships = {};
          for (const type of options.relationshipTypes) {
            if (relationships[type]) {
              filteredRelationships[type] = relationships[type];
            }
          }
        }
    
        // Format results
        let text = `${this.personaIndicator}đź”— **Element Relationships**\n\n`;
        text += `**Element**: ${options.elementName}\n`;
        if (options.elementType) {
          text += `**Type**: ${options.elementType}\n`;
        }
        text += '\n';
    
        const relationshipCount = Object.values(filteredRelationships)
          .reduce((sum, rels) => sum + (Array.isArray(rels) ? rels.length : 0), 0);
    
        if (relationshipCount === 0) {
          text += `No relationships found for this element.\n`;
        } else {
          for (const [relType, relations] of Object.entries(filteredRelationships)) {
            if (Array.isArray(relations) && relations.length > 0) {
              text += `**${relType.charAt(0).toUpperCase() + relType.slice(1)} (${relations.length})**\n`;
              for (const rel of relations) {
                // FIX: Use type-safe relationship parsing
                const parsedRel = parseRelationship(rel);
                if (isParsedRelationship(parsedRel)) {
                  const icon = this.getElementIcon(parsedRel.targetType);
                  text += `  ${icon} ${parsedRel.targetName}`;
                  if (parsedRel.strength) {
                    text += ` (strength: ${(parsedRel.strength * 100).toFixed(0)}%)`;
                  }
                  text += '\n';
                } else {
                  // Fallback for invalid relationships
                  const parsed = parseElementIdWithFallback(rel.element);
                  const icon = this.getElementIcon(parsed.type);
                  text += `  ${icon} ${parsed.name} ⚠️\n`;
                }
              }
              text += '\n';
            }
          }
        }
    
        return {
          content: [{
            type: "text",
            text
          }]
        };
      } catch (error: any) {
        ErrorHandler.logError('EnhancedIndexHandler.getElementRelationships', error, options);
        return {
          content: [{
            type: "text",
            text: `${this.personaIndicator}❌ Failed to get relationships: ${SecureErrorHandler.sanitizeError(error).message}`
          }]
        };
      }
    }
  • Registers the MCP tool 'get_element_relationships' with full input schema, description, and handler that maps args to server.getElementRelationships call.
      tool: {
        name: "get_element_relationships",
        description: "Get all relationships for a specific element, including semantic similarities, verb-based connections, and cross-element references.",
        inputSchema: {
          type: "object",
          properties: {
            element_name: {
              type: "string",
              description: "Name of the element to get relationships for",
            },
            element_type: {
              type: "string",
              enum: ["personas", "skills", "templates", "agents", "memories", "ensembles"],
              description: "Type of the element. If not specified, searches all types.",
            },
            relationship_types: {
              type: "array",
              items: {
                type: "string",
                enum: ["similar", "uses", "extends", "requires", "complements", "verb-based"]
              },
              description: "Filter by specific relationship types. If not specified, returns all types.",
            },
          },
          required: ["element_name"],
        },
      },
      handler: (args: GetElementRelationshipsArgs) => server.getElementRelationships({
        elementName: args.element_name,
        elementType: args.element_type,
        relationshipTypes: args.relationship_types
      })
    },
  • JSON schema for tool inputs defining element_name (required), optional element_type enum, and relationship_types array enum.
    inputSchema: {
      type: "object",
      properties: {
        element_name: {
          type: "string",
          description: "Name of the element to get relationships for",
        },
        element_type: {
          type: "string",
          enum: ["personas", "skills", "templates", "agents", "memories", "ensembles"],
          description: "Type of the element. If not specified, searches all types.",
        },
        relationship_types: {
          type: "array",
          items: {
            type: "string",
            enum: ["similar", "uses", "extends", "requires", "complements", "verb-based"]
          },
          description: "Filter by specific relationship types. If not specified, returns all types.",
        },
      },
      required: ["element_name"],
    },
  • Helper method in EnhancedIndexManager that retrieves raw relationships for an element from the in-memory index after parsing the elementId.
    public async getElementRelationships(elementId: string): Promise<Record<string, Relationship[]>> {
      const index = await this.getIndex();
      // FIX: Use centralized element ID parsing
      const parsed = parseElementId(elementId);
      if (!parsed) {
        return {};
      }
      const element = index.elements[parsed.type]?.[parsed.name];
    
      if (!element) {
        return {};
      }
    
      return element.relationships || {};
    }
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 what relationships are included (semantic similarities, verb-based connections, cross-element references) but doesn't disclose behavioral traits like whether this is a read-only operation, potential rate limits, authentication needs, pagination, or what the output format looks like. For a tool with no annotations, this leaves significant gaps in understanding how it behaves.

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 purpose and lists relationship types clearly. Every word earns its place with no redundancy or fluff, making it easy to parse quickly.

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 no annotations and no output schema, the description is incomplete for a tool with 3 parameters. It doesn't explain what the return values look like (e.g., list of relationships with details), potential errors, or usage constraints. For a read operation with moderate complexity, more context is needed to guide the agent effectively.

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 parameters thoroughly. The description doesn't add any meaning beyond what the schema provides—it doesn't explain parameter interactions, default behaviors, or examples. Baseline 3 is appropriate when the schema does the heavy lifting.

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 'Get' and resource 'relationships for a specific element', specifying the scope includes semantic similarities, verb-based connections, and cross-element references. It distinguishes from siblings like 'get_element_details' (which likely returns element metadata) and 'find_similar_elements' (which likely finds similar elements rather than relationships), though it doesn't explicitly name these distinctions.

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?

No explicit guidance on when to use this tool versus alternatives. The description implies usage when relationships are needed, but it doesn't specify prerequisites, exclusions, or compare to siblings like 'get_relationship_stats' or 'search_by_verb'. The agent must infer usage from the name and description 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/DollhouseMCP/DollhouseMCP'

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