Skip to main content
Glama

Build Session Context

graph_build_context
Read-only

Bundles graph health, pending work, recent additions, top hubs, contradictions, and optional topic neighbourhood into one call to reduce round trips at session start.

Instructions

Single tool call that bundles a session's worth of context: graph health, pending work, last dream run summary, recent additions, top knowledge hubs, unresolved contradictions, and (optionally) a topic neighbourhood. Use this at session start instead of running graph_stats / graph_query / graph_contradictions separately. Cuts 4-5 round trips to one.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
topicNoOptional topic to fetch a neighbourhood for (uses graph_query under the hood).
project_cwdNoOptional project directory for affinity scoring on the topic neighbourhood.
recent_daysNoWindow in days for 'recently added' entities (default 7).
hub_countNoNumber of top knowledge hubs to include (default 5).
include_contradictionsNoInclude unresolved contradictions (default true).
max_recentNoMax recent entities to list (default 15).

Implementation Reference

  • Registration of the graph_build_context tool with input schema, description, annotations (readOnlyHint), and the async handler function.
    server.registerTool("graph_build_context", {
      title: "Build Session Context",
      description:
        "Single tool call that bundles a session's worth of context: graph health, pending work, last dream " +
        "run summary, recent additions, top knowledge hubs, unresolved contradictions, and (optionally) a " +
        "topic neighbourhood. Use this at session start instead of running graph_stats / graph_query / " +
        "graph_contradictions separately. Cuts 4-5 round trips to one.",
      inputSchema: {
        topic: z
          .string()
          .optional()
          .describe("Optional topic to fetch a neighbourhood for (uses graph_query under the hood)."),
        project_cwd: z
          .string()
          .optional()
          .describe("Optional project directory for affinity scoring on the topic neighbourhood."),
        recent_days: z
          .number()
          .int()
          .min(1)
          .max(90)
          .optional()
          .default(7)
          .describe("Window in days for 'recently added' entities (default 7)."),
        hub_count: z
          .number()
          .int()
          .min(1)
          .max(20)
          .optional()
          .default(5)
          .describe("Number of top knowledge hubs to include (default 5)."),
        include_contradictions: z
          .boolean()
          .optional()
          .default(true)
          .describe("Include unresolved contradictions (default true)."),
        max_recent: z
          .number()
          .int()
          .min(1)
          .max(50)
          .optional()
          .default(15)
          .describe("Max recent entities to list (default 15)."),
      },
      annotations: { readOnlyHint: true },
    }, async (args) => {
      try {
        const tenantId = currentTenant();
        const recentDays = args.recent_days ?? 7;
        const hubCount = args.hub_count ?? 5;
        const includeContradictions = args.include_contradictions ?? true;
        const maxRecent = args.max_recent ?? 15;
    
        // Run the graph queries in parallel — independent
        const [statsResult, recent, hubs, contradictions, topicResult] = await Promise.all([
          client.getStats(tenantId),
          client.getRecentAdditions(tenantId, recentDays, maxRecent),
          client.getTopHubs(tenantId, hubCount),
          includeContradictions
            ? client.findContradictions(tenantId, false)
            : Promise.resolve({ contradictions: [] as Array<Record<string, unknown>> }),
          args.topic
            ? client.query(tenantId, [args.topic], {
                max_hops: 2,
                min_weight: 0.3,
                limit: 15,
                project_context: args.project_cwd,
                current_only: true,
              })
            : Promise.resolve(null),
        ]);
    
        // File-based context (non-graph)
        const pendingWork = countPendingWork();
        const lastDream = readLastDreamFromAudit() ?? lastDreamFromManifest();
    
        const hoursSinceLastDream = pendingWork.last_dream_run
          ? Math.round(((Date.now() - new Date(pendingWork.last_dream_run).getTime()) / (1000 * 60 * 60)) * 10) / 10
          : null;
    
        return toolResult({
          generated_at: new Date().toISOString(),
          graph_health: {
            nodes: statsResult.nodes.total,
            edges: statsResult.edges.total,
            by_node_type: statsResult.nodes.by_type,
            avg_weight: statsResult.health.avg_weight,
            orphaned: statsResult.health.orphaned_nodes,
            stale: statsResult.health.stale_nodes,
            unresolved_contradictions: statsResult.health.unresolved_contradictions,
          },
          pending_work: {
            unprocessed_transcripts: pendingWork.unprocessed_transcripts,
            pending_ingests: pendingWork.pending_ingests,
            last_dream_run: pendingWork.last_dream_run,
            hours_since_last_dream: hoursSinceLastDream,
          },
          last_dream: lastDream,
          recent_additions: {
            days: recentDays,
            entity_count: recent.nodes.length,
            edge_count: recent.edge_count,
            entities: recent.nodes,
          },
          top_hubs: hubs,
          contradictions: includeContradictions
            ? (contradictions as { contradictions: Array<Record<string, unknown>> }).contradictions
            : null,
          topic_neighbourhood: topicResult
            ? {
                topic: args.topic ?? "",
                node_count: topicResult.nodes.length,
                edge_count: topicResult.edges.length,
                nodes: topicResult.nodes.slice(0, 15),
                edges: topicResult.edges.slice(0, 25),
              }
            : null,
        });
      } catch (err) {
        const e = err instanceof Error ? err : new Error(String(err));
        return toolError(`graph_build_context failed: ${e.message}`);
      }
    });
  • Handler function that bundles graph health stats, recent additions, top hubs, contradictions, pending work, last dream info, and optional topic neighbourhood into a single response.
    }, async (args) => {
      try {
        const tenantId = currentTenant();
        const recentDays = args.recent_days ?? 7;
        const hubCount = args.hub_count ?? 5;
        const includeContradictions = args.include_contradictions ?? true;
        const maxRecent = args.max_recent ?? 15;
    
        // Run the graph queries in parallel — independent
        const [statsResult, recent, hubs, contradictions, topicResult] = await Promise.all([
          client.getStats(tenantId),
          client.getRecentAdditions(tenantId, recentDays, maxRecent),
          client.getTopHubs(tenantId, hubCount),
          includeContradictions
            ? client.findContradictions(tenantId, false)
            : Promise.resolve({ contradictions: [] as Array<Record<string, unknown>> }),
          args.topic
            ? client.query(tenantId, [args.topic], {
                max_hops: 2,
                min_weight: 0.3,
                limit: 15,
                project_context: args.project_cwd,
                current_only: true,
              })
            : Promise.resolve(null),
        ]);
    
        // File-based context (non-graph)
        const pendingWork = countPendingWork();
        const lastDream = readLastDreamFromAudit() ?? lastDreamFromManifest();
    
        const hoursSinceLastDream = pendingWork.last_dream_run
          ? Math.round(((Date.now() - new Date(pendingWork.last_dream_run).getTime()) / (1000 * 60 * 60)) * 10) / 10
          : null;
    
        return toolResult({
          generated_at: new Date().toISOString(),
          graph_health: {
            nodes: statsResult.nodes.total,
            edges: statsResult.edges.total,
            by_node_type: statsResult.nodes.by_type,
            avg_weight: statsResult.health.avg_weight,
            orphaned: statsResult.health.orphaned_nodes,
            stale: statsResult.health.stale_nodes,
            unresolved_contradictions: statsResult.health.unresolved_contradictions,
          },
          pending_work: {
            unprocessed_transcripts: pendingWork.unprocessed_transcripts,
            pending_ingests: pendingWork.pending_ingests,
            last_dream_run: pendingWork.last_dream_run,
            hours_since_last_dream: hoursSinceLastDream,
          },
          last_dream: lastDream,
          recent_additions: {
            days: recentDays,
            entity_count: recent.nodes.length,
            edge_count: recent.edge_count,
            entities: recent.nodes,
          },
          top_hubs: hubs,
          contradictions: includeContradictions
            ? (contradictions as { contradictions: Array<Record<string, unknown>> }).contradictions
            : null,
          topic_neighbourhood: topicResult
            ? {
                topic: args.topic ?? "",
                node_count: topicResult.nodes.length,
                edge_count: topicResult.edges.length,
                nodes: topicResult.nodes.slice(0, 15),
                edges: topicResult.edges.slice(0, 25),
              }
            : null,
        });
      } catch (err) {
        const e = err instanceof Error ? err : new Error(String(err));
        return toolError(`graph_build_context failed: ${e.message}`);
      }
    });
  • Input schema definition for graph_build_context with optional parameters: topic, project_cwd, recent_days, hub_count, include_contradictions, max_recent.
    inputSchema: {
      topic: z
        .string()
        .optional()
        .describe("Optional topic to fetch a neighbourhood for (uses graph_query under the hood)."),
      project_cwd: z
        .string()
        .optional()
        .describe("Optional project directory for affinity scoring on the topic neighbourhood."),
      recent_days: z
        .number()
        .int()
        .min(1)
        .max(90)
        .optional()
        .default(7)
        .describe("Window in days for 'recently added' entities (default 7)."),
      hub_count: z
        .number()
        .int()
        .min(1)
        .max(20)
        .optional()
        .default(5)
        .describe("Number of top knowledge hubs to include (default 5)."),
      include_contradictions: z
        .boolean()
        .optional()
        .default(true)
        .describe("Include unresolved contradictions (default true)."),
      max_recent: z
        .number()
        .int()
        .min(1)
        .max(50)
        .optional()
        .default(15)
        .describe("Max recent entities to list (default 15)."),
    },
  • Helper on Neo4jClient that queries recently added entities and edge counts within a time window. Called by the graph_build_context handler.
    async getRecentAdditions(tenantId: string, days: number, limit = 20): Promise<{
      nodes: Array<{ id: string; name: string; type: string; first_seen: string; confidence: number }>;
      edge_count: number;
    }> {
      const nodeRows = await this.run(
        `
        MATCH (n:Entity {tenant_id: $tenantId})
        WHERE n.first_seen > datetime() - duration({days: $days})
        RETURN n.id AS id,
               n.name AS name,
               [l IN labels(n) WHERE l <> 'Entity'][0] AS type,
               toString(n.first_seen) AS first_seen,
               n.confidence AS confidence
        ORDER BY n.first_seen DESC
        LIMIT $limit
        `,
        { tenantId, days, limit },
      );
    
      const edgeCountRows = await this.run(
        `
        MATCH (a:Entity {tenant_id: $tenantId})-[r]->(b:Entity {tenant_id: $tenantId})
        WHERE r.ingested_at IS NOT NULL
          AND r.ingested_at > datetime() - duration({days: $days})
        RETURN count(r) AS edge_count
        `,
        { tenantId, days },
      );
    
      return {
        nodes: nodeRows.map((r) => ({
          id: String(r["id"]),
          name: String(r["name"] ?? ""),
          type: String(r["type"] ?? "?"),
          first_seen: String(r["first_seen"] ?? ""),
          confidence: Number(r["confidence"] ?? 0),
        })),
        edge_count: Number(edgeCountRows[0]?.["edge_count"] ?? 0),
      };
    }
  • Helper on Neo4jClient that finds the most-connected entities (hubs) by degree. Called by the graph_build_context handler.
    async getTopHubs(tenantId: string, count = 5, weight_threshold = 0.3): Promise<Array<{
      id: string; name: string; type: string; degree: number; confidence: number;
    }>> {
      const rows = 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 >= 3
        RETURN n.id AS id,
               n.name AS name,
               [l IN labels(n) WHERE l <> 'Entity'][0] AS type,
               n.confidence AS confidence,
               degree
        ORDER BY degree DESC
        LIMIT $count
        `,
        { tenantId, threshold: weight_threshold, count },
      );
      return rows.map((r) => ({
        id: String(r["id"]),
        name: String(r["name"] ?? ""),
        type: String(r["type"] ?? "?"),
        degree: Number(r["degree"] ?? 0),
        confidence: Number(r["confidence"] ?? 0),
      }));
    }
Behavior4/5

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

The description adds value beyond the readOnlyHint annotation by detailing the specific data included in the bundled context. However, it does not disclose any additional behavioral traits such as performance implications or return size.

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 three sentences: first states purpose, second gives usage guidance, third quantifies benefit. No redundant information, perfectly front-loaded.

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?

Given the tool's complexity (6 optional parameters, no output schema), the description adequately explains what is returned. However, it lacks details on the exact format or structure of the output, which would be helpful for the agent.

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 coverage is 100%, providing baseline value. The description adds context by explaining that parameters like topic and project_cwd are for optional neighbourhood fetching and affinity scoring, linking them to the overall bundle purpose. This adds some meaning beyond the schema's 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 it bundles a session's worth of context, listing specific items like graph health, pending work, contradictions, etc. It also distinguishes itself from sibling tools by explicitly mentioning the individual tools it replaces (graph_stats, graph_query, graph_contradictions).

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?

It explicitly instructs to use the tool at session start instead of running separate tools, and quantifies the benefit as reducing round trips from 4-5 to 1. This provides clear when-to-use and alternative 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