Skip to main content
Glama

Graph Stats

graph_stats
Read-only

Assess graph health with counts of nodes, edges, orphans, contradictions, stale entries, schema version, and backlog. Use at session start or after graph decay/prune to verify results.

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' MCP tool via server.registerTool(). Defines inputSchema (empty), readOnlyHint annotation, and the async handler that calls client.getStats().
    // ─── 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}`);
      }
    });
  • The handler function for graph_stats. Calls client.getStats(currentTenant()), then enriches the result with schema version (from file) and pending ingest count (from directory listing), and returns the combined stats 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}`);
      }
    });
  • Input schema for graph_stats. Empty object '{}' — the tool takes no parameters.
    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 },
  • The getStats() method on Neo4jClient that performs the actual database queries: node counts by type, edge counts by type, and health metrics (avg weight, orphaned nodes, unresolved contradictions, stale nodes). All queries are tenant-scoped.
    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,
        },
      };
    }
Behavior4/5

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

Annotations already declare readOnlyHint=true, so the tool is safe. The description adds behavioral context by specifying it returns aggregate counts only and has no side effects. It does not mention any additional behaviors (e.g., rate limits), but for a simple stats tool, this is sufficient. Slight deduction for not elaborating on output structure beyond listing stats.

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 two concise sentences. The first sentence immediately states the purpose and what it returns, while the second provides usage guidance and confirms no parameters. Every word adds value, and it is front-loaded with the most critical information.

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 the tool's simplicity (no params, no output schema) and the richness of sibling tools, the description is fully complete. It explains what the tool returns, when to use it, and what it does not do (aggregates only). The agent can make an informed decision without needing additional context.

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?

The tool has no parameters, and the input schema is empty. The description explicitly confirms 'No parameters,' which is clear and accurate. With schema coverage at 100% and no params, no additional detail is needed.

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 explicitly states it returns aggregate graph health statistics (node/edge counts, average weight, etc.), using a specific verb+resource ('Graph health dashboard'). It clearly distinguishes itself from sibling tool graph_entities by noting it returns aggregates only, not 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?

The description provides clear guidance on when to use the tool: at session start, after graph_decay or graph_prune, or when debugging query output. It also explicitly excludes usage for individual entity lookup, directing users to graph_entities. This covers when-to-use and alternatives.

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