Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/pith/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11
7 changes: 7 additions & 0 deletions src/pith/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2024 Albert (VjAlbert)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
158 changes: 158 additions & 0 deletions src/pith/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# PITH v2 MCP Server

An MCP server that compresses inter-agent payloads to eliminate token waste in multi-agent pipelines. Uses **Shannon local information scoring** (I(w) = log2(total) − log2(count(w))) validated by Benford's Law structural integrity check; log2 lookups are O(1) via `@functools.lru_cache(maxsize=8192)`. SIZE_GATE = 10 000 chars ensures Benford statistical stability (≥100 sentences) and positive compute ROI. Zero external dependencies beyond the MCP SDK.

> **Core logic and full documentation:** [github.com/VjAlbert/pith-skill](https://github.com/VjAlbert/pith-skill)

---

## Overview

In multi-agent AI pipelines, agents pass verbose outputs — tool results, reasoning traces, search summaries — to downstream agents without compression. PITH fills this gap: it compresses those inter-agent payloads aggressively while preserving all structured content (code, JSON, URLs, file paths, numbers).

```
AGENT A — verbose output (487 tokens)
[PITH MCP Server]
AGENT B — compressed payload (284 tokens, -42%)
[PITH | ✓ | -42% tokens | benford:4.3% | compressed]
```

This module is the packaged MCP implementation, part of the [Anthropic MCP reference server monorepo](https://github.com/modelcontextprotocol/servers). It is published to PyPI as `mcp-server-pith` and registered with the Claude Desktop and Claude Code MCP clients.

---

## MCP Tools

### `compress`

Compress a verbose payload. Returns compressed text with a metadata header.

**Input:**
- `payload` (string, required): Text to compress
- `ratio` (number, optional, default: `0.6`): Fraction of sentences to keep (0.1–1.0)

**Output:**
```
[PITH | ✓ | -42% tokens | benford:4.3% | compressed]
<compressed text here>
```

Header fields: `✓`/`⚠` = Benford gate passed/warned, `-%` = token reduction, `benford:X%` = MAD from ideal distribution, `compressed`/`passthrough` = action taken.

### `compress_with_metadata`

Same compression, returns a JSON object with full metadata for programmatic pipelines.

**Output:**
```json
{
"compressed": "...",
"meta": {
"action": "compressed",
"original_tokens": 487,
"compressed_tokens": 284,
"ratio": 0.583,
"saved_pct": 41.7,
"sentences_original": 22,
"sentences_kept": 13,
"original_benford_mad": 4.1,
"compressed_benford_mad": 4.3,
"benford_ok": true,
"preserved_blocks": 0
}
}
```

---

## Compression Ratios

| Ratio | Mode | Best For |
|-------|------|----------|
| `0.8` | Conservative | Sensitive reasoning traces |
| `0.6` | Default | Most agent tool results |
| `0.4` | Aggressive | Bulk search results, summaries |
| `0.3` | Maximum | Context window critical |

---

## What is Always Preserved

Code blocks, inline code, JSON objects/arrays, URLs, file paths, XML/HTML tags. Extracted before compression, reinserted after — never touched by the scorer.

---

## Installation

### Claude Desktop

```json
{
"mcpServers": {
"pith": {
"command": "uvx",
"args": ["mcp-server-pith"]
}
}
}
```

On Windows:
```json
{
"mcpServers": {
"pith": {
"command": "cmd",
"args": ["/c", "uvx", "mcp-server-pith"]
}
}
}
```

### Direct

```bash
uvx mcp-server-pith # recommended — no install
pip install mcp-server-pith
python -m mcp_server_pith
```

---

## How it Works

1. **Size Gate** — payloads < 10 000 chars pass through unchanged (guarantees Benford stability ≥ 100 sentences)
2. **Extract** — code blocks, JSON, URLs, file paths quarantined before processing
3. **Filler Pre-pass** — boilerplate sentences (`"I believe…"`, `"Let me…"`, `"No errors…"`) removed before scoring
4. **Shannon Score** — each token scored via local information: `I(w) = log2(total) − log2(count(w))`; `@functools.lru_cache(maxsize=8192)` on `_log2` makes repeated lookups O(1)
5. **Prune** — tokens below adaptive threshold removed; logical connectors (`not`, `never`, `if`, `or`, …) always kept; polarity micro-checksum rolls back sentences where negation count changes
6. **Benford Gate** — if compressed MAD vs Benford's Law exceeds 2 × original MAD, halve reduction ratio and retry (max 3 attempts)
7. **Reassemble** — sentence order preserved, quarantined blocks reinserted, output wrapped in `<pith_optimization_layer>` XML

Full algorithm documentation, theory (Nash equilibrium, Zipf's Law, Benford's Law), comparison matrix, and benchmarks are in the [standalone repository](https://github.com/VjAlbert/pith-skill).

---

## Windows Encoding

At startup, both `sys.stdout` and `sys.stdin` are reconfigured to UTF-8 with `hasattr`-guarded calls, preventing `UnicodeEncodeError` on Windows CP1252 terminals. The guards ensure the calls are no-ops on non-standard streams (e.g., `StringIO` in test suites).

---

## Development

```bash
cd src/pith
uv sync --locked --all-extras --dev
uv run pytest # run eval suite
uv run --frozen pyright # type check
uv build # package
```

---

## License

MIT
36 changes: 36 additions & 0 deletions src/pith/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[project]
name = "mcp-server-pith"
version = "0.1.0"
description = "A Model Context Protocol server providing token-aware context compression for inter-agent payloads, optimized for Windows environments"
readme = "README.md"
requires-python = ">=3.10"
authors = [{ name = "Albert", email = "dotthofmann@gmail.com" }]
keywords = ["compression", "mcp", "llm", "agents", "tokens", "context"]
license = { text = "MIT" }
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
]
dependencies = [
"mcp>=1.1.3",
]

[project.scripts]
mcp-server-pith = "mcp_server_pith:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.uv]
dev-dependencies = ["pyright>=1.1.389", "ruff>=0.7.3", "pytest>=8.0.0"]

[tool.pytest.ini_options]
testpaths = ["tests"]

[tool.hatch.build.targets.wheel]
packages = ["src/mcp_server_pith"]
3 changes: 3 additions & 0 deletions src/pith/src/mcp_server_pith/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .server import main, serve

__all__ = ["main", "serve"]
3 changes: 3 additions & 0 deletions src/pith/src/mcp_server_pith/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from mcp_server_pith import main

main()
Loading
Loading