context-diamond
This server provides tools to compress text and files into structured, auditable Context Diamond capsules for LLM handoffs, and to benchmark compression performance.
compress_text: Compresses raw text, chat transcripts, logs, or notes into a Context Diamond capsule. Configurable options include title, token budget, output format (markdown or JSON), tokenizer profile, and optional loss/audit report.compress_file: Reads a UTF-8 text or Markdown file from disk and compresses it into a context capsule, supporting the same configuration options ascompress_text.benchmark_file: Benchmarks Context Diamond compression against a head/tail clipping baseline for a given file, with configurable token budget, output format, and tokenizer profile — helping you measure compression quality and token savings.
Captures repository state including branch, git status, and selected files to produce a context capsule for codebase handoffs.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@context-diamondcompress my sprint handoff to 300 tokens"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Context Diamond v0.7.0
Stop pasting the same messy context into every LLM. Turn chats, logs, issues, agent state, and docs into small, auditable context capsules.
Context Diamond v0.7.0 is a deterministic context compression and handoff toolkit for LLM agents. It extracts the things models keep losing in long conversations:
goals and success criteria
hard constraints
decisions already made
current working state
open questions and risks
files, symbols, entities, and anchors
It is built for developers who switch between coding agents, OpenCode, chat UIs, RAG pipelines, issue threads, and local notes. The default engine is offline, zero-dependency, inspectable, and safe to run before any text is sent to an LLM.
Why People Click This
Most LLM context tools promise "memory". Context Diamond gives you a portable handoff artifact you can read, diff, benchmark, paste, store, or feed to another agent.
Use it when you want to:
recover signal from noisy agent sessions
reduce repeated prompt/context cost
preserve constraints before handing work to another model
keep decisions visible instead of buried in a paragraph summary
audit what got dropped with a loss report
expose compression as an OpenCode MCP tool
Related MCP server: personal-kg-mcp
60-Second Demo
Install from GitHub:
pip install git+https://github.com/RainCherb/context-diamond.gitCompress a long handoff:
context-diamond examples/long_handoff.md --budget 320 --title "Sprint Handoff"Get JSON with an audit trail:
context-diamond examples/long_handoff.md --format json --loss-reportBenchmark it against dumb head/tail clipping:
context-diamond-bench examples/long_handoff.md --budget 320Inspect why shards were selected:
ctxd explain examples/long_handoff.mdBuild a capsule from a repository:
ctxd repo . --budget 1200Compare or merge capsules as the handoff evolves:
ctxd diff old_capsule.json new_capsule.json
ctxd merge chat.json repo.json issue.json --budget 900Batch-process multiple files:
ctxd batch notes/*.md --output-dir capsules/ --budget 400 --template codingUse a domain-specific template:
context-diamond incident_report.md --template incident --budget 500Stream capsules incrementally:
from context_diamond import StreamingCompressor
streamer = StreamingCompressor()
streamer.add_message("Goal: build a login form.")
streamer.add_message("Decision: use JWT tokens.")
capsule = streamer.current_capsuleExample benchmark output:
535 source tokens -> 387 rendered capsule tokens
1.38x ratio
constraints:1.00 decisions:1.00 risks:1.00 code:1.00Direct Token Savings
Context Diamond can automatically adapt compression to your target LLM's context window, apply multi-level cascade compression, or transparently intercept messages before they reach an API.
Adaptive Compression
Compress only when text exceeds the model's usable context:
context-diamond long_handoff.md --model gpt-4oRecognised models: gpt-4o, gpt-4o-mini, claude-3-opus, claude-3-sonnet,
claude-3-haiku, gemini-1.5-pro, gemini-1.5-flash, llama-3-70b,
llama-3-8b.
from context_diamond import AdaptiveCompressor
adaptive = AdaptiveCompressor()
result = adaptive.compress(long_text, model_name="claude-3-opus")
# result.was_compressed -> True/False
# result.original_tokens -> 45000
# result.final_tokens -> 1800
# result.text -> capsule markdown or originalCascade Compression
Multi-level aggressive squeeze (800 -> 400 -> 200 tokens):
context-diamond very_long_doc.md --cascade --cascade-levels 3from context_diamond import CascadeCompressor
cascade = CascadeCompressor()
capsule = cascade.compress(extremely_long_text)Middleware (Transparent API Savings)
Auto-compress messages before sending to an LLM:
from context_diamond import AutoCompressMiddleware
middleware = AutoCompressMiddleware(threshold_tokens=1200)
compressed = middleware.compress_messages(messages, model_name="gpt-4o")
# compressed messages have _compressed metadata
print(middleware.savings_report())
# {'tokens_saved': 42000, 'savings_percentage': 87.5}The Pitch
Generic summaries are cheap, but they often flatten the one thing you needed to keep. Context Diamond keeps the handoff structured:
Problem | Context Diamond answer |
"The model forgot the rules." | Rules live in their own section. |
"We reopened an old decision." | Decisions are extracted separately. |
"The transcript is mostly noise." | Noise is scored down and shown in loss reports. |
"I need this in OpenCode." | Run it as a local MCP server. |
"I do not want another API bill." | No runtime API calls by default. |
OpenCode MCP
Add Context Diamond to OpenCode as a local MCP server:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"context_diamond": {
"type": "local",
"command": ["context-diamond-mcp"],
"enabled": true,
"timeout": 30000
}
}
}OpenCode tools (prefixed with context_diamond_):
Compression:
compress_text,compress_file,batch_compressExplainability:
explain_textRepository:
repo_capsuleBenchmark:
benchmark_fileStreaming:
streaming_add,streaming_get,streaming_resetDiscovery:
list_templates,list_tokenizers,get_template_info
See docs/opencode.md.
CLI
# Markdown capsule
context-diamond notes.md --budget 500 --output capsule.md
# JSON capsule for automation
context-diamond notes.md --format json --loss-report --output capsule.json
# Explain shard scoring
ctxd explain notes.md
# Repository capsule
ctxd repo . --budget 1200
# Capsule evolution
ctxd diff old.json new.json
ctxd merge chat.json repo.json --output merged.md
# Stdin
type notes.md | context-diamond - --budget 350
# Precise tokenizers (optional extras)
context-diamond notes.md --tokenizer tiktoken --budget 500Use a JSON message list:
context-diamond conversation.json --messages-json --format json[
{"role": "user", "content": "Build a local context compressor."},
{"role": "assistant", "content": "Decision: use deterministic extraction first."}
]Python API
from context_diamond import CompressionConfig, ContextDiamondCompressor
text = """
Goal: reduce token waste in LLM handoffs.
The tool must run locally and avoid API keys by default.
Decision: emit markdown and JSON capsules.
"""
compressor = ContextDiamondCompressor(CompressionConfig(token_budget=220))
capsule = compressor.compress(text)
print(capsule.to_markdown())Integration helpers:
from context_diamond import compress_documents, compress_messages, compress_tool_payloadSee docs/integrations.md.
What The Capsule Looks Like
# Context Diamond Capsule
- Strategy: `diamond-v1`
- Source tokens: `535`
- Capsule tokens: `315`
- Compression ratio: `1.7x`
## Diamond Pulse
- The strongest signals from the source.
## Rules And Constraints
- Requirements that should not be violated.
## Decisions Already Made
- Choices that should not be reopened accidentally.
## Open Questions And Risks
- Unresolved items that need attention.Why This Over X
Context Diamond is not trying to replace every prompt compressor, RAG compressor, or memory store. It is best at one job:
create auditable context capsules for LLM and coding-agent handoffs.
Read the honest comparison in docs/why-context-diamond.md.
Features
Offline by default: no hidden network calls.
Zero runtime dependencies: install it into boring environments.
OpenCode-ready: ships a local stdio MCP server.
Benchmarkable: compare against deterministic clipping baselines.
Auditable: optional loss report shows omitted shards.
Explainable:
ctxd explainshows shard facets, scores, tokens, and reasons.Repo-aware:
ctxd repocaptures branch, git state, and selected files.Composable capsules:
ctxd diffandctxd mergesupport handoff evolution.Structured: goals, rules, decisions, facts, state, risks, anchors.
Composable: CLI, Python API, JSON output, adapters, MCP.
Precise tokenizers: optional
tiktoken,anthropic, andtransformersadapters.Templates: domain-specific presets (
coding,support,research,incident).Streaming:
StreamingCompressorfor incremental capsule updates.Batch processing:
ctxd batchfor multiple files.
Docs
Local Development
git clone https://github.com/RainCherb/context-diamond.git
cd context-diamond
python -m venv .venv
.\.venv\Scripts\activate
pip install -e ".[dev]"
python -m pytest
python -m ruff check .On macOS or Linux, activate with source .venv/bin/activate.
Roadmap
Larger public benchmark corpus with task-level answer quality checks.
Domain-adapted embedding reranker profiles.
More first-class agent adapters: GitHub issues, Linear, Slack, Markdown logs.
Extended plugin hooks for custom facet detection and scoring.
PyPI release after the public API stabilizes.
Star This If
you lose context when switching between LLM tools
you want OpenCode agents to compress handoffs before continuing
you prefer inspectable local tools over another black-box summarizer
you like boring, deterministic software that saves expensive tokens
MIT licensed. Built to be small, honest, and useful.
Available Tools
3 toolsbenchmark_fileC
Benchmark Context Diamond against head/tail clipping for one file.
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Path to a UTF-8 text file. | |
| budget | No | Target section token budget. | |
| profile | No | generic | |
| format | No | markdown |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description must disclose behavior. It does not explain if the tool is read-only, what side effects exist, or what output is produced.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The single sentence is concise but too brief. It could include a bit more context without losing efficiency.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given four parameters and no output schema, the description fails to explain the benchmark's results, what 'Context Diamond' means, or how the parameters influence the outcome.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The description provides no additional meaning beyond the input schema. Although schema descriptions exist for each parameter, the tool description does not connect them to the benchmark purpose.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states the specific action: benchmarking Context Diamond against head/tail clipping for one file. It clearly distinguishes from sibling tools that compress files or text.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance on when to use this tool versus alternatives, no prerequisites, and no examples of how to invoke it correctly.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
compress_fileC
Compress a UTF-8 text/markdown file into a context capsule.
| Name | Required | Description | Default |
|---|---|---|---|
| budget | No | Target section token budget. | |
| title | No | Capsule title. | OpenCode Context Capsule |
| format | No | markdown | |
| loss_report | No | Include kept/omitted shard audit data in JSON metadata. | |
| tokenizer_profile | No | generic | |
| path | Yes | Path to a UTF-8 text or markdown file. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description must disclose all behavioral traits. It mentions the core transformation but omits side effects (e.g., does it modify the original file?), permissions, or return value. This leaves agents uncertain about the tool's impact.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is very concise (one sentence) with no wasted words, but it is under-specified for the complexity of the tool. A slightly longer description would be more appropriate.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool has 6 parameters, no output schema, and no annotations, the description is severely incomplete. It fails to explain output, usage context, or parameter interdependencies, making it nearly useless for proper tool invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 67%, but the description adds no additional meaning beyond what the schema provides. Key parameters like format, budget, and tokenizer_profile remain unexplained, and the concept of a 'context capsule' is not elaborated.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action (Compress) and the resource (UTF-8 text/markdown file) and uses the specific term 'context capsule' which distinguishes it from sibling tools like compress_text that likely operate on text directly.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is provided on when to use this tool versus its siblings (benchmark_file, compress_text) or when not to use it. The description is too brief to help an agent decide between alternatives.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
compress_textB
Compress raw text into a Context Diamond capsule.
| Name | Required | Description | Default |
|---|---|---|---|
| budget | No | Target section token budget. | |
| title | No | Capsule title. | OpenCode Context Capsule |
| format | No | markdown | |
| loss_report | No | Include kept/omitted shard audit data in JSON metadata. | |
| tokenizer_profile | No | generic | |
| text | Yes | Raw text, chat transcript, logs, or notes to compress. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description should disclose behavioral traits. It only states 'compress raw text into a Context Diamond capsule' without explaining what compression entails (lossy/lossless), side effects, or what a 'Context Diamond capsule' is.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence, concise and to the point. However, it could be slightly more informative without losing conciseness.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given 6 parameters, no output schema, and no annotations, the description is insufficient. It does not explain what a 'Context Diamond capsule' is, how compression works, or what the tool returns.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 67%, so baseline is 3. The description does not add significant meaning beyond the schema; it uses the term 'Context Diamond capsule' but does not elaborate on parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Description uses specific verb 'compress' and resource 'raw text' into a 'Context Diamond capsule', clearly distinguishing it from sibling tools like compress_file.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance on when to use or avoid this tool, nor any mention of alternatives. The description implies it's for text compression but lacks contextual usage advice.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.
3 tool updates
v0.1.0- First observed
benchmark_file - First observed
compress_file - First observed
compress_text
TDQS
benchmark_file is clearly distinct from the two compression tools. compress_file and compress_text overlap in purpose (both compress into a capsule) but are differentiated by input type (file vs raw text), reducing ambiguity.
All tools follow a consistent verb_noun pattern with underscores, all lowercase. No mixing of conventions.
With only 3 tools, the server is tightly scoped to its purpose of compressing and benchmarking, which is appropriate for a specialized server.
The tools cover the core functions of compression and benchmarking, but the absence of decompression or extraction tools may be a minor gap depending on use cases.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Stop re-explaining yourself to Agents. Give it the right context, right when needed.
Shared, permission-aware company context for AI agents, with provenance, approvals and audit.
Verified memory for AI agents. Signed assertions, billing attestation, session continuity.
Durable agent-to-agent handoffs and shared scratchpad for multi-agent workflows.
Related MCP Servers
- AlicenseBqualityCmaintenanceProvides a shared context layer for AI agent teams to improve token efficiency through context deduplication and incremental state sharing. It enables multiple agents to coordinate tasks, share real-time discoveries, and manage dependencies while significantly reducing redundant data transmission.1507MIT
- AlicenseAqualityCmaintenanceAuto-captures decision context from multi-agent workflows to preserve the 'why' behind every choice. Enables task traceability, reasoning retrieval, and continuous improvement across planning and implementation sessions.17236MIT
- AlicenseCqualityCmaintenanceCaptures key development moments, enables multi-agent traceability, provides intelligent context curation, and facilitates seamless agent-to-agent handoffs.2917MIT
- AlicenseAqualityCmaintenanceEnables LLM agents to acquire token-budgeted, deterministic context packs from repositories, with hash-chained provenance for auditability.2MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
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/RainCherb/context-diamond'
If you have feedback or need assistance with the MCP directory API, please join our Discord server