Skip to main content
Glama

Build Session Context

graph_build_context
Read-only

Obtain a unified session context: graph health, pending work, dream summary, recent entries, top hubs, contradictions, and optional topic neighborhood—all in one call.

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 its title, description, inputSchema, and annotations.
    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) => {
  • Handler function that bundles session context: graph health stats, pending work, last dream run, recent additions, top knowledge hubs, contradictions, and optional topic neighbourhood.
    }, 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 defining 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)."),
    },
    annotations: { readOnlyHint: true },
  • Helper function that reads the dream audit log to extract the most recent dream run's start and end events.
    function readLastDreamFromAudit(): {
      started_at: string;
      ended_at: string | null;
      duration_ms: number | null;
      source: string | null;
      transcripts_processed: number | null;
      ingest_processed: number | null;
      entities_created: number | null;
      edges_created: number | null;
      errors: number | null;
    } | null {
      const auditPath = join(GRAPH_MEMORY_HOME, "logs", "dream-audit.jsonl");
      let raw: string;
      let didTruncate = false;
      try {
        const stats = statSync(auditPath);
        const tailBytes = Math.min(stats.size, 32768);
        didTruncate = stats.size > tailBytes;
        const fd = openSync(auditPath, "r");
        try {
          const buf = Buffer.alloc(tailBytes);
          readSync(fd, buf, 0, tailBytes, stats.size - tailBytes);
          raw = buf.toString("utf-8");
        } finally {
          closeSync(fd);
        }
      } catch {
        return null;
      }
    
      // Parse the lines we got (drop the first one if we may have started mid-line)
      const lines = raw.split("\n").filter((l) => l.trim().length > 0);
      if (lines.length === 0) return null;
      if (didTruncate) lines.shift();
    
      let lastStart: Record<string, unknown> | null = null;
      let lastEnd: Record<string, unknown> | null = null;
      for (const line of lines) {
        try {
          const evt = JSON.parse(line) as Record<string, unknown>;
          if (evt["event"] === "run_start") {
            lastStart = evt;
            lastEnd = null;
          } else if (evt["event"] === "run_end") {
            lastEnd = evt;
          }
        } catch { /* skip bad lines */ }
      }
    
      if (!lastStart) return null;
    
      return {
        started_at: String(lastStart["timestamp"] ?? ""),
        ended_at: lastEnd ? String(lastEnd["timestamp"] ?? "") : null,
        duration_ms: lastEnd ? Number(lastEnd["duration_ms"] ?? 0) : null,
        source: String(lastStart["source"] ?? "") || null,
        transcripts_processed: lastEnd ? Number(lastEnd["transcripts_processed"] ?? 0) : null,
        ingest_processed: lastEnd ? Number(lastEnd["ingest_processed"] ?? 0) : null,
        entities_created: lastEnd ? Number(lastEnd["entities_created"] ?? 0) : null,
        edges_created: lastEnd ? Number(lastEnd["edges_created"] ?? 0) : null,
        errors: lastEnd ? Number(lastEnd["errors"] ?? 0) : null,
      };
    }
  • Fallback helper that reads the manifest to synthesize a last_dream record when the audit log is missing.
    /** Read the manifest and synthesize a minimal last_dream record from it. Used when dream-audit.jsonl is missing or pre-dates the audit log feature. */
    function lastDreamFromManifest(): {
      started_at: string;
      ended_at: string | null;
      duration_ms: number | null;
      source: string | null;
      transcripts_processed: number | null;
      ingest_processed: number | null;
      entities_created: number | null;
      edges_created: number | null;
      errors: number | null;
    } | null {
      try {
        const manifestPath = join(GRAPH_MEMORY_HOME, "processed", "manifest.json");
        const manifest = JSON.parse(readFileSync(manifestPath, "utf-8")) as {
          last_dream_run?: string | null;
          processed?: Record<string, { processed_at?: string; entities_extracted?: number; edges_created?: number }>;
        };
        if (!manifest.last_dream_run) return null;
    
        // Sum stats for transcripts whose processed_at is within 1 hour of last_dream_run
        const lastRun = new Date(manifest.last_dream_run).getTime();
        let entitiesCreated = 0;
        let edgesCreated = 0;
        let transcriptsProcessed = 0;
        for (const entry of Object.values(manifest.processed ?? {})) {
          if (!entry.processed_at) continue;
          const t = new Date(entry.processed_at).getTime();
          if (Math.abs(t - lastRun) > 1000 * 60 * 60) continue;
          transcriptsProcessed++;
          entitiesCreated += entry.entities_extracted ?? 0;
          edgesCreated += entry.edges_created ?? 0;
        }
    
        return {
          started_at: manifest.last_dream_run,
          ended_at: null,
          duration_ms: null,
          source: "manifest",
          transcripts_processed: transcriptsProcessed,
          ingest_processed: null,
          entities_created: entitiesCreated,
          edges_created: edgesCreated,
          errors: null,
        };
      } catch {
        return null;
      }
    }
  • Helper function that scans filesystem for unprocessed transcripts and pending ingest documents.
    function countPendingWork(): { unprocessed_transcripts: number; pending_ingests: number; last_dream_run: string | null } {
      let lastDreamRun: string | null = null;
      let processedIds = new Set<string>();
      try {
        const manifestPath = join(GRAPH_MEMORY_HOME, "processed", "manifest.json");
        const manifest = JSON.parse(readFileSync(manifestPath, "utf-8")) as {
          last_dream_run?: string | null;
          processed?: Record<string, unknown>;
        };
        lastDreamRun = manifest.last_dream_run ?? null;
        processedIds = new Set(Object.keys(manifest.processed ?? {}));
      } catch { /* no manifest yet */ }
    
      let unprocessed = 0;
      try {
        const projectsDir = join(homedir(), ".claude", "projects");
        const projectDirs = readdirSync(projectsDir, { withFileTypes: true });
        for (const dir of projectDirs) {
          if (!dir.isDirectory()) continue;
          try {
            const files = readdirSync(join(projectsDir, dir.name));
            for (const f of files) {
              if (!f.endsWith(".jsonl") || f.startsWith("agent-")) continue;
              const sid = f.replace(".jsonl", "");
              if (!processedIds.has(sid)) unprocessed++;
            }
          } catch { /* skip */ }
        }
      } catch { /* projects dir missing */ }
    
      let pending = 0;
      try {
        pending = readdirSync(join(GRAPH_MEMORY_HOME, "ingest", "pending"))
          .filter((f) => !f.endsWith(".meta.json") && !f.endsWith(".error"))
          .length;
      } catch { /* dir missing */ }
    
      return { unprocessed_transcripts: unprocessed, pending_ingests: pending, last_dream_run: lastDreamRun };
    }
Behavior4/5

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

Annotations already declare readOnlyHint=true; description adds detail on what context is bundled (e.g., topic neighbourhood option) without contradicting annotations. No extra behavioral traits needed beyond stated scope.

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, no wasted words. Front-loads the key benefit and enumerates components efficiently. Perfectly concise for the complexity.

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?

No output schema, but description itemizes return components (graph health, pending work, etc.) and lists optional parameters. Complete enough for a session-start tool with clear usage context.

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

Parameters3/5

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

Schema coverage is 100%, so baseline 3 is appropriate. Description adds context like 'uses graph_query under the hood' for topic param but mainly mirrors schema descriptions. Adequate but not exceptional.

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?

Description explicitly states it bundles session context (graph health, pending work, etc.) and names sibling tools it replaces (graph_stats, graph_query, graph_contradictions), making its purpose and differentiation clear.

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?

Provides explicit guidance: 'Use this at session start instead of running ... separately' and quantifies benefit ('Cuts 4-5 round trips to one'), clearly indicating when and why to use it over 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