Skip to main content
Glama

Graph Stats

graph_stats
Read-only

Assess graph health by returning counts of nodes, edges, orphans, and other aggregate metrics. Use at session start or after maintenance to verify graph state.

Instructions

Graph health dashboard — node/edge counts by type, average weight, orphan count, unresolved contradictions, stale entries, schema version, and pending ingest backlog. Returns aggregate counts only; for individual entities use graph_entities. Call at session start to size up the graph before deeper queries, after graph_decay or graph_prune to verify the result, or when debugging unexpected query output. No parameters.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Registration of the graph_stats tool via server.registerTool with empty input schema and readOnlyHint annotation.
    // ─── Tool: graph_stats ───
    
    server.registerTool("graph_stats", {
      title: "Graph Stats",
      description:
        "Graph health dashboard — node/edge counts by type, average weight, orphan count, unresolved contradictions, stale entries, schema version, and pending ingest backlog. Returns aggregate counts only; for individual entities use graph_entities. Call at session start to size up the graph before deeper queries, after graph_decay or graph_prune to verify the result, or when debugging unexpected query output. No parameters.",
      inputSchema: {},
      annotations: { readOnlyHint: true },
    }, async () => {
      debugLog('graph_stats called');
      try {
        debugLog('attempting getStats()...');
        const stats = await client.getStats(currentTenant());
        debugLog('getStats() succeeded');
    
        // Add schema version and ingest status
        let schemaVersion = "1";
        try {
          schemaVersion = readFileSync(
            join(GRAPH_MEMORY_HOME, "schema", "current_version.txt"),
            "utf-8",
          ).trim();
        } catch { /* default to 1 */ }
    
        let pendingIngest = 0;
        try {
          const pendingDir = join(GRAPH_MEMORY_HOME, "ingest", "pending");
          pendingIngest = readdirSync(pendingDir).filter((f) => !f.endsWith(".meta.json")).length;
        } catch { /* dir doesn't exist */ }
    
        return toolResult({
          schema_version: schemaVersion,
          ...stats,
          health: {
            ...stats.health,
            pending_ingest_docs: pendingIngest,
          },
        });
      } catch (err) {
        const e = err instanceof Error ? err : new Error(String(err));
        debugLog(`graph_stats FULL ERROR: ${e.constructor.name}: ${e.message}`);
        debugLog(`code=${(e as NodeJS.ErrnoException).code ?? 'none'}`);
        debugLog(`stack=${e.stack ?? 'no stack'}`);
        return toolError(`graph_stats failed: ${e.message}`);
      }
    });
  • Handler function for graph_stats: calls client.getStats(currentTenant()) then augments with schema version (read from file) and pending ingest count (read from directory). Returns combined result via toolResult().
    }, async () => {
      debugLog('graph_stats called');
      try {
        debugLog('attempting getStats()...');
        const stats = await client.getStats(currentTenant());
        debugLog('getStats() succeeded');
    
        // Add schema version and ingest status
        let schemaVersion = "1";
        try {
          schemaVersion = readFileSync(
            join(GRAPH_MEMORY_HOME, "schema", "current_version.txt"),
            "utf-8",
          ).trim();
        } catch { /* default to 1 */ }
    
        let pendingIngest = 0;
        try {
          const pendingDir = join(GRAPH_MEMORY_HOME, "ingest", "pending");
          pendingIngest = readdirSync(pendingDir).filter((f) => !f.endsWith(".meta.json")).length;
        } catch { /* dir doesn't exist */ }
    
        return toolResult({
          schema_version: schemaVersion,
          ...stats,
          health: {
            ...stats.health,
            pending_ingest_docs: pendingIngest,
          },
        });
      } catch (err) {
        const e = err instanceof Error ? err : new Error(String(err));
        debugLog(`graph_stats FULL ERROR: ${e.constructor.name}: ${e.message}`);
        debugLog(`code=${(e as NodeJS.ErrnoException).code ?? 'none'}`);
        debugLog(`stack=${e.stack ?? 'no stack'}`);
        return toolError(`graph_stats failed: ${e.message}`);
      }
    });
  • Empty input schema for graph_stats — the tool takes no parameters.
    inputSchema: {},
    annotations: { readOnlyHint: true },
  • The getStats method on Neo4jClient that queries Neo4j for node/edge counts by type, and health metrics (avg weight, orphans, contradictions, stale nodes), all scoped to a tenant.
    async getStats(tenantId: string): Promise<{
      nodes: { total: number; by_type: Record<string, number> };
      edges: { total: number; by_type: Record<string, number> };
      health: {
        avg_weight: number;
        orphaned_nodes: number;
        unresolved_contradictions: number;
        stale_nodes: number;
      };
    }> {
      // Node counts by type (tenant-scoped)
      const nodeRows = await this.run(`
        MATCH (n:Entity {tenant_id: $tenantId})
        WITH labels(n) AS labels, count(n) AS count
        UNWIND labels AS label
        WITH label, sum(count) AS total WHERE label <> 'Entity'
        RETURN label, total ORDER BY total DESC
      `, { tenantId });
      const byType: Record<string, number> = {};
      let totalNodes = 0;
      for (const row of nodeRows) {
        const count = Number(row["total"] ?? 0);
        byType[String(row["label"])] = count;
        totalNodes += count;
      }
    
      // Edge counts by type (tenant-scoped — both endpoints in tenant)
      const edgeRows = await this.run(`
        MATCH (a:Entity {tenant_id: $tenantId})-[r]->(b:Entity {tenant_id: $tenantId})
        RETURN type(r) AS type, count(r) AS count ORDER BY count DESC
      `, { tenantId });
      const edgeByType: Record<string, number> = {};
      let totalEdges = 0;
      for (const row of edgeRows) {
        const count = Number(row["count"] ?? 0);
        edgeByType[String(row["type"])] = count;
        totalEdges += count;
      }
    
      // Health metrics (tenant-scoped)
      const healthRows = await this.run(`
        OPTIONAL MATCH (a:Entity {tenant_id: $tenantId})-[r]->(b:Entity {tenant_id: $tenantId})
        WITH avg(r.weight) AS avgWeight
        OPTIONAL MATCH (orphan:Entity {tenant_id: $tenantId})
        WHERE NOT (orphan)-[]-()
        WITH avgWeight, count(orphan) AS orphanCount
        OPTIONAL MATCH (a2:Entity {tenant_id: $tenantId})-[c:CONTRADICTS]->(b2:Entity {tenant_id: $tenantId})
        WHERE c.resolved = false
        WITH avgWeight, orphanCount, count(c) AS contradictions
        OPTIONAL MATCH (stale:Entity {tenant_id: $tenantId})
        WHERE stale.confidence < 0.2 AND stale.last_seen < datetime() - duration('P90D')
        RETURN avgWeight, orphanCount, contradictions, count(stale) AS staleCount
      `, { tenantId });
      const hRow = healthRows[0];
      const avgWeight = hRow ? Number(hRow["avgWeight"] ?? 0) : 0;
      const orphaned = Number(hRow?.["orphanCount"] ?? 0);
      const contradictions = Number(hRow?.["contradictions"] ?? 0);
      const staleNodes = Number(hRow?.["staleCount"] ?? 0);
    
      return {
        nodes: { total: totalNodes, by_type: byType },
        edges: { total: totalEdges, by_type: edgeByType },
        health: {
          avg_weight: Math.round(avgWeight * 100) / 100,
          orphaned_nodes: orphaned,
          unresolved_contradictions: contradictions,
          stale_nodes: staleNodes,
        },
      };
    }
Behavior5/5

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

Annotations already declare readOnlyHint=true, and the description adds that it returns aggregate counts only, confirming no side effects. No contradictions.

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?

Two sentences pack all necessary information: purpose, metrics, usage guidance, and parameter note. Front-loaded and efficient.

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?

With no parameters and no output schema, the description fully covers functionality, usage scenarios, and return type, leaving no gaps.

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?

No parameters exist (baseline 4 per rules), and description correctly states 'No parameters' without needing further elaboration.

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 'Graph health dashboard' and enumerates specific metrics (node/edge counts, average weight, orphan count, etc.), with a distinction from sibling tool graph_entities for individual entities.

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 advises when to call: at session start, after graph_decay or graph_prune, or when debugging unexpected output, providing clear context for usage.

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