Skip to main content
Glama

Run the compression pipeline now

memory_compress

Cluster similar project memories by embedding similarity, merge each cluster into a canonical memory, and mark originals as compressed. Use after bulk import or to sanity-check compression. Requires compression.enabled=true.

Instructions

Force one compression cycle now: cluster similar memories by embedding similarity, merge each cluster into a canonical memory, and mark originals as compressed. Use after a bulk import or to sanity-check compression. Compression normally runs on the maintenance schedule. Side effects: writes merged memories, updates originals' compressed_into pointer, may call embeddings + LLM providers. Requires compression.enabled=true; otherwise returns a no-op message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_pathNoAbsolute project path to compress. Empty string (default) compresses every project.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
messageYesSummary line per project, e.g. `Compressed 3 cluster(s) in project <id>`, or `No clusters to compress.` Returns a no-op message when `compression.enabled=false`.

Implementation Reference

  • Main handler for the memory_compress tool. Accepts an optional project_path parameter, resolves projects, runs runCompressionCycle for each, and returns a summary of compression results (clusters, token reductions).
    export async function handleMemoryCompress(
      db: Database.Database,
      config: Config,
      params: { project_path?: string },
    ): Promise<string> {
      if (!config.compression.enabled) {
        return "Compression is disabled in config (compression.enabled = false).";
      }
    
      const compCfg = toCompressionConfig(config);
    
      let projectIds: string[];
      if (params.project_path) {
        const row = db
          .prepare("SELECT id FROM projects WHERE root_path = ?")
          .get(params.project_path) as { id: string } | undefined;
        if (!row) {
          return `No project found for path ${params.project_path}.`;
        }
        projectIds = [row.id];
      } else {
        projectIds = (db.prepare("SELECT id FROM projects").all() as Array<{ id: string }>).map(r => r.id);
      }
    
      if (projectIds.length === 0) {
        return "No projects to compress.";
      }
    
      let totalClusters = 0;
      let totalTokensBefore = 0;
      let totalTokensAfter = 0;
      const perProject: string[] = [];
    
      for (const projectId of projectIds) {
        const results = runCompressionCycle(db, projectId, compCfg);
        if (results.length === 0) continue;
        totalClusters += results.length;
        const tokensBefore = results.reduce((acc, r) => acc + r.tokens_before, 0);
        const tokensAfter = results.reduce((acc, r) => acc + r.tokens_after, 0);
        totalTokensBefore += tokensBefore;
        totalTokensAfter += tokensAfter;
        perProject.push(`  - project ${projectId}: ${results.length} cluster(s), ${tokensBefore}→${tokensAfter} tokens`);
      }
    
      if (totalClusters === 0) {
        return "No clusters found to compress.";
      }
    
      const savings = totalTokensBefore > 0
        ? Math.round((1 - totalTokensAfter / totalTokensBefore) * 100)
        : 0;
    
      return (
        `Compressed ${totalClusters} cluster(s) across ${perProject.length} project(s).\n` +
        `Tokens: ${totalTokensBefore} → ${totalTokensAfter} (${savings}% reduction).\n` +
        perProject.join("\n")
      );
    }
  • Tool registration with input/output schemas: input expects project_path (string, default ''), output returns a message string describing compression results.
    server.registerTool(
      "memory_compress",
      {
        title: "Run the compression pipeline now",
        description: [
          "Force one compression cycle now: cluster similar memories by embedding similarity, merge each cluster into a canonical memory, and mark originals as compressed.",
          "Use after a bulk import or to sanity-check compression. Compression normally runs on the maintenance schedule.",
          "Side effects: writes merged memories, updates originals' `compressed_into` pointer, may call embeddings + LLM providers. Requires `compression.enabled=true`; otherwise returns a no-op message.",
        ].join(" "),
        inputSchema: {
          project_path: z.string().default("").describe("Absolute project path to compress. Empty string (default) compresses every project."),
        },
        annotations: {
          title: "Run the compression pipeline now",
          readOnlyHint: false,
          destructiveHint: false,
          idempotentHint: false,
          openWorldHint: true,
        },
        outputSchema: {
          message: z.string().describe("Summary line per project, e.g. `Compressed 3 cluster(s) in project <id>`, or `No clusters to compress.` Returns a no-op message when `compression.enabled=false`."),
        },
  • src/index.ts:596-620 (registration)
    Registration of the 'memory_compress' tool on the MCP server, with title, description, input/output schemas, annotations, and the handler callback.
    server.registerTool(
      "memory_compress",
      {
        title: "Run the compression pipeline now",
        description: [
          "Force one compression cycle now: cluster similar memories by embedding similarity, merge each cluster into a canonical memory, and mark originals as compressed.",
          "Use after a bulk import or to sanity-check compression. Compression normally runs on the maintenance schedule.",
          "Side effects: writes merged memories, updates originals' `compressed_into` pointer, may call embeddings + LLM providers. Requires `compression.enabled=true`; otherwise returns a no-op message.",
        ].join(" "),
        inputSchema: {
          project_path: z.string().default("").describe("Absolute project path to compress. Empty string (default) compresses every project."),
        },
        annotations: {
          title: "Run the compression pipeline now",
          readOnlyHint: false,
          destructiveHint: false,
          idempotentHint: false,
          openWorldHint: true,
        },
        outputSchema: {
          message: z.string().describe("Summary line per project, e.g. `Compressed 3 cluster(s) in project <id>`, or `No clusters to compress.` Returns a no-op message when `compression.enabled=false`."),
        },
      },
      async (params) => textResult(await handleMemoryCompress(db, config, params))
    );
  • runCompressionCycle: selects non-compressed memories, clusters them, merges each cluster, and applies compression within a database transaction.
    export function runCompressionCycle(
      db: Database.Database,
      projectId: string,
      config: CompressionConfig,
    ): CompressionResult[] {
      const results: CompressionResult[] = [];
    
      const tx = db.transaction(() => {
        const rows = db
          .prepare(
            `
            SELECT * FROM memories
            WHERE project_id = ? AND deleted_at IS NULL AND source != 'compression'
            ORDER BY created_at DESC LIMIT 200
          `,
          )
          .all(projectId) as MemoryRecord[];
    
        const clusters = clusterMemories(rows, config);
        for (const cluster of clusters) {
          const merged = mergeCluster(cluster);
          applyCompression(db, merged);
          results.push(merged);
        }
      });
    
      tx();
      return results;
    }
  • toCompressionConfig: maps the user-facing config to the engine's CompressionConfig type used by the compression pipeline.
    export function toCompressionConfig(config: Config): CompressionConfig {
      return {
        cluster_similarity_threshold: config.compression.clusterSimilarityThreshold,
        min_cluster_size: config.compression.minClusterSize,
        max_body_ratio: config.compression.maxBodyRatio,
        temporal_window_hours: config.compression.temporalWindowHours,
      };
    }
Behavior4/5

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

The description discloses side effects (writes merged memories, updates pointers, may call external providers) and the config requirement, adding valuable context beyond the annotations. There is no contradiction with 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 three concise sentences, front-loading the core action and usage. Every sentence adds value without redundancy.

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 presence of an output schema, return values need not be described. The description covers purpose, usage, side effects, and prerequisites. It lacks details on performance or data volume but is otherwise complete.

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 description coverage is 100% for the single parameter, and the description repeats the schema's description. No additional meaning is added, so baseline of 3 is appropriate.

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's action: forcing a compression cycle with specific steps (cluster, merge, mark). It identifies the resource (memories) and distinguishes from the maintenance schedule, which is a sibling context.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly suggests using the tool after bulk import or to sanity-check compression, and notes that compression normally runs via schedule. It also mentions the prerequisite config flag. However, it does not explicitly state when not to use or suggest alternative sibling tools.

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/lfrmonteiro99/memento-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server