shrinkwrap-cli 0.1.4__tar.gz → 0.1.5__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.
Files changed (50) hide show
  1. shrinkwrap_cli-0.1.5/AGENT_PROMPT.md +10 -0
  2. shrinkwrap_cli-0.1.5/CHANGELOG.md +15 -0
  3. shrinkwrap_cli-0.1.5/CONTRIBUTING.md +26 -0
  4. shrinkwrap_cli-0.1.5/MANIFEST.in +2 -0
  5. shrinkwrap_cli-0.1.5/PKG-INFO +108 -0
  6. shrinkwrap_cli-0.1.5/README.md +93 -0
  7. shrinkwrap_cli-0.1.5/docs/architecture.md +48 -0
  8. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/pyproject.toml +8 -3
  9. shrinkwrap_cli-0.1.5/shrinkwrap/__init__.py +9 -0
  10. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap/benchmarks/corpus.py +13 -2
  11. shrinkwrap_cli-0.1.5/shrinkwrap/benchmarks/runner.py +67 -0
  12. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap/cli.py +30 -9
  13. shrinkwrap_cli-0.1.5/shrinkwrap/engine/compactor.py +162 -0
  14. shrinkwrap_cli-0.1.5/shrinkwrap/engine/privacy.py +88 -0
  15. shrinkwrap_cli-0.1.5/shrinkwrap/engine/retrieval.py +54 -0
  16. shrinkwrap_cli-0.1.5/shrinkwrap/engine/retrieval_buffer.py +102 -0
  17. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap/engine/tracker.py +78 -33
  18. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap/gap_report/gap_report.py +10 -10
  19. shrinkwrap_cli-0.1.5/shrinkwrap/proxy/config_manager.py +106 -0
  20. shrinkwrap_cli-0.1.5/shrinkwrap/proxy/http_proxy.py +14 -0
  21. shrinkwrap_cli-0.1.5/shrinkwrap/proxy/stdio_proxy.py +169 -0
  22. shrinkwrap_cli-0.1.5/shrinkwrap/proxy/transform.py +46 -0
  23. shrinkwrap_cli-0.1.5/shrinkwrap/state.py +9 -0
  24. shrinkwrap_cli-0.1.5/shrinkwrap_cli.egg-info/PKG-INFO +108 -0
  25. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap_cli.egg-info/SOURCES.txt +13 -1
  26. shrinkwrap_cli-0.1.5/shrinkwrap_cli.egg-info/requires.txt +1 -0
  27. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/tests/test_engine.py +8 -6
  28. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/tests/test_proxy.py +5 -2
  29. shrinkwrap_cli-0.1.5/tests/test_regressions.py +191 -0
  30. shrinkwrap_cli-0.1.5/tests/test_retrieval.py +152 -0
  31. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/tests/test_suite.py +1 -1
  32. shrinkwrap_cli-0.1.5/tests/test_tracker_concurrency.py +32 -0
  33. shrinkwrap_cli-0.1.4/PKG-INFO +0 -206
  34. shrinkwrap_cli-0.1.4/README.md +0 -195
  35. shrinkwrap_cli-0.1.4/shrinkwrap/__init__.py +0 -10
  36. shrinkwrap_cli-0.1.4/shrinkwrap/benchmarks/runner.py +0 -63
  37. shrinkwrap_cli-0.1.4/shrinkwrap/engine/compactor.py +0 -117
  38. shrinkwrap_cli-0.1.4/shrinkwrap/engine/privacy.py +0 -24
  39. shrinkwrap_cli-0.1.4/shrinkwrap/engine/retrieval_buffer.py +0 -67
  40. shrinkwrap_cli-0.1.4/shrinkwrap/proxy/config_manager.py +0 -79
  41. shrinkwrap_cli-0.1.4/shrinkwrap/proxy/http_proxy.py +0 -21
  42. shrinkwrap_cli-0.1.4/shrinkwrap/proxy/stdio_proxy.py +0 -71
  43. shrinkwrap_cli-0.1.4/shrinkwrap_cli.egg-info/PKG-INFO +0 -206
  44. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/LICENSE +0 -0
  45. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/setup.cfg +0 -0
  46. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap/engine/tokenizer.py +0 -0
  47. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap/shell/guidance.py +0 -0
  48. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap_cli.egg-info/dependency_links.txt +0 -0
  49. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/shrinkwrap_cli.egg-info/entry_points.txt +0 -0
  50. {shrinkwrap_cli-0.1.4 → shrinkwrap_cli-0.1.5}/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,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.5 (2026-11-18)
4
+
5
+ - Bound JSON and text previews and avoid summaries that expand the estimated output.
6
+ - Preserve unchanged stdio responses on the wire and compress large, repetitive buffer entries.
7
+ - Keep analytics counters accurate across concurrent proxy processes with locked, atomic updates.
8
+ - Add selective, paged retrieval through the CLI and a `shrinkwrap_fetch` MCP tool.
9
+ - Redact pass-through output and buffered samples, tighten buffer permissions, and validate reference handles.
10
+ - Support Codex TOML configuration and selective server wrapping, improve installer isolation, and add Python 3.9/3.12 tests.
11
+ - Run tests and verify the package version before PyPI publication; publish once per GitHub release.
12
+
13
+ ## 0.1.4
14
+
15
+ 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,2 @@
1
+ include AGENT_PROMPT.md CHANGELOG.md CONTRIBUTING.md
2
+ recursive-include docs *.md
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: shrinkwrap-cli
3
+ Version: 0.1.5
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
+ Dynamic: license-file
15
+
16
+ # ShrinkWrap
17
+
18
+ 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.
19
+
20
+ 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.
21
+
22
+ ## Install and configure
23
+
24
+ ```bash
25
+ python3 -m venv ~/.local/share/shrinkwrap/venv
26
+ ~/.local/share/shrinkwrap/venv/bin/python -m pip install shrinkwrap-cli
27
+ export PATH="$HOME/.local/share/shrinkwrap/venv/bin:$PATH"
28
+ shrinkwrap install --dry-run
29
+ shrinkwrap install
30
+ ```
31
+
32
+ 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.
33
+
34
+ `install` wraps local stdio server commands in supported MCP client configuration files. It supports Codex's `~/.codex/config.toml` and 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:
35
+
36
+ ```bash
37
+ shrinkwrap rollback ~/.codex/config.toml
38
+ ```
39
+
40
+ 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.
41
+
42
+ You can also run the proxy directly:
43
+
44
+ ```bash
45
+ shrinkwrap wrap-stdio -- npx -y @modelcontextprotocol/server-filesystem /path/to/files
46
+ ```
47
+
48
+ ## What gets compacted
49
+
50
+ 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.
51
+
52
+ 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`.
53
+
54
+ ## Retrieve a payload
55
+
56
+ ```bash
57
+ shrinkwrap fetch sw-ref:0123456789ab
58
+ shrinkwrap fetch sw-ref:0123456789ab --pointer /rows/10
59
+ shrinkwrap fetch sw-ref:0123456789ab --pointer /rows --offset 0 --limit 4000
60
+ ```
61
+
62
+ 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.
63
+
64
+ The stdio proxy also advertises a `shrinkwrap_fetch` MCP tool when the wrapped server does not already use that name. An agent can call it with `ref_handle` and optional `pointer`, `offset`, and `limit` arguments. It returns up to 4,000 characters by default, with a 16,000-character maximum per call. Follow `next_offset` to read more. The HTTP transformer does not advertise this tool. The [MCP tools specification](https://modelcontextprotocol.io/specification/2025-11-25/server/tools) defines the discovery and call messages used here.
65
+
66
+ 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.
67
+
68
+ 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.
69
+
70
+ ## Measure your workload
71
+
72
+ ```bash
73
+ shrinkwrap benchmark
74
+ shrinkwrap gain
75
+ shrinkwrap session --markdown
76
+ ```
77
+
78
+ `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.
79
+
80
+ `gain` and `session` report estimated tokens saved by actual proxy calls. Financial figures use a fixed `$3.00 / 1M tokens` assumption and are estimates, not billing data.
81
+
82
+ ## Commands
83
+
84
+ | Command | Purpose |
85
+ | --- | --- |
86
+ | `shrinkwrap install [--dry-run]` | Discover and wrap supported local MCP configs |
87
+ | `shrinkwrap wrap <file> [--server name] [--dry-run]` | Wrap a config file or one named server |
88
+ | `shrinkwrap rollback <file>` | Restore its `.swbak` backup |
89
+ | `shrinkwrap wrap-stdio -- <command> [args]` | Proxy a stdio MCP server |
90
+ | `shrinkwrap fetch <sw-ref:handle>` | Retrieve a buffered redacted payload |
91
+ | `shrinkwrap benchmark` | Run the synthetic compaction suite |
92
+ | `shrinkwrap gain [--history] [--json]` | Show cumulative estimated savings |
93
+ | `shrinkwrap session [--markdown] [--json]` | Show session estimated savings |
94
+ | `shrinkwrap status` | Show installed version and available components |
95
+
96
+ ## Development
97
+
98
+ 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.
99
+
100
+ ```bash
101
+ python3 -m venv .venv
102
+ .venv/bin/python -m pip install -e . pytest
103
+ .venv/bin/python -m pytest -q
104
+ ```
105
+
106
+ ## License
107
+
108
+ MIT. See [LICENSE](https://github.com/lucronn/shrinkwrap/blob/main/LICENSE).
@@ -0,0 +1,93 @@
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 supports Codex's `~/.codex/config.toml` and 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
+ ## What gets compacted
34
+
35
+ 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.
36
+
37
+ 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`.
38
+
39
+ ## Retrieve a payload
40
+
41
+ ```bash
42
+ shrinkwrap fetch sw-ref:0123456789ab
43
+ shrinkwrap fetch sw-ref:0123456789ab --pointer /rows/10
44
+ shrinkwrap fetch sw-ref:0123456789ab --pointer /rows --offset 0 --limit 4000
45
+ ```
46
+
47
+ 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.
48
+
49
+ The stdio proxy also advertises a `shrinkwrap_fetch` MCP tool when the wrapped server does not already use that name. An agent can call it with `ref_handle` and optional `pointer`, `offset`, and `limit` arguments. It returns up to 4,000 characters by default, with a 16,000-character maximum per call. Follow `next_offset` to read more. The HTTP transformer does not advertise this tool. The [MCP tools specification](https://modelcontextprotocol.io/specification/2025-11-25/server/tools) defines the discovery and call messages used here.
50
+
51
+ 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.
52
+
53
+ 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.
54
+
55
+ ## Measure your workload
56
+
57
+ ```bash
58
+ shrinkwrap benchmark
59
+ shrinkwrap gain
60
+ shrinkwrap session --markdown
61
+ ```
62
+
63
+ `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.
64
+
65
+ `gain` and `session` report estimated tokens saved by actual proxy calls. Financial figures use a fixed `$3.00 / 1M tokens` assumption and are estimates, not billing data.
66
+
67
+ ## Commands
68
+
69
+ | Command | Purpose |
70
+ | --- | --- |
71
+ | `shrinkwrap install [--dry-run]` | Discover and wrap supported local MCP configs |
72
+ | `shrinkwrap wrap <file> [--server name] [--dry-run]` | Wrap a config file or one named server |
73
+ | `shrinkwrap rollback <file>` | Restore its `.swbak` backup |
74
+ | `shrinkwrap wrap-stdio -- <command> [args]` | Proxy a stdio MCP server |
75
+ | `shrinkwrap fetch <sw-ref:handle>` | Retrieve a buffered redacted payload |
76
+ | `shrinkwrap benchmark` | Run the synthetic compaction suite |
77
+ | `shrinkwrap gain [--history] [--json]` | Show cumulative estimated savings |
78
+ | `shrinkwrap session [--markdown] [--json]` | Show session estimated savings |
79
+ | `shrinkwrap status` | Show installed version and available components |
80
+
81
+ ## Development
82
+
83
+ 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.
84
+
85
+ ```bash
86
+ python3 -m venv .venv
87
+ .venv/bin/python -m pip install -e . pytest
88
+ .venv/bin/python -m pytest -q
89
+ ```
90
+
91
+ ## License
92
+
93
+ 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 first page of `tools/list`, 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
+ - 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`. 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. `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/2025-11-25/server/tools) for the `tools/list`, `tools/call`, and result formats used by the proxy.
@@ -4,13 +4,18 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "shrinkwrap-cli"
7
- version = "0.1.4"
8
- description = "Drop-in 90%+ Token Compaction Proxy for MCP & AI Agent Tools"
7
+ version = "0.1.5"
8
+ description = "Local stdio MCP tool-result compaction with retrievable references"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "ShrinkWrap Maintainers" }]
11
11
  license = "MIT"
12
12
  requires-python = ">=3.9"
13
- dependencies = []
13
+ dependencies = ["tomlkit>=0.13,<1"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/lucronn/shrinkwrap"
17
+ Issues = "https://github.com/lucronn/shrinkwrap/issues"
18
+ Changelog = "https://github.com/lucronn/shrinkwrap/blob/main/CHANGELOG.md"
14
19
 
15
20
  [project.scripts]
16
21
  shrinkwrap = "shrinkwrap.cli:main"
@@ -0,0 +1,9 @@
1
+ """
2
+ ShrinkWrap: local compaction of MCP tool result text with TTL-backed retrieval.
3
+ """
4
+
5
+ __version__ = "0.1.5"
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
- Real-World Benchmark Corpus for ShrinkWrap.
3
- Contains authentic production-like payloads: GitHub API responses, Postgres query results, Slack thread histories, Web Scrapes, and Python stack traces.
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
+ }
@@ -14,6 +14,7 @@ from shrinkwrap.proxy.config_manager import ConfigManager
14
14
  from shrinkwrap.proxy.stdio_proxy import StdioMCPProxy
15
15
  from shrinkwrap.engine.tracker import global_tracker
16
16
  from shrinkwrap.engine.retrieval_buffer import global_buffer
17
+ from shrinkwrap.engine.retrieval import select_pointer, retrieve_chunk
17
18
  from shrinkwrap import __version__, __coverage_status__, __universal_status__
18
19
 
19
20
  def print_gain_report(history: bool = False, reset: bool = False, output_json: bool = False):
@@ -141,6 +142,9 @@ def main():
141
142
  # fetch
142
143
  fetch_p = subparsers.add_parser("fetch", help="Retrieve uncompacted payload from memory by reference handle")
143
144
  fetch_p.add_argument("ref_handle", type=str, help="Reference handle (e.g. sw-ref:a1b2c3d4)")
145
+ fetch_p.add_argument("--pointer", default="", help="RFC 6901 JSON Pointer into a buffered object or array")
146
+ fetch_p.add_argument("--offset", type=int, help="Character offset for a bounded chunk")
147
+ fetch_p.add_argument("--limit", type=int, help="Maximum characters to return (1-16000)")
144
148
 
145
149
  # benchmark
146
150
  subparsers.add_parser("benchmark", help="Execute benchmark test suite across sample payloads")
@@ -155,6 +159,7 @@ def main():
155
159
  wrap_p = subparsers.add_parser("wrap", help="Wrap MCP server commands in a specific config file")
156
160
  wrap_p.add_argument("config_file", type=str, help="Path to configuration file")
157
161
  wrap_p.add_argument("--dry-run", action="store_true", help="Preview changes without writing")
162
+ wrap_p.add_argument("--server", help="Wrap only this named MCP server")
158
163
 
159
164
  # rollback
160
165
  rollback_p = subparsers.add_parser("rollback", help="Restore configuration file from backup")
@@ -170,15 +175,15 @@ def main():
170
175
  print("Error: No target command specified for wrap-stdio.", file=sys.stderr)
171
176
  sys.exit(1)
172
177
  proxy = StdioMCPProxy(cmd_args)
173
- asyncio.run(proxy.run())
178
+ sys.exit(asyncio.run(proxy.run()))
174
179
 
175
180
  elif args.subcommand == "status":
176
181
  print(f"ShrinkWrap System Status")
177
182
  print(f"========================")
178
183
  print(f"Version: {__version__}")
179
184
  print(f"Coverage Status: {__coverage_status__}")
180
- print(f"Universal Gate: {__universal_status__}")
181
- print("Active Adapters: shell, stdio_mcp_proxy, http_mcp_proxy")
185
+ print(f"Host Interception: {__universal_status__}")
186
+ print("Available: stdio MCP proxy, HTTP response transformer, shell guidance")
182
187
 
183
188
  elif args.subcommand in ("gain", "stats"):
184
189
  print_gain_report(history=args.history, reset=args.reset, output_json=args.json)
@@ -187,15 +192,22 @@ def main():
187
192
  print_session_report(session_id=args.session_id, markdown=args.markdown, output_json=args.json)
188
193
 
189
194
  elif args.subcommand == "fetch":
190
-
191
195
  data = global_buffer.fetch(args.ref_handle)
192
196
  if data is None:
193
197
  print(f"Error: Reference handle '{args.ref_handle}' not found or expired.", file=sys.stderr)
194
198
  sys.exit(1)
195
- if isinstance(data, (dict, list)):
196
- print(json.dumps(data, indent=2))
197
- else:
198
- print(data)
199
+ try:
200
+ if args.offset is not None or args.limit is not None:
201
+ chunk = retrieve_chunk(data, pointer=args.pointer,
202
+ offset=args.offset if args.offset is not None else 0,
203
+ limit=args.limit if args.limit is not None else 4_000)
204
+ print(json.dumps(chunk, ensure_ascii=False))
205
+ else:
206
+ selected = select_pointer(data, args.pointer)
207
+ print(selected if isinstance(selected, str) else json.dumps(selected, indent=2, ensure_ascii=False))
208
+ except ValueError as exc:
209
+ print(f"Error: {exc}", file=sys.stderr)
210
+ sys.exit(1)
199
211
 
200
212
  elif args.subcommand == "benchmark":
201
213
  res = run_benchmark_suite()
@@ -222,19 +234,28 @@ def main():
222
234
  if not configs:
223
235
  print("No supported MCP client configuration files detected.")
224
236
  sys.exit(0)
237
+ failed = False
225
238
  for c in configs:
226
239
  ok, msg = cm.wrap_config(c, dry_run=args.dry_run)
227
240
  print(f"[{c.name}] {msg}")
241
+ failed |= not ok
242
+ if failed:
243
+ sys.exit(1)
228
244
 
229
245
  elif args.subcommand == "wrap":
230
246
  cm = ConfigManager()
231
- ok, msg = cm.wrap_config(Path(args.config_file), dry_run=args.dry_run)
247
+ ok, msg = cm.wrap_config(Path(args.config_file), dry_run=args.dry_run,
248
+ server_name=args.server)
232
249
  print(msg)
250
+ if not ok:
251
+ sys.exit(1)
233
252
 
234
253
  elif args.subcommand == "rollback":
235
254
  cm = ConfigManager()
236
255
  ok, msg = cm.rollback_config(Path(args.config_file))
237
256
  print(msg)
257
+ if not ok:
258
+ sys.exit(1)
238
259
 
239
260
  else:
240
261
  parser.print_help()