shrinkwrap-cli 0.1.4__tar.gz → 0.1.6__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shrinkwrap_cli-0.1.6/AGENT_PROMPT.md +10 -0
- shrinkwrap_cli-0.1.6/CHANGELOG.md +23 -0
- shrinkwrap_cli-0.1.6/CONTRIBUTING.md +26 -0
- shrinkwrap_cli-0.1.6/MANIFEST.in +2 -0
- shrinkwrap_cli-0.1.6/PKG-INFO +118 -0
- shrinkwrap_cli-0.1.6/README.md +101 -0
- shrinkwrap_cli-0.1.6/docs/architecture.md +48 -0
- shrinkwrap_cli-0.1.6/pyproject.toml +28 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/__init__.py +9 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap/benchmarks/corpus.py +13 -2
- shrinkwrap_cli-0.1.6/shrinkwrap/benchmarks/runner.py +67 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/benchmarks/stdio.py +167 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap/cli.py +63 -10
- shrinkwrap_cli-0.1.6/shrinkwrap/engine/compactor.py +176 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/engine/privacy.py +88 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/engine/retrieval.py +67 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/engine/retrieval_buffer.py +102 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/tracker.py +100 -39
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap/gap_report/gap_report.py +10 -10
- shrinkwrap_cli-0.1.6/shrinkwrap/proxy/config_manager.py +108 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/proxy/http_proxy.py +14 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/proxy/stdio_proxy.py +237 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/proxy/transform.py +49 -0
- shrinkwrap_cli-0.1.6/shrinkwrap/state.py +9 -0
- shrinkwrap_cli-0.1.6/shrinkwrap_cli.egg-info/PKG-INFO +118 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/SOURCES.txt +15 -1
- shrinkwrap_cli-0.1.6/shrinkwrap_cli.egg-info/requires.txt +4 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/tests/test_engine.py +8 -6
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/tests/test_proxy.py +5 -2
- shrinkwrap_cli-0.1.6/tests/test_regressions.py +192 -0
- shrinkwrap_cli-0.1.6/tests/test_retrieval.py +162 -0
- shrinkwrap_cli-0.1.6/tests/test_stdio_workflows.py +119 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/tests/test_suite.py +1 -1
- shrinkwrap_cli-0.1.6/tests/test_tracker_concurrency.py +32 -0
- shrinkwrap_cli-0.1.4/PKG-INFO +0 -206
- shrinkwrap_cli-0.1.4/README.md +0 -195
- shrinkwrap_cli-0.1.4/pyproject.toml +0 -20
- shrinkwrap_cli-0.1.4/shrinkwrap/__init__.py +0 -10
- shrinkwrap_cli-0.1.4/shrinkwrap/benchmarks/runner.py +0 -63
- shrinkwrap_cli-0.1.4/shrinkwrap/engine/compactor.py +0 -117
- shrinkwrap_cli-0.1.4/shrinkwrap/engine/privacy.py +0 -24
- shrinkwrap_cli-0.1.4/shrinkwrap/engine/retrieval_buffer.py +0 -67
- shrinkwrap_cli-0.1.4/shrinkwrap/proxy/config_manager.py +0 -79
- shrinkwrap_cli-0.1.4/shrinkwrap/proxy/http_proxy.py +0 -21
- shrinkwrap_cli-0.1.4/shrinkwrap/proxy/stdio_proxy.py +0 -71
- shrinkwrap_cli-0.1.4/shrinkwrap_cli.egg-info/PKG-INFO +0 -206
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/LICENSE +0 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/setup.cfg +0 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/tokenizer.py +0 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap/shell/guidance.py +0 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/dependency_links.txt +0 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/entry_points.txt +0 -0
- {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Setup prompt for an AI coding assistant
|
|
2
|
+
|
|
3
|
+
```text
|
|
4
|
+
Please set up ShrinkWrap for my local stdio MCP servers:
|
|
5
|
+
|
|
6
|
+
1. Install the `shrinkwrap-cli` package in an appropriate Python environment.
|
|
7
|
+
2. Run `shrinkwrap install --dry-run` and show which local MCP configurations and servers it would change. Codex uses `~/.codex/config.toml`.
|
|
8
|
+
3. Run `shrinkwrap install`, then verify the wrapped servers still start, their original tools work, and `shrinkwrap_fetch` appears in their tool list. ShrinkWrap saves a `.swbak` copy of each modified config.
|
|
9
|
+
4. Run `shrinkwrap benchmark` for the synthetic corpus and `shrinkwrap session` for estimated savings from real proxy calls. Do not treat the synthetic benchmark as measured savings for my workload.
|
|
10
|
+
```
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.6 (2026-11-26)
|
|
4
|
+
|
|
5
|
+
- Batch per-block analytics writes and attribute stdio results to the requested tool.
|
|
6
|
+
- Support configurable stdio message sizes, correlate tool replies by request ID, and check paginated tool discovery before advertising retrieval.
|
|
7
|
+
- Find a buffered array row by field value, including when its index is unknown.
|
|
8
|
+
- Measure latency, bytes, tokens, follow-up fetches and peak proxy memory with `benchmark --stdio`.
|
|
9
|
+
- Discover active Codex profiles via `CODEX_HOME` and list eligible servers during dry run.
|
|
10
|
+
|
|
11
|
+
## 0.1.5 (2026-11-18)
|
|
12
|
+
|
|
13
|
+
- Bound JSON and text previews and avoid summaries that expand the estimated output.
|
|
14
|
+
- Preserve unchanged stdio responses on the wire and compress large, repetitive buffer entries.
|
|
15
|
+
- Keep analytics counters accurate across concurrent proxy processes with locked, atomic updates.
|
|
16
|
+
- Add selective, paged retrieval through the CLI and a `shrinkwrap_fetch` MCP tool.
|
|
17
|
+
- Redact pass-through output and buffered samples, tighten buffer permissions, and validate reference handles.
|
|
18
|
+
- Support Codex TOML configuration and selective server wrapping, improve installer isolation, and add Python 3.9/3.12 tests.
|
|
19
|
+
- Run tests and verify the package version before PyPI publication; publish once per GitHub release.
|
|
20
|
+
|
|
21
|
+
## 0.1.4
|
|
22
|
+
|
|
23
|
+
Previous published release.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
## Local setup
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
python3 -m venv .venv
|
|
7
|
+
.venv/bin/python -m pip install -e . pytest build
|
|
8
|
+
.venv/bin/python -m pytest -q
|
|
9
|
+
.venv/bin/python -m shrinkwrap.cli benchmark
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The test workflow runs the suite on Python 3.9 and 3.12. Run the tests and `git diff --check` before opening a pull request. Add an end-to-end stdio test when changing request routing or tool discovery; use a temporary buffer for tests that store payloads.
|
|
13
|
+
|
|
14
|
+
Benchmark inputs are synthetic. Keep real credentials, customer data, and private tool output out of tests and issue reports. A change to compaction should check both token reduction and exact retrieval of the redacted original. A change to buffer storage should check readability of existing entries and expiry behavior.
|
|
15
|
+
|
|
16
|
+
## Documentation
|
|
17
|
+
|
|
18
|
+
Update the [README](README.md) when a command or user-facing behavior changes. The [architecture guide](docs/architecture.md) covers message routing, compaction, and the buffer format. State benchmark numbers as estimates from the synthetic corpus; do not present them as measured model billing or a guarantee for other tools.
|
|
19
|
+
|
|
20
|
+
## Releases
|
|
21
|
+
|
|
22
|
+
1. Update the version in `pyproject.toml` and `shrinkwrap/__init__.py`, and add release notes to `CHANGELOG.md`.
|
|
23
|
+
2. Let the pull request test workflow pass, then merge the reviewed changes.
|
|
24
|
+
3. Create a GitHub release with the tag `v<version>`. The publication workflow runs on the published release, checks that the tag matches the package version, runs tests, builds the distributions, and uploads them to PyPI through trusted publishing.
|
|
25
|
+
|
|
26
|
+
Publishing a tag alone does not upload the package. PyPI does not accept a second upload of an existing distribution filename.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: shrinkwrap-cli
|
|
3
|
+
Version: 0.1.6
|
|
4
|
+
Summary: Local stdio MCP tool-result compaction with retrievable references
|
|
5
|
+
Author: ShrinkWrap Maintainers
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/lucronn/shrinkwrap
|
|
8
|
+
Project-URL: Issues, https://github.com/lucronn/shrinkwrap/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/lucronn/shrinkwrap/blob/main/CHANGELOG.md
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: tomlkit<1,>=0.13
|
|
14
|
+
Provides-Extra: benchmark
|
|
15
|
+
Requires-Dist: tiktoken>=0.7; extra == "benchmark"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# ShrinkWrap
|
|
19
|
+
|
|
20
|
+
ShrinkWrap is a local compaction proxy for text returned by MCP tools. It replaces large text blocks with a bounded summary and a `sw-ref:` handle. The full, redacted payload is kept in a local buffer for later retrieval.
|
|
21
|
+
|
|
22
|
+
The command line provides a working **stdio MCP proxy**. The Python package also exposes an HTTP response transformer; it does not start an HTTP listener or intercept arbitrary shell commands.
|
|
23
|
+
|
|
24
|
+
## Install and configure
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
python3 -m venv ~/.local/share/shrinkwrap/venv
|
|
28
|
+
~/.local/share/shrinkwrap/venv/bin/python -m pip install shrinkwrap-cli
|
|
29
|
+
export PATH="$HOME/.local/share/shrinkwrap/venv/bin:$PATH"
|
|
30
|
+
shrinkwrap install --dry-run
|
|
31
|
+
shrinkwrap install
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The virtual environment works with a system Python that restricts direct package installs. Put its `bin` directory on PATH in future shells to use the `shrinkwrap` command there.
|
|
35
|
+
|
|
36
|
+
`install` wraps local stdio server commands in supported MCP client configuration files. It checks `$CODEX_HOME/config.toml` and `config.json` for the active Codex profile (default `~/.codex`). Dry run lists the eligible server names and configuration path. It also supports JSON configurations for Claude Desktop, Cursor, Gemini, and Antigravity. Remote URL servers are left alone. For each modified file, ShrinkWrap saves a `.swbak` copy. You can restore it with:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
shrinkwrap rollback ~/.codex/config.toml
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
For a single server, use `shrinkwrap wrap <config-file> --server <name> [--dry-run]`. Without `--server`, `wrap` handles all local servers in the file. Auto-wrapping uses the Python executable running ShrinkWrap, so a desktop client does not need `shrinkwrap` on its own PATH. [Codex's MCP documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli) describes the `config.toml` server format.
|
|
43
|
+
|
|
44
|
+
You can also run the proxy directly:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
shrinkwrap wrap-stdio -- npx -y @modelcontextprotocol/server-filesystem /path/to/files
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Stdio accepts messages up to 16 MiB before the newline in either direction. Set `SHRINKWRAP_MAX_FRAME_BYTES` to a positive byte count before starting the proxy if your server needs larger messages. Exceeding the configured limit ends the proxy with an error.
|
|
51
|
+
|
|
52
|
+
## What gets compacted
|
|
53
|
+
|
|
54
|
+
ShrinkWrap examines MCP tool result **text** blocks. JSON arrays and objects get a count, a bounded sample, and a reference handle. Long text gets bounded head and tail excerpts; tracebacks get selected error lines. Small output passes through after redaction. A candidate summary is used only when its estimated token count is smaller than the redacted output.
|
|
55
|
+
|
|
56
|
+
Tool results may also contain `structuredContent`. ShrinkWrap redacts strings in that field but does not compact it, since clients may validate it against a tool's output schema. Redaction can change values in a way that strict schema validators reject. Images, audio, and other non-text content blocks pass through. These cases can limit total response savings. See the [MCP tool result documentation](https://ts.sdk.modelcontextprotocol.io/v2/clients/calling) for the distinction between `content` and `structuredContent`.
|
|
57
|
+
|
|
58
|
+
## Retrieve a payload
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
shrinkwrap fetch sw-ref:0123456789ab
|
|
62
|
+
shrinkwrap fetch sw-ref:0123456789ab --pointer /rows/10
|
|
63
|
+
shrinkwrap fetch sw-ref:0123456789ab --pointer /files --match path src/main.py
|
|
64
|
+
shrinkwrap fetch sw-ref:0123456789ab --pointer /rows --offset 0 --limit 4000
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The handle retrieves the **redacted** payload. `--pointer` selects a JSON value using [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901); `--offset` and `--limit` return a bounded character chunk with `next_offset` for paging. Chunks of an object or array are fragments of its serialized JSON and can be joined before parsing.
|
|
68
|
+
|
|
69
|
+
The stdio proxy also advertises a `shrinkwrap_fetch` MCP tool on the final discovery page after checking the preceding pages for a name collision. An agent can call it with `ref_handle` and optional `pointer`, `match`, `offset`, and `limit` arguments. It returns up to 4,000 characters by default, with a 16,000-character maximum per call. For an array at the selected pointer, `"match":{"field":"path","value":"src/main.py"}` returns the unique matching row. Zero or multiple matches produce an error. Follow `next_offset` with the same selection to read more. The HTTP transformer does not advertise this tool. The [MCP tools specification](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) defines the discovery and call messages used here.
|
|
70
|
+
|
|
71
|
+
Files live in `~/.shrinkwrap/buffer/` by default. Set `SHRINKWRAP_STATE_DIR` before launching the proxy and CLI to put the buffer and analytics in another directory. Large entries that compress well are stored as gzip JSON; existing plain JSON entries remain readable. Entries expire after one hour by default and are removed during periodic cleanup or when an expired handle is fetched. Set `SHRINKWRAP_TTL_SECONDS` to a positive number to change the TTL. Buffer directories and new files are owner-only.
|
|
72
|
+
|
|
73
|
+
Redaction handles common token formats, private key blocks, bearer values, and named credential fields. It is best effort. Check outputs before using ShrinkWrap with unusually sensitive data. ShrinkWrap itself sends no payloads or analytics to a remote service.
|
|
74
|
+
|
|
75
|
+
## Measure your workload
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
shrinkwrap benchmark
|
|
79
|
+
shrinkwrap benchmark --stdio
|
|
80
|
+
shrinkwrap gain
|
|
81
|
+
shrinkwrap session --markdown
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`benchmark` runs seven **synthetic** payloads, including single-line and large-field cases that previously expanded. The current corpus shows roughly 98.9% reduction by a character and word heuristic, not a model tokenizer. The corpus and local execution time do not predict savings or latency for your tools. Benchmark runs use a temporary buffer and do not add events to your analytics.
|
|
85
|
+
|
|
86
|
+
`benchmark --stdio` runs a local fixture server directly and through the proxy using temporary state. It measures warmed median and p95 round-trip latency, response bytes, returned text tokens, and peak proxy RSS where Linux exposes it. The file lookup and full recovery cases verify the returned data and include every fetch. Their wire-byte totals include the original call and all follow-ups. Text-token totals count the original reply and all returned text blocks. Fetch arguments are reported separately. A full recovery can cost more tokens than the original response.
|
|
87
|
+
|
|
88
|
+
Counts use the heuristic by default. To measure with a tokenizer, install `'shrinkwrap-cli[benchmark]'` and run `shrinkwrap benchmark --stdio --encoding o200k_base --json`. The tokenizer may download its vocabulary on first use.
|
|
89
|
+
|
|
90
|
+
`gain` and `session` report estimated tokens saved on initial tool output before retrieval. Financial figures use a fixed `$3.00 / 1M tokens` assumption and are estimates, not billing data.
|
|
91
|
+
|
|
92
|
+
## Commands
|
|
93
|
+
|
|
94
|
+
| Command | Purpose |
|
|
95
|
+
| --- | --- |
|
|
96
|
+
| `shrinkwrap install [--dry-run]` | Discover and wrap supported local MCP configs |
|
|
97
|
+
| `shrinkwrap wrap <file> [--server name] [--dry-run]` | Wrap a config file or one named server |
|
|
98
|
+
| `shrinkwrap rollback <file>` | Restore its `.swbak` backup |
|
|
99
|
+
| `shrinkwrap wrap-stdio -- <command> [args]` | Proxy a stdio MCP server |
|
|
100
|
+
| `shrinkwrap fetch <sw-ref:handle>` | Retrieve a buffered redacted payload |
|
|
101
|
+
| `shrinkwrap benchmark [--stdio] [--json]` | Measure engine compaction or complete stdio workflows |
|
|
102
|
+
| `shrinkwrap gain [--history] [--json]` | Show cumulative estimated savings |
|
|
103
|
+
| `shrinkwrap session [--markdown] [--json]` | Show session estimated savings |
|
|
104
|
+
| `shrinkwrap status` | Show installed version and available components |
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
See [Contributing](https://github.com/lucronn/shrinkwrap/blob/main/CONTRIBUTING.md) for tests and releases, the [architecture guide](https://github.com/lucronn/shrinkwrap/blob/main/docs/architecture.md) for message and buffer behavior, and the [changelog](https://github.com/lucronn/shrinkwrap/blob/main/CHANGELOG.md) for release notes.
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
python3 -m venv .venv
|
|
112
|
+
.venv/bin/python -m pip install -e . pytest
|
|
113
|
+
.venv/bin/python -m pytest -q
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## License
|
|
117
|
+
|
|
118
|
+
MIT. See [LICENSE](https://github.com/lucronn/shrinkwrap/blob/main/LICENSE).
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# ShrinkWrap
|
|
2
|
+
|
|
3
|
+
ShrinkWrap is a local compaction proxy for text returned by MCP tools. It replaces large text blocks with a bounded summary and a `sw-ref:` handle. The full, redacted payload is kept in a local buffer for later retrieval.
|
|
4
|
+
|
|
5
|
+
The command line provides a working **stdio MCP proxy**. The Python package also exposes an HTTP response transformer; it does not start an HTTP listener or intercept arbitrary shell commands.
|
|
6
|
+
|
|
7
|
+
## Install and configure
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
python3 -m venv ~/.local/share/shrinkwrap/venv
|
|
11
|
+
~/.local/share/shrinkwrap/venv/bin/python -m pip install shrinkwrap-cli
|
|
12
|
+
export PATH="$HOME/.local/share/shrinkwrap/venv/bin:$PATH"
|
|
13
|
+
shrinkwrap install --dry-run
|
|
14
|
+
shrinkwrap install
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The virtual environment works with a system Python that restricts direct package installs. Put its `bin` directory on PATH in future shells to use the `shrinkwrap` command there.
|
|
18
|
+
|
|
19
|
+
`install` wraps local stdio server commands in supported MCP client configuration files. It checks `$CODEX_HOME/config.toml` and `config.json` for the active Codex profile (default `~/.codex`). Dry run lists the eligible server names and configuration path. It also supports JSON configurations for Claude Desktop, Cursor, Gemini, and Antigravity. Remote URL servers are left alone. For each modified file, ShrinkWrap saves a `.swbak` copy. You can restore it with:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
shrinkwrap rollback ~/.codex/config.toml
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
For a single server, use `shrinkwrap wrap <config-file> --server <name> [--dry-run]`. Without `--server`, `wrap` handles all local servers in the file. Auto-wrapping uses the Python executable running ShrinkWrap, so a desktop client does not need `shrinkwrap` on its own PATH. [Codex's MCP documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli) describes the `config.toml` server format.
|
|
26
|
+
|
|
27
|
+
You can also run the proxy directly:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
shrinkwrap wrap-stdio -- npx -y @modelcontextprotocol/server-filesystem /path/to/files
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Stdio accepts messages up to 16 MiB before the newline in either direction. Set `SHRINKWRAP_MAX_FRAME_BYTES` to a positive byte count before starting the proxy if your server needs larger messages. Exceeding the configured limit ends the proxy with an error.
|
|
34
|
+
|
|
35
|
+
## What gets compacted
|
|
36
|
+
|
|
37
|
+
ShrinkWrap examines MCP tool result **text** blocks. JSON arrays and objects get a count, a bounded sample, and a reference handle. Long text gets bounded head and tail excerpts; tracebacks get selected error lines. Small output passes through after redaction. A candidate summary is used only when its estimated token count is smaller than the redacted output.
|
|
38
|
+
|
|
39
|
+
Tool results may also contain `structuredContent`. ShrinkWrap redacts strings in that field but does not compact it, since clients may validate it against a tool's output schema. Redaction can change values in a way that strict schema validators reject. Images, audio, and other non-text content blocks pass through. These cases can limit total response savings. See the [MCP tool result documentation](https://ts.sdk.modelcontextprotocol.io/v2/clients/calling) for the distinction between `content` and `structuredContent`.
|
|
40
|
+
|
|
41
|
+
## Retrieve a payload
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
shrinkwrap fetch sw-ref:0123456789ab
|
|
45
|
+
shrinkwrap fetch sw-ref:0123456789ab --pointer /rows/10
|
|
46
|
+
shrinkwrap fetch sw-ref:0123456789ab --pointer /files --match path src/main.py
|
|
47
|
+
shrinkwrap fetch sw-ref:0123456789ab --pointer /rows --offset 0 --limit 4000
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The handle retrieves the **redacted** payload. `--pointer` selects a JSON value using [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901); `--offset` and `--limit` return a bounded character chunk with `next_offset` for paging. Chunks of an object or array are fragments of its serialized JSON and can be joined before parsing.
|
|
51
|
+
|
|
52
|
+
The stdio proxy also advertises a `shrinkwrap_fetch` MCP tool on the final discovery page after checking the preceding pages for a name collision. An agent can call it with `ref_handle` and optional `pointer`, `match`, `offset`, and `limit` arguments. It returns up to 4,000 characters by default, with a 16,000-character maximum per call. For an array at the selected pointer, `"match":{"field":"path","value":"src/main.py"}` returns the unique matching row. Zero or multiple matches produce an error. Follow `next_offset` with the same selection to read more. The HTTP transformer does not advertise this tool. The [MCP tools specification](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) defines the discovery and call messages used here.
|
|
53
|
+
|
|
54
|
+
Files live in `~/.shrinkwrap/buffer/` by default. Set `SHRINKWRAP_STATE_DIR` before launching the proxy and CLI to put the buffer and analytics in another directory. Large entries that compress well are stored as gzip JSON; existing plain JSON entries remain readable. Entries expire after one hour by default and are removed during periodic cleanup or when an expired handle is fetched. Set `SHRINKWRAP_TTL_SECONDS` to a positive number to change the TTL. Buffer directories and new files are owner-only.
|
|
55
|
+
|
|
56
|
+
Redaction handles common token formats, private key blocks, bearer values, and named credential fields. It is best effort. Check outputs before using ShrinkWrap with unusually sensitive data. ShrinkWrap itself sends no payloads or analytics to a remote service.
|
|
57
|
+
|
|
58
|
+
## Measure your workload
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
shrinkwrap benchmark
|
|
62
|
+
shrinkwrap benchmark --stdio
|
|
63
|
+
shrinkwrap gain
|
|
64
|
+
shrinkwrap session --markdown
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`benchmark` runs seven **synthetic** payloads, including single-line and large-field cases that previously expanded. The current corpus shows roughly 98.9% reduction by a character and word heuristic, not a model tokenizer. The corpus and local execution time do not predict savings or latency for your tools. Benchmark runs use a temporary buffer and do not add events to your analytics.
|
|
68
|
+
|
|
69
|
+
`benchmark --stdio` runs a local fixture server directly and through the proxy using temporary state. It measures warmed median and p95 round-trip latency, response bytes, returned text tokens, and peak proxy RSS where Linux exposes it. The file lookup and full recovery cases verify the returned data and include every fetch. Their wire-byte totals include the original call and all follow-ups. Text-token totals count the original reply and all returned text blocks. Fetch arguments are reported separately. A full recovery can cost more tokens than the original response.
|
|
70
|
+
|
|
71
|
+
Counts use the heuristic by default. To measure with a tokenizer, install `'shrinkwrap-cli[benchmark]'` and run `shrinkwrap benchmark --stdio --encoding o200k_base --json`. The tokenizer may download its vocabulary on first use.
|
|
72
|
+
|
|
73
|
+
`gain` and `session` report estimated tokens saved on initial tool output before retrieval. Financial figures use a fixed `$3.00 / 1M tokens` assumption and are estimates, not billing data.
|
|
74
|
+
|
|
75
|
+
## Commands
|
|
76
|
+
|
|
77
|
+
| Command | Purpose |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `shrinkwrap install [--dry-run]` | Discover and wrap supported local MCP configs |
|
|
80
|
+
| `shrinkwrap wrap <file> [--server name] [--dry-run]` | Wrap a config file or one named server |
|
|
81
|
+
| `shrinkwrap rollback <file>` | Restore its `.swbak` backup |
|
|
82
|
+
| `shrinkwrap wrap-stdio -- <command> [args]` | Proxy a stdio MCP server |
|
|
83
|
+
| `shrinkwrap fetch <sw-ref:handle>` | Retrieve a buffered redacted payload |
|
|
84
|
+
| `shrinkwrap benchmark [--stdio] [--json]` | Measure engine compaction or complete stdio workflows |
|
|
85
|
+
| `shrinkwrap gain [--history] [--json]` | Show cumulative estimated savings |
|
|
86
|
+
| `shrinkwrap session [--markdown] [--json]` | Show session estimated savings |
|
|
87
|
+
| `shrinkwrap status` | Show installed version and available components |
|
|
88
|
+
|
|
89
|
+
## Development
|
|
90
|
+
|
|
91
|
+
See [Contributing](https://github.com/lucronn/shrinkwrap/blob/main/CONTRIBUTING.md) for tests and releases, the [architecture guide](https://github.com/lucronn/shrinkwrap/blob/main/docs/architecture.md) for message and buffer behavior, and the [changelog](https://github.com/lucronn/shrinkwrap/blob/main/CHANGELOG.md) for release notes.
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
python3 -m venv .venv
|
|
95
|
+
.venv/bin/python -m pip install -e . pytest
|
|
96
|
+
.venv/bin/python -m pytest -q
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## License
|
|
100
|
+
|
|
101
|
+
MIT. See [LICENSE](https://github.com/lucronn/shrinkwrap/blob/main/LICENSE).
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
ShrinkWrap runs between a local MCP client and a stdio MCP server. The proxy forwards client requests to the server and inspects server responses before the client receives them.
|
|
4
|
+
|
|
5
|
+
```mermaid
|
|
6
|
+
flowchart LR
|
|
7
|
+
Client[MCP client] --> Proxy[ShrinkWrap stdio proxy]
|
|
8
|
+
Proxy --> Server[Wrapped MCP server]
|
|
9
|
+
Server --> Proxy
|
|
10
|
+
Proxy --> Client
|
|
11
|
+
Proxy <--> Buffer[Local TTL buffer]
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Stdio message flow
|
|
15
|
+
|
|
16
|
+
- The proxy forwards messages it does not change as their original bytes. This includes initialization, notifications, and small tool results.
|
|
17
|
+
- On the final page of a discovery sequence that began with a cursorless `tools/list` request, it appends a `shrinkwrap_fetch` definition if the wrapped server has no tool with that name. Calls to this added tool are answered by the proxy from its buffer. Other calls go to the wrapped server.
|
|
18
|
+
- The proxy correlates requests with replies by ID. For a `tools/call` result, it examines text blocks in `result.content`. JSON text containing an object or array is parsed for a structural summary; other text is treated as text. Non-text blocks pass through.
|
|
19
|
+
- `result.structuredContent` is redacted but not compacted. Some clients validate it against an output schema, so redaction can make a strict schema check fail. A large structured result can therefore limit overall token savings.
|
|
20
|
+
|
|
21
|
+
The HTTP module is a Python response transformer. It does not provide an HTTP listener, request forwarding, tool discovery, or the `shrinkwrap_fetch` tool.
|
|
22
|
+
|
|
23
|
+
## Compaction decision
|
|
24
|
+
|
|
25
|
+
The engine converts input to text, redacts recognized secrets, estimates tokens, and compares that estimate with a threshold. For larger input it creates a bounded candidate summary: counts and short samples for JSON, or short excerpts for text and errors. It writes the redacted payload to the buffer only if the candidate is estimated to be smaller. If storage fails, it returns the redacted input instead of an unusable reference.
|
|
26
|
+
|
|
27
|
+
Token counts use a character and word heuristic. They are useful for a local decision and analytics, but they are not model tokenizer counts or billing data.
|
|
28
|
+
|
|
29
|
+
Each proxy process records analytics in `stats.json`. All text block events for a reply share one transaction, preserving block counts and reported tool names. Updates take a cross-process file lock and replace the JSON file atomically, so concurrent wrapped servers do not overwrite each other's counters. The recent-event history keeps at most 100 entries.
|
|
30
|
+
|
|
31
|
+
## Retrieval
|
|
32
|
+
|
|
33
|
+
Both `shrinkwrap fetch` and the stdio `shrinkwrap_fetch` tool read the same buffer. A reference identifies the full redacted payload for one hour by default. An optional [JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901) selects a nested value. An optional exact string field match selects a unique row from an array at that pointer. `offset` and `limit` split its text representation into character chunks. For an object or array, concatenate chunks before parsing the JSON. The MCP tool defaults to 4,000 characters and allows at most 16,000 per call.
|
|
34
|
+
|
|
35
|
+
The buffer stores smaller entries as JSON. For entries of at least 64 KiB, it uses gzip JSON when that saves at least 10% of the bytes. Existing plain JSON entries remain readable. File modification times determine expiry; periodic cleanup removes old entries. The buffer directory and newly written files are owner-only. `SHRINKWRAP_STATE_DIR` can relocate both the buffer and analytics files when set before process startup.
|
|
36
|
+
|
|
37
|
+
Handles are 12 hexadecimal characters from a SHA-256 digest. They identify cached content; they are not authentication tokens. Redaction is best effort, so use care with unusually sensitive payloads.
|
|
38
|
+
|
|
39
|
+
## Supported scope
|
|
40
|
+
|
|
41
|
+
| Surface | Behavior |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| Local stdio MCP server | Request forwarding, text compaction, and `shrinkwrap_fetch` retrieval |
|
|
44
|
+
| HTTP response transformer API | Text compaction and structured result redaction when embedded by a separate HTTP transport |
|
|
45
|
+
| Shell command output | No automatic interception |
|
|
46
|
+
| Hosted tools and connected apps | No automatic interception |
|
|
47
|
+
|
|
48
|
+
See the [MCP tools specification](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) for the `tools/list`, `tools/call`, and result formats used by the proxy.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "shrinkwrap-cli"
|
|
7
|
+
version = "0.1.6"
|
|
8
|
+
description = "Local stdio MCP tool-result compaction with retrievable references"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
authors = [{ name = "ShrinkWrap Maintainers" }]
|
|
11
|
+
license = "MIT"
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
dependencies = ["tomlkit>=0.13,<1"]
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
benchmark = ["tiktoken>=0.7"]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Repository = "https://github.com/lucronn/shrinkwrap"
|
|
20
|
+
Issues = "https://github.com/lucronn/shrinkwrap/issues"
|
|
21
|
+
Changelog = "https://github.com/lucronn/shrinkwrap/blob/main/CHANGELOG.md"
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
shrinkwrap = "shrinkwrap.cli:main"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
where = ["."]
|
|
28
|
+
include = ["shrinkwrap*"]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ShrinkWrap: local compaction of MCP tool result text with TTL-backed retrieval.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.6"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
__coverage_status__ = "stdio MCP proxy; HTTP response transformer library"
|
|
9
|
+
__universal_status__ = "unavailable (requires host-level integration)"
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""
|
|
2
|
-
|
|
3
|
-
Contains
|
|
2
|
+
Synthetic benchmark corpus for ShrinkWrap.
|
|
3
|
+
Contains representative API, SQL, chat, HTML, and traceback payloads plus
|
|
4
|
+
pathological long fields that previously expanded during compaction.
|
|
4
5
|
"""
|
|
5
6
|
|
|
6
7
|
def generate_benchmark_cases():
|
|
@@ -96,5 +97,15 @@ def generate_benchmark_cases():
|
|
|
96
97
|
f' File "/usr/local/lib/python3.11/site-packages/engine/service_{i}.py", line {i*14+3}, in execute_pipeline\n result = self._dispatch_handler(step_id={i}, context=ctx)'
|
|
97
98
|
for i in range(100)
|
|
98
99
|
) + "\nDatabaseConnectionError: Failed to establish TLS handshake with db-cluster.internal:5432 (Connection timed out after 30000ms)"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
"name": "single_line_output",
|
|
103
|
+
"source": "shell",
|
|
104
|
+
"input": "x" * 50000
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
"name": "large_first_field",
|
|
108
|
+
"source": "mcp",
|
|
109
|
+
"input": {"body": "x" * 50000, "id": 42}
|
|
99
110
|
}
|
|
100
111
|
]
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Benchmark Suite Runner for ShrinkWrap.
|
|
3
|
+
Calculates token and byte reduction metrics across test cases.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import time
|
|
7
|
+
import json
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Dict, Any
|
|
11
|
+
from shrinkwrap.engine.compactor import CompactionEngine
|
|
12
|
+
from shrinkwrap.engine.retrieval_buffer import RetrievalBuffer
|
|
13
|
+
from shrinkwrap.benchmarks.corpus import generate_benchmark_cases
|
|
14
|
+
|
|
15
|
+
def run_benchmark_suite() -> Dict[str, Any]:
|
|
16
|
+
cases = generate_benchmark_cases()
|
|
17
|
+
results = []
|
|
18
|
+
|
|
19
|
+
total_orig_tokens = 0
|
|
20
|
+
total_comp_tokens = 0
|
|
21
|
+
total_orig_bytes = 0
|
|
22
|
+
total_comp_bytes = 0
|
|
23
|
+
|
|
24
|
+
with tempfile.TemporaryDirectory(prefix="shrinkwrap-benchmark-") as buffer_dir:
|
|
25
|
+
compactor = CompactionEngine(token_threshold=100, record_stats=False,
|
|
26
|
+
buffer=RetrievalBuffer(Path(buffer_dir)))
|
|
27
|
+
t0 = time.perf_counter()
|
|
28
|
+
for c in cases:
|
|
29
|
+
inp = c["input"]
|
|
30
|
+
raw_str = json.dumps(inp, ensure_ascii=False, separators=(",", ":")) if isinstance(inp, (dict, list)) else str(inp)
|
|
31
|
+
orig_bytes = len(raw_str.encode("utf-8"))
|
|
32
|
+
|
|
33
|
+
compacted, strat, orig_tok, comp_tok = compactor.compact(inp, source_type=c["source"])
|
|
34
|
+
comp_str = json.dumps(compacted, ensure_ascii=False, separators=(",", ":")) if isinstance(compacted, (dict, list)) else str(compacted)
|
|
35
|
+
comp_bytes = len(comp_str.encode("utf-8"))
|
|
36
|
+
|
|
37
|
+
total_orig_tokens += orig_tok
|
|
38
|
+
total_comp_tokens += comp_tok
|
|
39
|
+
total_orig_bytes += orig_bytes
|
|
40
|
+
total_comp_bytes += comp_bytes
|
|
41
|
+
|
|
42
|
+
savings_pct = ((orig_tok - comp_tok) / orig_tok * 100) if orig_tok > 0 else 0.0
|
|
43
|
+
results.append({
|
|
44
|
+
"name": c["name"],
|
|
45
|
+
"source": c["source"],
|
|
46
|
+
"strategy": strat,
|
|
47
|
+
"orig_tokens": orig_tok,
|
|
48
|
+
"comp_tokens": comp_tok,
|
|
49
|
+
"savings_pct": round(savings_pct, 2)
|
|
50
|
+
})
|
|
51
|
+
t1 = time.perf_counter()
|
|
52
|
+
total_time_ms = (t1 - t0) * 1000
|
|
53
|
+
|
|
54
|
+
overall_tok_savings = ((total_orig_tokens - total_comp_tokens) / total_orig_tokens * 100) if total_orig_tokens > 0 else 0.0
|
|
55
|
+
overall_byte_savings = ((total_orig_bytes - total_comp_bytes) / total_orig_bytes * 100) if total_orig_bytes > 0 else 0.0
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
"summary": {
|
|
59
|
+
"total_cases": len(cases),
|
|
60
|
+
"total_orig_tokens": total_orig_tokens,
|
|
61
|
+
"total_comp_tokens": total_comp_tokens,
|
|
62
|
+
"overall_token_savings_pct": round(overall_tok_savings, 2),
|
|
63
|
+
"overall_byte_savings_pct": round(overall_byte_savings, 2),
|
|
64
|
+
"execution_time_ms": round(total_time_ms, 2)
|
|
65
|
+
},
|
|
66
|
+
"cases": results
|
|
67
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Measure a local MCP server directly and through the installed stdio proxy."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from contextlib import asynccontextmanager
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import statistics
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from shrinkwrap.benchmarks.corpus import generate_benchmark_cases
|
|
16
|
+
from shrinkwrap.engine.tokenizer import estimate_tokens
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def compact_json(value):
|
|
20
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def text_block(value):
|
|
24
|
+
return {"type": "text", "text": compact_json(value)}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def fixtures():
|
|
28
|
+
root = Path(__file__).resolve().parents[1]
|
|
29
|
+
rows = []
|
|
30
|
+
for path in sorted(root.rglob("*.py")):
|
|
31
|
+
contents = path.read_bytes()
|
|
32
|
+
rows.append({"path": path.relative_to(root).as_posix(), "size": len(contents),
|
|
33
|
+
"sha256": hashlib.sha256(contents).hexdigest(),
|
|
34
|
+
"first_line_lengths": [len(line) for line in contents.splitlines()[:100]]})
|
|
35
|
+
postgres = next(case["input"] for case in generate_benchmark_cases()
|
|
36
|
+
if case["name"] == "postgres_query_result")
|
|
37
|
+
return rows, {
|
|
38
|
+
"small": {"content": [{"type": "text", "text": "ok"}]},
|
|
39
|
+
"files": {"content": [text_block(rows)]},
|
|
40
|
+
"files_by_block": {"content": [text_block(row) for row in rows]},
|
|
41
|
+
"postgres": {"content": [text_block(postgres)]},
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def serve():
|
|
46
|
+
_, replies = fixtures()
|
|
47
|
+
for line in sys.stdin.buffer:
|
|
48
|
+
request = json.loads(line)
|
|
49
|
+
if request["method"] == "tools/list":
|
|
50
|
+
result = {"tools": [{"name": name, "inputSchema": {"type": "object"}} for name in replies]}
|
|
51
|
+
else:
|
|
52
|
+
result = replies[request["params"]["name"]]
|
|
53
|
+
print(compact_json({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def peak_rss_kib(pid):
|
|
57
|
+
"""Linux reports lifetime high water RSS in KiB on the process status page."""
|
|
58
|
+
try:
|
|
59
|
+
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
|
|
60
|
+
if line.startswith("VmHWM:"):
|
|
61
|
+
return int(line.split()[1])
|
|
62
|
+
except OSError:
|
|
63
|
+
pass
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@asynccontextmanager
|
|
68
|
+
async def session(wrapped, state):
|
|
69
|
+
target = [sys.executable, "-m", "shrinkwrap.benchmarks.stdio"]
|
|
70
|
+
if wrapped:
|
|
71
|
+
target = [sys.executable, "-m", "shrinkwrap.cli", "wrap-stdio", "--", *target]
|
|
72
|
+
proc = await asyncio.create_subprocess_exec(
|
|
73
|
+
*target, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
|
|
74
|
+
limit=16 * 1024 * 1024, env=dict(os.environ, SHRINKWRAP_STATE_DIR=state))
|
|
75
|
+
try:
|
|
76
|
+
yield proc
|
|
77
|
+
proc.stdin.close()
|
|
78
|
+
if await asyncio.wait_for(proc.wait(), timeout=10):
|
|
79
|
+
raise RuntimeError("benchmark subprocess failed")
|
|
80
|
+
finally:
|
|
81
|
+
if proc.returncode is None:
|
|
82
|
+
proc.kill()
|
|
83
|
+
await proc.communicate()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def exchange(proc, method, params):
|
|
87
|
+
# Sequential requests allow the same ID to be reused after each response.
|
|
88
|
+
wire = (compact_json({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) + "\n").encode()
|
|
89
|
+
start = time.perf_counter_ns()
|
|
90
|
+
proc.stdin.write(wire)
|
|
91
|
+
await proc.stdin.drain()
|
|
92
|
+
reply = await asyncio.wait_for(proc.stdout.readline(), timeout=15)
|
|
93
|
+
elapsed_ms = (time.perf_counter_ns() - start) / 1e6
|
|
94
|
+
if not reply:
|
|
95
|
+
raise RuntimeError("benchmark subprocess closed the connection")
|
|
96
|
+
result = json.loads(reply)["result"]
|
|
97
|
+
if result.get("isError"):
|
|
98
|
+
raise RuntimeError(result["content"][0]["text"])
|
|
99
|
+
return result, elapsed_ms, len(wire), len(reply)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def run_stdio_benchmark(encoding="estimate", samples=21):
|
|
103
|
+
count = estimate_tokens
|
|
104
|
+
if encoding != "estimate":
|
|
105
|
+
try:
|
|
106
|
+
import tiktoken
|
|
107
|
+
except ImportError as exc:
|
|
108
|
+
raise ValueError("Install shrinkwrap-cli[benchmark] for tokenizer counts") from exc
|
|
109
|
+
encoder = tiktoken.get_encoding(encoding)
|
|
110
|
+
count = lambda s: len(encoder.encode_ordinary(s))
|
|
111
|
+
|
|
112
|
+
rows, cases = fixtures()
|
|
113
|
+
target_path = "engine/compactor.py"
|
|
114
|
+
expected = next(row for row in rows if row["path"] == target_path)
|
|
115
|
+
report = {"encoding": encoding, "samples_per_case": samples, "cases": {}, "retrieval": {}}
|
|
116
|
+
with tempfile.TemporaryDirectory(prefix="shrinkwrap-stdio-") as state:
|
|
117
|
+
for mode in ("direct", "proxy"):
|
|
118
|
+
async with session(mode == "proxy", state) as proc:
|
|
119
|
+
listing, *_ = await exchange(proc, "tools/list", {})
|
|
120
|
+
if mode == "proxy" and "shrinkwrap_fetch" not in [t["name"] for t in listing["tools"]]:
|
|
121
|
+
raise RuntimeError("retrieval tool missing")
|
|
122
|
+
for name in cases:
|
|
123
|
+
params = {"name": name, "arguments": {}}
|
|
124
|
+
await exchange(proc, "tools/call", params) # warm up outside the samples
|
|
125
|
+
times = []
|
|
126
|
+
for _ in range(samples):
|
|
127
|
+
result, ms, sent, received = await exchange(proc, "tools/call", params)
|
|
128
|
+
times.append(ms)
|
|
129
|
+
tokens = sum(count(item["text"]) for item in result["content"])
|
|
130
|
+
summary = {"median_ms": round(statistics.median(times), 3),
|
|
131
|
+
"p95_ms": round(sorted(times)[math.ceil(.95 * samples) - 1], 3),
|
|
132
|
+
"response_bytes": received, "returned_text_tokens": tokens}
|
|
133
|
+
report["cases"].setdefault(name, {})[mode] = summary
|
|
134
|
+
if name != "files" or mode != "proxy":
|
|
135
|
+
continue
|
|
136
|
+
ref = json.loads(result["content"][0]["text"])["ref_handle"]
|
|
137
|
+
for task in ("find_file_size", "recover_all"):
|
|
138
|
+
args = {"ref_handle": ref}
|
|
139
|
+
if task == "find_file_size":
|
|
140
|
+
args["match"] = {"field": "path", "value": target_path}
|
|
141
|
+
chunks = []
|
|
142
|
+
total_tokens, arg_tokens, total_bytes = tokens, 0, sent + received
|
|
143
|
+
while True:
|
|
144
|
+
fetched, _, tx, rx = await exchange(proc, "tools/call", {
|
|
145
|
+
"name": "shrinkwrap_fetch", "arguments": args})
|
|
146
|
+
text = fetched["content"][0]["text"]
|
|
147
|
+
total_bytes += tx + rx
|
|
148
|
+
total_tokens += count(text)
|
|
149
|
+
arg_tokens += count(compact_json(args))
|
|
150
|
+
chunk = json.loads(text)
|
|
151
|
+
chunks.append(chunk["chunk"])
|
|
152
|
+
if chunk["next_offset"] is None:
|
|
153
|
+
break
|
|
154
|
+
args["offset"] = chunk["next_offset"]
|
|
155
|
+
actual = json.loads("".join(chunks))
|
|
156
|
+
if actual != (expected if task == "find_file_size" else rows):
|
|
157
|
+
raise RuntimeError(f"incorrect retrieval for {task}")
|
|
158
|
+
report["retrieval"][task] = {
|
|
159
|
+
"fetch_calls": len(chunks), "returned_text_tokens": total_tokens,
|
|
160
|
+
"fetch_argument_tokens": arg_tokens, "round_trip_bytes": total_bytes}
|
|
161
|
+
if mode == "proxy":
|
|
162
|
+
report["proxy_peak_rss_kib"] = peak_rss_kib(proc.pid)
|
|
163
|
+
return report
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
if __name__ == "__main__":
|
|
167
|
+
serve()
|