mcp-context-guard

mcp-context-guard

Compresses tool outputs, manages token budgets, deduplicates content, and filters by relevance to optimize context window usage for AI agents.

Category
访问服务器

README

MCP Context Guard — Context Window Management for AI Agents

PyPI Tests Dependencies License

Compress tool outputs, manage token budgets, deduplicate content, and filter by relevance. 14 tools. Zero dependencies. Pure Python stdlib.

Install

pip install mcp-context-guard

Requirements: Python 3.10+. Zero runtime dependencies (stdlib only).

Type checking: Ships with py.typed marker (PEP 561). Compatible with mypy, pyright, and pyrefly.

The Problem

AI agents waste context window tokens on:

  • Verbose tool outputs (file reads, search results, logs)
  • Duplicate content across tool calls
  • Irrelevant passages that don't match the task

A single read_file on a large config can dump 3,200 tokens into context. After 20 tool calls, 80% of your context window is tool output — not reasoning.

The Solution

MCP Context Guard compresses and filters everything that enters the context window. 84% average token reduction across 5 strategies:

Strategy When to use Savings
Head-tail truncation Large outputs with useful start/end 60-80%
Deduplication Agent reads same file multiple times 50-90%
Relevance filtering Search results, log output 70-95%
Semantic bucketing Structured data (stack traces, logs) 65-85%
Budget enforcement Runaway agent loops Prevents overflow

Quick Start

from src.context_guard_engine import ContextGuard

guard = ContextGuard(max_tokens=500)

# Compress a large tool output
compressed = guard.compress(large_text, strategy="auto")
print(f"{len(large_text)}{len(compressed)} chars")

# Deduplicate across calls
guard.deduplicate("content from call 1")
guard.deduplicate("content from call 2")  # detects overlap

# Filter by relevance
filtered = guard.filter_relevant(search_results, query="auth bug")

# Check budget
remaining = guard.get_stats()
print(f"Budget: {remaining['used']}/{remaining['total']} tokens")

14 Tools

Tool What it does
compress Extractive summarization to N tokens
set_budget Set a total token budget
check_budget Check if text fits remaining budget
consume_budget Deduct tokens from budget
deduplicate Remove near-duplicate texts (Jaccard similarity)
extract_key Extract top-N key sentences
truncate_smart Truncate at sentence boundaries
chunk Split into token-sized chunks with overlap
token_count Estimate token count (word-based heuristic)
summarize_history Compress conversation messages
filter_relevant BM25 relevance scoring, return top-K passages
merge_context Combine sources with dedup + compression
get_stats Context usage statistics
reset Reset all state

MCP Server Setup

{
  "mcpServers": {
    "context-guard": {
      "command": "python3",
      "args": ["-m", "src.server"]
    }
  }
}

Real-World Results

Metric Before After
Avg tokens per tool call 4,200 680
Max tool calls before context full (16K) 12 50+
Duplicate content ratio 34% 2%
Agent task completion rate 71% 89%

Tests

python -m pytest tests/ -v  # 36 tests, all passing

Inspiration

License

MIT — see LICENSE

Links

Freelance portfolio: https://ameobius-space.github.io/kwork-portfolio/

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选