Skip to main content
Glama

Semantic Graph Search

graph_search
Read-only

Find entities in your knowledge graph by describing them in natural language, even if your wording doesn't match stored names. Optionally explore connected nodes.

Instructions

Find entities semantically similar to a natural-language query, then optionally expand via graph traversal. Uses local sentence embeddings (bge-small-en, 384-dim) — no external API. Best when the user's wording doesn't match canonical entity names (e.g. "containers" → Docker, "AI tools" → Claude Code/Anthropic SDK). Falls back to graph_query if no embeddings available.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesNatural-language query (any phrasing — synonyms and paraphrases work).
top_kNoHow many semantically similar entities to retrieve as seeds (default 10).
min_similarityNoMinimum cosine similarity threshold (default 0.5).
entity_typesNoRestrict results to these entity types.
expandNoIf true (default), also return the immediate graph neighbours of each seed.
expand_min_weightNoMin edge weight when expanding (default 0.3).

Implementation Reference

  • The graph_search tool handler function. Takes a natural-language query, embeds it via embedText(), performs vector similarity search against the Neo4j entity_embedding index (tenant-scoped), and optionally expands results via graph traversal. Returns seeds (similar entities) and optionally expansion (neighbor edges/nodes).
    }, async (args) => {
      try {
        // 1. Embed the query
        const { embedText } = await import("../shared/embeddings.js");
        let queryVec: number[];
        try {
          queryVec = await embedText(args.query);
        } catch (err) {
          const e = err instanceof Error ? err : new Error(String(err));
          return toolError(`graph_search: embedder unavailable (${e.message}). Try graph_query instead.`);
        }
    
        // 2. Vector similarity search → seeds (tenant-scoped)
        const tenantId = currentTenant();
        const seeds = await client.vectorSearch(tenantId, queryVec, {
          top_k: args.top_k ?? 10,
          min_similarity: args.min_similarity ?? 0.5,
          entity_types: args.entity_types as EntityType[] | undefined,
        });
    
        if (seeds.length === 0) {
          return toolResult({
            query: args.query,
            seeds: [],
            expansion: null,
            note: "No entities matched at the given similarity threshold. Try lowering min_similarity or check that embeddings have been backfilled (graph_stats > schema or check startup logs).",
          });
        }
    
        // 3. Optionally expand: for each seed, find the top edges
        const expansionEdges: Array<{ from: string; to: string; from_name: string; to_name: string; relation: string; weight: number }> = [];
        const expansionNodes = new Map<string, { id: string; name: string; type: string; from_seed: string }>();
    
        if (args.expand !== false) {
          const minWeight = args.expand_min_weight ?? 0.3;
          const seedIds = seeds.slice(0, 5).map((s) => s.id); // Expand only top 5 seeds to keep payload tight
    
          const expansionRows = await client.runReadQuery(
            `
            MATCH (a:Entity {tenant_id: $tenantId})-[r]-(b:Entity {tenant_id: $tenantId})
            WHERE a.id IN $seedIds AND r.weight > $minWeight
            RETURN a.id AS from_id, a.name AS from_name,
                   b.id AS to_id, b.name AS to_name,
                   [l IN labels(b) WHERE l <> 'Entity'][0] AS to_type,
                   type(r) AS relation, r.weight AS weight
            ORDER BY r.weight DESC
            LIMIT 30
            `,
            { tenantId, seedIds, minWeight },
          );
    
          for (const row of expansionRows) {
            const fromId = String(row["from_id"]);
            const toId = String(row["to_id"]);
            const toName = String(row["to_name"] ?? "");
            const toType = String(row["to_type"] ?? "?");
    
            expansionEdges.push({
              from: fromId,
              to: toId,
              from_name: String(row["from_name"] ?? ""),
              to_name: toName,
              relation: String(row["relation"] ?? ""),
              weight: Number(row["weight"] ?? 0),
            });
    
            // Don't include seeds themselves in the expansion node list
            if (!seeds.find((s) => s.id === toId)) {
              expansionNodes.set(toId, { id: toId, name: toName, type: toType, from_seed: fromId });
            }
          }
        }
    
        return toolResult({
          query: args.query,
          seeds,
          expansion: args.expand === false ? null : {
            nodes: Array.from(expansionNodes.values()),
            edges: expansionEdges,
            node_count: expansionNodes.size,
            edge_count: expansionEdges.length,
          },
        });
      } catch (err) {
        const e = err instanceof Error ? err : new Error(String(err));
        return toolError(`graph_search failed: ${e.message}`);
      }
    });
  • Registration of the graph_search tool via server.registerTool('graph_search', ...). Defines title, description, inputSchema (query, top_k, min_similarity, entity_types, expand, expand_min_weight), and annotations (readOnlyHint).
    server.registerTool("graph_search", {
      title: "Semantic Graph Search",
      description:
        "Find entities semantically similar to a natural-language query, then optionally expand via " +
        "graph traversal. Uses local sentence embeddings (bge-small-en, 384-dim) — no external API. " +
        "Best when the user's wording doesn't match canonical entity names (e.g. \"containers\" → Docker, " +
        "\"AI tools\" → Claude Code/Anthropic SDK). Falls back to graph_query if no embeddings available.",
      inputSchema: {
        query: z
          .string()
          .min(1)
          .describe("Natural-language query (any phrasing — synonyms and paraphrases work)."),
        top_k: z
          .number()
          .int()
          .min(1)
          .max(50)
          .optional()
          .default(10)
          .describe("How many semantically similar entities to retrieve as seeds (default 10)."),
        min_similarity: z
          .number()
          .min(0)
          .max(1)
          .optional()
          .default(0.5)
          .describe("Minimum cosine similarity threshold (default 0.5)."),
        entity_types: z
          .array(z.enum(ENTITY_TYPES))
          .optional()
          .describe("Restrict results to these entity types."),
        expand: z
          .boolean()
          .optional()
          .default(true)
          .describe("If true (default), also return the immediate graph neighbours of each seed."),
        expand_min_weight: z
          .number()
          .min(0)
          .max(1)
          .optional()
          .default(0.3)
          .describe("Min edge weight when expanding (default 0.3)."),
      },
      annotations: { readOnlyHint: true },
  • Zod input schema for graph_search: query (string, required), top_k (1-50, default 10), min_similarity (0-1, default 0.5), entity_types (optional array of ENTITY_TYPES), expand (boolean, default true), expand_min_weight (0-1, default 0.3).
    inputSchema: {
      query: z
        .string()
        .min(1)
        .describe("Natural-language query (any phrasing — synonyms and paraphrases work)."),
      top_k: z
        .number()
        .int()
        .min(1)
        .max(50)
        .optional()
        .default(10)
        .describe("How many semantically similar entities to retrieve as seeds (default 10)."),
      min_similarity: z
        .number()
        .min(0)
        .max(1)
        .optional()
        .default(0.5)
        .describe("Minimum cosine similarity threshold (default 0.5)."),
      entity_types: z
        .array(z.enum(ENTITY_TYPES))
        .optional()
        .describe("Restrict results to these entity types."),
      expand: z
        .boolean()
        .optional()
        .default(true)
        .describe("If true (default), also return the immediate graph neighbours of each seed."),
      expand_min_weight: z
        .number()
        .min(0)
        .max(1)
        .optional()
        .default(0.3)
        .describe("Min edge weight when expanding (default 0.3)."),
    },
  • The embedText() helper function used by graph_search to embed the natural-language query string into a 384-dim vector using bge-small-en-v1.5 (via @huggingface/transformers pipeline). Returns a number array.
    export async function embedText(text: string): Promise<number[]> {
      const cleaned = text.trim();
      if (!cleaned) return new Array<number>(EMBEDDING_DIM).fill(0);
      const e = await getEmbedder();
      const result = await e(cleaned, { pooling: "mean", normalize: true });
      // result.data is a Float32Array of length 384
      return Array.from(result.data as Float32Array);
    }
  • The vectorSearch() method on Neo4jClient called by graph_search. Queries the 'entity_embedding' vector index with over-request tenant-filtering strategy, returning entities with similarity scores.
    async vectorSearch(
      tenantId: string,
      queryEmbedding: number[],
      options: { top_k?: number; min_similarity?: number; entity_types?: EntityType[] } = {},
    ): Promise<Array<{ id: string; name: string; type: string; score: number; confidence: number }>> {
      const topK = options.top_k ?? 10;
      const minSim = options.min_similarity ?? 0.5;
      const candidatePool = Math.max(topK * 4, 40); // over-request, then filter by tenant
    
      const typeFilter = options.entity_types && options.entity_types.length > 0
        ? `AND ANY(l IN labels(node) WHERE l IN $types)`
        : "";
    
      const rows = await this.run(
        `
        CALL db.index.vector.queryNodes('entity_embedding', $candidatePool, $queryEmbedding)
        YIELD node, score
        WHERE node.tenant_id = $tenantId AND score >= $minSim ${typeFilter}
        RETURN node.id AS id,
               node.name AS name,
               [l IN labels(node) WHERE l <> 'Entity'][0] AS type,
               node.confidence AS confidence,
               score
        ORDER BY score DESC
        LIMIT $topK
        `,
        {
          tenantId,
          candidatePool,
          topK,
          queryEmbedding,
          minSim,
          ...(options.entity_types && options.entity_types.length > 0 && { types: options.entity_types }),
        },
      );
    
      return rows.map((r) => ({
        id: String(r["id"]),
        name: String(r["name"] ?? ""),
        type: String(r["type"] ?? "?"),
        confidence: Number(r["confidence"] ?? 0),
        score: Number(r["score"] ?? 0),
      }));
    }
Behavior5/5

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

Annotations already mark this as read-only, and the description adds value by disclosing the use of local sentence embeddings (bge-small-en, 384-dim) with no external API call, and the fallback behavior. No contradiction with annotations.

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?

Three sentences: first states core function, second provides technical detail, third gives usage guidance. Every sentence earns its place, no superfluous text.

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

Completeness4/5

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

The description covers the main behavior and parameter context well, but omits explicit return value format. Given the simple output and no output schema, it is almost complete; a minor gap for perfect completeness.

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

Parameters4/5

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

Schema description coverage is 100%, so the baseline is 3. However, the description adds context about the embedding model and the purpose of parameters like min_similarity, going beyond the schema's per-parameter descriptions.

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

Purpose5/5

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

The description clearly states the tool finds semantically similar entities using natural-language queries and optionally expands via graph traversal. It distinguishes itself from sibling tool graph_query by mentioning a fallback when embeddings are unavailable.

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

Usage Guidelines5/5

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

Explicitly indicates it is best used when user wording does not match canonical entity names, and provides a fallback to graph_query if embeddings are not available, giving clear when-to-use guidance.

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/stevepridemore/graph-memory'

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