Skip to main content
Glama

Detect Knowledge Communities

graph_communities
Read-only

Detect clusters of densely connected entities in a knowledge graph using a seed-based BFS approach. Each entity belongs to one community, helping you explore related groups like 'everything related to infrastructure'.

Instructions

Find clusters of densely-interconnected entities in the graph. Uses greedy seed-based BFS through edges above the weight threshold — works without GDS or APOC. Each entity is assigned to at most one community (the first that reaches it from a high-degree seed). Useful for understanding knowledge neighbourhoods (e.g. "everything related to infrastructure"). Returns at most max_communities clusters, each shaped {community_id, seed: {id, name, type}, size, members: [{id, name, type}]}, sorted by size desc; communities below min_size are filtered out. Use graph_query or graph_search instead when you have a specific entity to start from.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
weight_thresholdNoOnly traverse edges with weight strictly greater than this (default 0.4).
max_communitiesNoMaximum number of communities to return (default 10).
max_hopsNoBFS depth from each seed (default 3, capped at 4).
min_sizeNoMinimum members for a community to be returned (default 2).

Implementation Reference

  • MCP tool registration for 'graph_communities' — defines title, description, input schema (weight_threshold, max_communities, max_hops, min_size), and the handler which delegates to Neo4jClient.findCommunities().
    server.registerTool("graph_communities", {
      title: "Detect Knowledge Communities",
      description:
        "Find clusters of densely-interconnected entities in the graph. Uses greedy seed-based BFS through " +
        "edges above the weight threshold — works without GDS or APOC. Each entity is assigned to at most " +
        "one community (the first that reaches it from a high-degree seed). Useful for understanding " +
        "knowledge neighbourhoods (e.g. \"everything related to infrastructure\"). " +
        "Returns at most `max_communities` clusters, each shaped `{community_id, seed: {id, name, type}, size, members: [{id, name, type}]}`, sorted by size desc; communities below `min_size` are filtered out. " +
        "Use graph_query or graph_search instead when you have a specific entity to start from.",
      inputSchema: {
        weight_threshold: z
          .number()
          .min(0)
          .max(1)
          .optional()
          .default(0.4)
          .describe("Only traverse edges with weight strictly greater than this (default 0.4)."),
        max_communities: z
          .number()
          .int()
          .min(1)
          .max(30)
          .optional()
          .default(10)
          .describe("Maximum number of communities to return (default 10)."),
        max_hops: z
          .number()
          .int()
          .min(1)
          .max(4)
          .optional()
          .default(3)
          .describe("BFS depth from each seed (default 3, capped at 4)."),
        min_size: z
          .number()
          .int()
          .min(2)
          .optional()
          .default(2)
          .describe("Minimum members for a community to be returned (default 2)."),
      },
      annotations: { readOnlyHint: true },
    }, async (args) => {
      try {
        const result = await client.findCommunities(currentTenant(), {
          weight_threshold: args.weight_threshold,
          max_communities: args.max_communities,
          max_hops: args.max_hops,
          min_size: args.min_size,
        });
        return toolResult(result);
      } catch (err) {
        const e = err instanceof Error ? err : new Error(String(err));
        return toolError(`graph_communities failed: ${e.message}`);
      }
    });
  • Input schema for graph_communities — defines weight_threshold, max_communities, max_hops, and min_size with validation (min/max) and defaults.
    inputSchema: {
      weight_threshold: z
        .number()
        .min(0)
        .max(1)
        .optional()
        .default(0.4)
        .describe("Only traverse edges with weight strictly greater than this (default 0.4)."),
      max_communities: z
        .number()
        .int()
        .min(1)
        .max(30)
        .optional()
        .default(10)
        .describe("Maximum number of communities to return (default 10)."),
      max_hops: z
        .number()
        .int()
        .min(1)
        .max(4)
        .optional()
        .default(3)
        .describe("BFS depth from each seed (default 3, capped at 4)."),
      min_size: z
        .number()
        .int()
        .min(2)
        .optional()
        .default(2)
        .describe("Minimum members for a community to be returned (default 2)."),
    },
  • Core implementation of community detection — greedy seed-based BFS clustering algorithm. Ranks entities by degree of strong edges, picks highest-degree unassigned entity as seed, performs BFS traversal through edges above weight threshold up to max_hops, assigns all reached entities to that community, and repeats up to max_communities.
    async findCommunities(tenantId: string, options: {
      weight_threshold?: number;
      max_communities?: number;
      max_hops?: number;
      min_size?: number;
    } = {}): Promise<{
      communities: Array<{
        id: number;
        seed_name: string;
        seed_id: string;
        member_count: number;
        dominant_type: string;
        members: Array<{ id: string; name: string; type: string }>;
      }>;
      coverage: {
        total_entities: number;
        assigned: number;
        unassigned: number;
      };
    }> {
      const threshold = options.weight_threshold ?? 0.4;
      const maxCommunities = options.max_communities ?? 10;
      const maxHops = Math.max(1, Math.min(options.max_hops ?? 3, 4));
      const minSize = options.min_size ?? 2;
    
      // Step 1: rank nodes by strong-edge degree (tenant-scoped)
      const hubRows = await this.run(
        `
        MATCH (n:Entity {tenant_id: $tenantId})-[r]-(other:Entity {tenant_id: $tenantId})
        WHERE r.weight > $threshold
        WITH n, count(r) AS degree
        WHERE degree >= 2
        RETURN n.id AS id,
               n.name AS name,
               [l IN labels(n) WHERE l <> 'Entity'][0] AS type,
               degree
        ORDER BY degree DESC
        LIMIT 100
        `,
        { tenantId, threshold },
      );
    
      // Total entity count for coverage stats (tenant-scoped)
      const totalRows = await this.run(
        `MATCH (n:Entity {tenant_id: $tenantId}) RETURN count(n) AS total`,
        { tenantId },
      );
      const totalEntities = Number(totalRows[0]?.["total"] ?? 0);
    
      const assigned = new Set<string>();
      const communities: Array<{
        id: number;
        seed_name: string;
        seed_id: string;
        member_count: number;
        dominant_type: string;
        members: Array<{ id: string; name: string; type: string }>;
      }> = [];
    
      for (const hub of hubRows) {
        if (communities.length >= maxCommunities) break;
        const hubId = String(hub["id"]);
        if (assigned.has(hubId)) continue;
    
        // BFS: variable-length path from seed, all relationships above threshold,
        // confined to this tenant's subgraph. Path is bound to a variable so we
        // can pass it to nodes() — passing the pattern directly is List<Path>.
        const memberRows = await this.run(
          `
          MATCH (seed:Entity {tenant_id: $tenantId, id: $seedId})
          MATCH path = (seed)-[r*1..${maxHops}]-(m:Entity)
          WHERE ALL(node IN nodes(path) WHERE node.tenant_id = $tenantId)
            AND ALL(rel IN r WHERE rel.weight > $threshold)
          RETURN DISTINCT m.id AS id,
                 m.name AS name,
                 [l IN labels(m) WHERE l <> 'Entity'][0] AS type
          `,
          { tenantId, seedId: hubId, threshold },
        );
    
        const seedRow = {
          id: hubId,
          name: String(hub["name"] ?? hubId),
          type: String(hub["type"] ?? "?"),
        };
    
        const members = [seedRow];
        const seenInCluster = new Set<string>([hubId]);
        for (const row of memberRows) {
          const id = String(row["id"]);
          if (assigned.has(id) || seenInCluster.has(id)) continue;
          seenInCluster.add(id);
          members.push({
            id,
            name: String(row["name"] ?? id),
            type: String(row["type"] ?? "?"),
          });
        }
    
        if (members.length < minSize) continue;
    
        // Compute dominant type
        const typeCounts: Record<string, number> = {};
        for (const m of members) typeCounts[m.type] = (typeCounts[m.type] ?? 0) + 1;
        const dominantType = Object.entries(typeCounts).sort((a, b) => b[1] - a[1])[0]?.[0] ?? "?";
    
        // Mark these as assigned (greedy: each entity belongs to the first community that grabs it)
        for (const m of members) assigned.add(m.id);
    
        communities.push({
          id: communities.length + 1,
          seed_name: seedRow.name,
          seed_id: seedRow.id,
          member_count: members.length,
          dominant_type: dominantType,
          members: members.slice(0, 30),
        });
      }
    
      return {
        communities,
        coverage: {
          total_entities: totalEntities,
          assigned: assigned.size,
          unassigned: totalEntities - assigned.size,
        },
      };
    }
Behavior5/5

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

Annotations provide readOnlyHint=true, and the description adds significant behavioral detail: algorithm (seed-based BFS, no GDS/APOC), assignment rule (each entity to at most one community), return structure (shaped as described), and output order (sorted by size desc). It also mentions filtering by min_size and max_communities, adding context beyond 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?

The description is a single paragraph of moderate length, well-structured with clear sentences. It front-loads the main purpose, then explains algorithm details, constraints, return format, and alternatives. Every sentence adds value with no redundancy.

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

Completeness5/5

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

Given no output schema, the description fully explains the return format (each cluster with community_id, seed, size, members) and sorting/filtering behavior. It covers purpose, algorithm, parameter effects, and alternative tools. The description is complete for an agent to decide when and how to use this tool.

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

Parameters5/5

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

All four parameters have schema descriptions, but the tool description adds contextual meaning: weight_threshold controls traversal edge weight, max_hops is BFS depth, min_size filters small communities, max_communities limits output. This goes beyond the schema's default/min/max to explain how each parameter affects the algorithm.

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 clusters of densely-interconnected entities using a specific algorithm (seed-based BFS). It distinguishes from sibling tools graph_query and graph_search, which are for starting from a specific entity. The verb 'Find' and resource 'clusters' are specific and well-defined.

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?

The description explicitly states when to use this tool (e.g., for understanding knowledge neighbourhoods) and when not to (e.g., 'Use graph_query or graph_search instead when you have a specific entity to start from'). It also implies to use for community detection without a starting entity.

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