Skip to main content
Glama

Prompt Compressor

Rule-based prompt compression β€” reduce LLM token usage without a model, without an API, without sending data anywhere.

npm npm MCP Live

⭐ Find it useful? Star it on GitHub Β· πŸ› Found a bug or have an idea? Open an issue


Three ways to use it

Web tool

prompt-compressor.com β€” paste a prompt, pick a risk level, review every change individually, download.

npm package

npm install prompt-compressor
import { compress } from 'prompt-compressor';

const { output, stats } = compress(systemPrompt, 'low');
// { tokensBefore: 1200, tokensAfter: 820, saved: 380, reductionPct: 31 }

MCP server (Claude, Cursor, VS Code, Windsurf)

Give your AI assistant compression tools. No install step, because your client runs it with npx.

Claude Code:

claude mcp add prompt-compressor -- npx -y prompt-compressor-mcp

Claude Desktop / Cursor / Windsurf (claude_desktop_config.json, ~/.cursor/mcp.json, ~/.codeium/windsurf/mcp_config.json):

{
  "mcpServers": {
    "prompt-compressor": {
      "command": "npx",
      "args": ["-y", "prompt-compressor-mcp"]
    }
  }
}

VS Code (.vscode/mcp.json):

{
  "servers": {
    "prompt-compressor": { "type": "stdio", "command": "npx", "args": ["-y", "prompt-compressor-mcp"] }
  }
}

Tool

What it does

compress_prompt

Compress text at a chosen risk level and return token stats

compress_file

Compress a local file (read-only, the file is not modified)

compare_levels

Show the savings at every risk level side by side

estimate_tokens

Quick token count

Then just ask: "Compress the system prompt in prompts/support.md at low risk and show how many tokens it saves." More details are in the MCP package README.


Related MCP server: winnow

Why

Token costs on Bedrock (and other LLM APIs) add up fast β€” system prompts, tool descriptions, conversation history, RAG context. All of it gets sent on every call.

Most compression tools require a model to compress, which defeats the purpose. This uses deterministic rules only β€” no model, no API, nothing leaves your process.


Risk levels

Pick a level β€” every algorithm at or below that risk runs automatically.

Level

What runs

Typical saving

'none'

Whitespace, unicode normalization, indentation

5–15%

'very-low'

+ Filler removal, phrase shortening, JSON/SQL minify

15–30%

'low'

+ Hedging removal, code comments, deduplication, stack traces

25–45%

'medium'

+ TF-IDF, TextRank, fuzzy/n-gram/Levenshtein dedup

30–70%


npm package usage

// Simple
const { output, stats } = compress(text, 'low');

// With overrides
const { output, stats } = compress(text, {
  level: 'low',
  tfidf: true,
  tfidfRatio: 0.7,
  codeComments: false,  // disable a step
});

// Individual functions
import { removeFiller, tfidfCompress, deduplicateLines } from 'prompt-compressor';

Inside your own MCP server or Bedrock pipeline

import { compress } from 'prompt-compressor';

// Before every API call:
const { output } = compress(systemPrompt, 'low');
const response = await bedrock.invokeModel({ body: JSON.stringify({ system: output, messages }) });

Variable protection

Prompt variables are automatically detected and preserved β€” compression never breaks templates.

Supported: {{var}}, {var}, ${var}, <tag>, [[var]], %VAR%


Algorithms (30+)

Algorithm

Risk

What it does

compressWhitespace

none

Collapse spaces, tabs, excess blank lines

normalizeUnicode

none

Smart quotes, em-dash, zero-width chars

cleanPunctuation

none

!!! β†’ !, ??? β†’ ?

stripLicenseHeaders

none

Remove copyright blocks from code

normalizeIndentation

none

4-space β†’ 2-space in code blocks

removeFiller

very-low

Remove "please note that", "e.g.", "i.e." clauses

shortenPhrases

very-low

"in order to" β†’ "to", "utilize" β†’ "use" (50+ rules)

numberWordsToNumerals

very-low

"twenty" β†’ "20"

normalizeDates

very-low

"Monday, Dec 25th 2023" β†’ "2023-12-25"

minifyJSON

very-low

Minify JSON code blocks

minifySQL

very-low

Remove SQL comments, collapse whitespace

removeHedging

low

Remove "perhaps", "it seems", "one might say"

removeMetaCommentary

low

Remove "Here is...", "I hope this helps"

removeParentheticals

low

Remove "(as mentioned above)", "(see below)"

stripCodeComments

low

Remove //, /* */, # comments

stripDocstrings

low

Remove Python/JSDoc documentation blocks

removeNullJsonFields

low

Strip null/empty fields from JSON

stripBase64AndHex

low

Replace long hashes with placeholders

truncateStackTraces

low

Keep 4 frames, replace rest with count

deduplicateLines

low

Remove duplicate lines

deduplicateSentences

low

Remove duplicate sentences

fuzzyDeduplicate

medium

Jaccard-based near-duplicate removal

ngramDeduplicate

medium

Bigram/trigram near-duplicate removal

levenshteinDeduplicate

medium

Edit-distance near-duplicate removal

tfidfCompress

medium

Keep top sentences by TF-IDF score

textRankCompress

medium

PageRank-style sentence centrality

extractiveCompress

medium

Keep top sentences by Term Frequency


Repository structure

/                        ← web app (React + Vite)
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ compression.js   ← all compression logic
β”‚   β”œβ”€β”€ App.jsx          ← UI
β”‚   β”œβ”€β”€ ReviewDiffView.jsx
β”‚   └── ...
    β”œβ”€β”€ npm-package/     ← npm package `prompt-compressor` (separate, zero shared code)
    β”‚   β”œβ”€β”€ src/
    β”‚   β”‚   β”œβ”€β”€ algorithms.js
    β”‚   β”‚   └── protect.js
    β”‚   β”œβ”€β”€ test/
    β”‚   β”œβ”€β”€ index.js
    β”‚   β”œβ”€β”€ index.d.ts
    β”‚   └── package.json
    └── mcp-package/     ← MCP server `prompt-compressor-mcp` (uses the npm package)
        β”œβ”€β”€ index.js     ← tools: compress_prompt, compress_file, compare_levels, estimate_tokens
        β”œβ”€β”€ bin.js       ← stdio entry point
        β”œβ”€β”€ test/
        └── server.json  ← MCP registry manifest

Releasing

Bump version in src/npm-package/package.json and/or src/mcp-package/package.json, then merge to main. The Release to npm workflow publishes any version that isn't on npm yet, library first and then the MCP server. It needs the NPM_TOKEN secret. Pushing an npm-v* / mcp-v* tag or using "Run workflow" also works.


Run the web app locally

npm install
npm run dev

Open http://localhost:5173


License

MIT β€” Tom Ketter

Available Tools

4 tools
compare_levelsCompare compression levelsA
Read-only

Run every risk level on the same text and report token savings for each, so you can pick the right trade-off.

Inputs: text (required).

compress_fileCompress fileA
Read-only

Read a local text file (prompt, docs, logs, JSON, code) and return a compressed version with token stats. Does not modify the file.

Inputs: path (required), level.

compress_promptCompress promptA
Read-only

Compress a prompt, system prompt, or context block to use fewer tokens, using deterministic rule-based algorithms (no LLM call). Template variables like {{name}} and {var} are preserved. Returns the compressed text and token stats.

Inputs: text (required), level.

estimate_tokensEstimate tokensA
Read-only

Estimate the token count of a text (fast heuristic, no tokenizer download).

Inputs: text (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 4 tools

    Disambiguation4/5

    Each tool has a distinct input mode (raw text vs. file path) and a distinct action (compress, compare, estimate), so misselection is unlikely. The only mild overlap is that estimate_tokens returns token counts that the compress tools also report, but the descriptions make the fast-heuristic-only purpose clear.

    Naming Consistency5/5

    All four names use snake_case with a verb_noun pattern (compress_prompt, compress_file, compare_levels, estimate_tokens). The two compress_* tools share a prefix that correctly signals a shared operation with different targets.

    Tool Count5/5

    Four tools is well-scoped for a narrow prompt-compression utility: text compression, file compression, level comparison, and token estimation. Each tool covers a genuinely different need with no filler.

    Completeness4/5

    The core lifecycle (estimate cost, compress input, compress file, tune the risk/savings trade-off) is fully covered with no dead ends. Minor gaps remain around batch/directory processing and a way to inspect or restore what was changed, but agents can work around these with repeated calls.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Provides code-aware context compression by stripping comments, docstrings, and whitespace while maintaining full logic fidelity for AI agents. It features tools for architectural mapping, symbol searching, and token-budgeted multi-file reading.
      9
      4
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables semantic prompt compression for LLM workflows, reducing token usage by 30-70% while preserving semantic meaning.
      12
      MIT
    • F
      license
      Not graded
      quality
      B
      maintenance
      Shrinks logs, JSON, docs and web pages before your AI reads them: offline, deterministic, no API key. Folds repetitive log lines (12,037 to 127 tokens on a 400-line log) while code, URLs and quoted strings come back byte-for-byte. Also fetches URLs as clean text, counts tokens exactly, and has optional local Ollama tools for image and text compression.
      73 PyPI
      25
      -