shrinkwrap-cli 0.1.5__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.
Files changed (43) hide show
  1. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/CHANGELOG.md +8 -0
  2. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/PKG-INFO +15 -5
  3. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/README.md +12 -4
  4. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/docs/architecture.md +5 -5
  5. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/pyproject.toml +4 -1
  6. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/__init__.py +1 -1
  7. shrinkwrap_cli-0.1.6/shrinkwrap/benchmarks/stdio.py +167 -0
  8. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/cli.py +35 -3
  9. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/compactor.py +17 -3
  10. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/retrieval.py +16 -3
  11. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/tracker.py +24 -8
  12. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/proxy/config_manager.py +9 -7
  13. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/proxy/stdio_proxy.py +101 -33
  14. shrinkwrap_cli-0.1.6/shrinkwrap/proxy/transform.py +49 -0
  15. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/PKG-INFO +15 -5
  16. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/SOURCES.txt +2 -0
  17. shrinkwrap_cli-0.1.6/shrinkwrap_cli.egg-info/requires.txt +4 -0
  18. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/tests/test_regressions.py +1 -0
  19. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/tests/test_retrieval.py +13 -3
  20. shrinkwrap_cli-0.1.6/tests/test_stdio_workflows.py +119 -0
  21. shrinkwrap_cli-0.1.5/shrinkwrap/proxy/transform.py +0 -46
  22. shrinkwrap_cli-0.1.5/shrinkwrap_cli.egg-info/requires.txt +0 -1
  23. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/AGENT_PROMPT.md +0 -0
  24. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/CONTRIBUTING.md +0 -0
  25. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/LICENSE +0 -0
  26. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/MANIFEST.in +0 -0
  27. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/setup.cfg +0 -0
  28. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/benchmarks/corpus.py +0 -0
  29. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/benchmarks/runner.py +0 -0
  30. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/privacy.py +0 -0
  31. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/retrieval_buffer.py +0 -0
  32. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/engine/tokenizer.py +0 -0
  33. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/gap_report/gap_report.py +0 -0
  34. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/proxy/http_proxy.py +0 -0
  35. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/shell/guidance.py +0 -0
  36. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap/state.py +0 -0
  37. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/dependency_links.txt +0 -0
  38. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/entry_points.txt +0 -0
  39. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/shrinkwrap_cli.egg-info/top_level.txt +0 -0
  40. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/tests/test_engine.py +0 -0
  41. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/tests/test_proxy.py +0 -0
  42. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/tests/test_suite.py +0 -0
  43. {shrinkwrap_cli-0.1.5 → shrinkwrap_cli-0.1.6}/tests/test_tracker_concurrency.py +0 -0
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
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
+
3
11
  ## 0.1.5 (2026-11-18)
4
12
 
5
13
  - Bound JSON and text previews and avoid summaries that expand the estimated output.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: shrinkwrap-cli
3
- Version: 0.1.5
3
+ Version: 0.1.6
4
4
  Summary: Local stdio MCP tool-result compaction with retrievable references
5
5
  Author: ShrinkWrap Maintainers
6
6
  License-Expression: MIT
@@ -11,6 +11,8 @@ Requires-Python: >=3.9
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
13
  Requires-Dist: tomlkit<1,>=0.13
14
+ Provides-Extra: benchmark
15
+ Requires-Dist: tiktoken>=0.7; extra == "benchmark"
14
16
  Dynamic: license-file
15
17
 
16
18
  # ShrinkWrap
@@ -31,7 +33,7 @@ shrinkwrap install
31
33
 
32
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.
33
35
 
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:
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:
35
37
 
36
38
  ```bash
37
39
  shrinkwrap rollback ~/.codex/config.toml
@@ -45,6 +47,8 @@ You can also run the proxy directly:
45
47
  shrinkwrap wrap-stdio -- npx -y @modelcontextprotocol/server-filesystem /path/to/files
46
48
  ```
47
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
+
48
52
  ## What gets compacted
49
53
 
50
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.
@@ -56,12 +60,13 @@ Tool results may also contain `structuredContent`. ShrinkWrap redacts strings in
56
60
  ```bash
57
61
  shrinkwrap fetch sw-ref:0123456789ab
58
62
  shrinkwrap fetch sw-ref:0123456789ab --pointer /rows/10
63
+ shrinkwrap fetch sw-ref:0123456789ab --pointer /files --match path src/main.py
59
64
  shrinkwrap fetch sw-ref:0123456789ab --pointer /rows --offset 0 --limit 4000
60
65
  ```
61
66
 
62
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.
63
68
 
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.
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.
65
70
 
66
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.
67
72
 
@@ -71,13 +76,18 @@ Redaction handles common token formats, private key blocks, bearer values, and n
71
76
 
72
77
  ```bash
73
78
  shrinkwrap benchmark
79
+ shrinkwrap benchmark --stdio
74
80
  shrinkwrap gain
75
81
  shrinkwrap session --markdown
76
82
  ```
77
83
 
78
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.
79
85
 
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.
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.
81
91
 
82
92
  ## Commands
83
93
 
@@ -88,7 +98,7 @@ shrinkwrap session --markdown
88
98
  | `shrinkwrap rollback <file>` | Restore its `.swbak` backup |
89
99
  | `shrinkwrap wrap-stdio -- <command> [args]` | Proxy a stdio MCP server |
90
100
  | `shrinkwrap fetch <sw-ref:handle>` | Retrieve a buffered redacted payload |
91
- | `shrinkwrap benchmark` | Run the synthetic compaction suite |
101
+ | `shrinkwrap benchmark [--stdio] [--json]` | Measure engine compaction or complete stdio workflows |
92
102
  | `shrinkwrap gain [--history] [--json]` | Show cumulative estimated savings |
93
103
  | `shrinkwrap session [--markdown] [--json]` | Show session estimated savings |
94
104
  | `shrinkwrap status` | Show installed version and available components |
@@ -16,7 +16,7 @@ shrinkwrap install
16
16
 
17
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
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:
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
20
 
21
21
  ```bash
22
22
  shrinkwrap rollback ~/.codex/config.toml
@@ -30,6 +30,8 @@ You can also run the proxy directly:
30
30
  shrinkwrap wrap-stdio -- npx -y @modelcontextprotocol/server-filesystem /path/to/files
31
31
  ```
32
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
+
33
35
  ## What gets compacted
34
36
 
35
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.
@@ -41,12 +43,13 @@ Tool results may also contain `structuredContent`. ShrinkWrap redacts strings in
41
43
  ```bash
42
44
  shrinkwrap fetch sw-ref:0123456789ab
43
45
  shrinkwrap fetch sw-ref:0123456789ab --pointer /rows/10
46
+ shrinkwrap fetch sw-ref:0123456789ab --pointer /files --match path src/main.py
44
47
  shrinkwrap fetch sw-ref:0123456789ab --pointer /rows --offset 0 --limit 4000
45
48
  ```
46
49
 
47
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.
48
51
 
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.
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.
50
53
 
51
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.
52
55
 
@@ -56,13 +59,18 @@ Redaction handles common token formats, private key blocks, bearer values, and n
56
59
 
57
60
  ```bash
58
61
  shrinkwrap benchmark
62
+ shrinkwrap benchmark --stdio
59
63
  shrinkwrap gain
60
64
  shrinkwrap session --markdown
61
65
  ```
62
66
 
63
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.
64
68
 
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.
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.
66
74
 
67
75
  ## Commands
68
76
 
@@ -73,7 +81,7 @@ shrinkwrap session --markdown
73
81
  | `shrinkwrap rollback <file>` | Restore its `.swbak` backup |
74
82
  | `shrinkwrap wrap-stdio -- <command> [args]` | Proxy a stdio MCP server |
75
83
  | `shrinkwrap fetch <sw-ref:handle>` | Retrieve a buffered redacted payload |
76
- | `shrinkwrap benchmark` | Run the synthetic compaction suite |
84
+ | `shrinkwrap benchmark [--stdio] [--json]` | Measure engine compaction or complete stdio workflows |
77
85
  | `shrinkwrap gain [--history] [--json]` | Show cumulative estimated savings |
78
86
  | `shrinkwrap session [--markdown] [--json]` | Show session estimated savings |
79
87
  | `shrinkwrap status` | Show installed version and available components |
@@ -14,8 +14,8 @@ flowchart LR
14
14
  ## Stdio message flow
15
15
 
16
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.
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
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
20
 
21
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.
@@ -26,11 +26,11 @@ The engine converts input to text, redacts recognized secrets, estimates tokens,
26
26
 
27
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
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.
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
30
 
31
31
  ## Retrieval
32
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.
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
34
 
35
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
36
 
@@ -45,4 +45,4 @@ Handles are 12 hexadecimal characters from a SHA-256 digest. They identify cache
45
45
  | Shell command output | No automatic interception |
46
46
  | Hosted tools and connected apps | No automatic interception |
47
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.
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.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "shrinkwrap-cli"
7
- version = "0.1.5"
7
+ version = "0.1.6"
8
8
  description = "Local stdio MCP tool-result compaction with retrievable references"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "ShrinkWrap Maintainers" }]
@@ -12,6 +12,9 @@ license = "MIT"
12
12
  requires-python = ">=3.9"
13
13
  dependencies = ["tomlkit>=0.13,<1"]
14
14
 
15
+ [project.optional-dependencies]
16
+ benchmark = ["tiktoken>=0.7"]
17
+
15
18
  [project.urls]
16
19
  Repository = "https://github.com/lucronn/shrinkwrap"
17
20
  Issues = "https://github.com/lucronn/shrinkwrap/issues"
@@ -2,7 +2,7 @@
2
2
  ShrinkWrap: local compaction of MCP tool result text with TTL-backed retrieval.
3
3
  """
4
4
 
5
- __version__ = "0.1.5"
5
+ __version__ = "0.1.6"
6
6
 
7
7
 
8
8
  __coverage_status__ = "stdio MCP proxy; HTTP response transformer library"
@@ -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()
@@ -143,11 +143,16 @@ def main():
143
143
  fetch_p = subparsers.add_parser("fetch", help="Retrieve uncompacted payload from memory by reference handle")
144
144
  fetch_p.add_argument("ref_handle", type=str, help="Reference handle (e.g. sw-ref:a1b2c3d4)")
145
145
  fetch_p.add_argument("--pointer", default="", help="RFC 6901 JSON Pointer into a buffered object or array")
146
+ fetch_p.add_argument("--match", nargs=2, metavar=("FIELD", "VALUE"),
147
+ help="Select one array row by an exact string field value")
146
148
  fetch_p.add_argument("--offset", type=int, help="Character offset for a bounded chunk")
147
149
  fetch_p.add_argument("--limit", type=int, help="Maximum characters to return (1-16000)")
148
150
 
149
151
  # benchmark
150
- subparsers.add_parser("benchmark", help="Execute benchmark test suite across sample payloads")
152
+ bench = subparsers.add_parser("benchmark", help="Measure compaction and retrieval")
153
+ bench.add_argument("--stdio", action="store_true", help="Measure complete local stdio exchanges")
154
+ bench.add_argument("--encoding", help="Tokenizer for the stdio run, e.g. o200k_base")
155
+ bench.add_argument("--json", action="store_true", help="Print machine-readable measurements")
151
156
 
152
157
  # gap-report
153
158
  subparsers.add_parser("gap-report", help="Display host capability audit and extension proposal")
@@ -196,21 +201,48 @@ def main():
196
201
  if data is None:
197
202
  print(f"Error: Reference handle '{args.ref_handle}' not found or expired.", file=sys.stderr)
198
203
  sys.exit(1)
204
+ match = dict(zip(("field", "value"), args.match)) if args.match else None
199
205
  try:
200
206
  if args.offset is not None or args.limit is not None:
201
- chunk = retrieve_chunk(data, pointer=args.pointer,
207
+ chunk = retrieve_chunk(data, pointer=args.pointer, match=match,
202
208
  offset=args.offset if args.offset is not None else 0,
203
209
  limit=args.limit if args.limit is not None else 4_000)
204
210
  print(json.dumps(chunk, ensure_ascii=False))
205
211
  else:
206
- selected = select_pointer(data, args.pointer)
212
+ selected = select_pointer(data, args.pointer, match)
207
213
  print(selected if isinstance(selected, str) else json.dumps(selected, indent=2, ensure_ascii=False))
208
214
  except ValueError as exc:
209
215
  print(f"Error: {exc}", file=sys.stderr)
210
216
  sys.exit(1)
211
217
 
212
218
  elif args.subcommand == "benchmark":
219
+ if args.stdio:
220
+ from shrinkwrap.benchmarks.stdio import run_stdio_benchmark
221
+ try:
222
+ report = asyncio.run(run_stdio_benchmark(args.encoding or "estimate"))
223
+ except ValueError as exc:
224
+ parser.error(str(exc))
225
+ if args.json:
226
+ print(json.dumps(report, indent=2))
227
+ return
228
+ print(f"Stdio benchmark ({report['encoding']}, {report['samples_per_case']} samples per case)")
229
+ print("Case Mode Median ms P95 ms Reply bytes Text tokens")
230
+ for name, modes in report["cases"].items():
231
+ for mode, row in modes.items():
232
+ print(f"{name:<20} {mode:<8} {row['median_ms']:>9.3f} {row['p95_ms']:>8.3f}"
233
+ f" {row['response_bytes']:>13} {row['returned_text_tokens']:>13}")
234
+ for task, row in report["retrieval"].items():
235
+ print(f"{task}: {row['fetch_calls']} fetch(es), {row['returned_text_tokens']} returned text tokens,"
236
+ f" {row['fetch_argument_tokens']} fetch argument tokens, {row['round_trip_bytes']} wire bytes")
237
+ rss = report["proxy_peak_rss_kib"]
238
+ print(f"Proxy peak RSS: {rss} KiB" if rss is not None else "Proxy peak RSS unavailable")
239
+ return
240
+ if args.encoding:
241
+ parser.error("--encoding requires --stdio")
213
242
  res = run_benchmark_suite()
243
+ if args.json:
244
+ print(json.dumps(res, indent=2))
245
+ return
214
246
  s = res["summary"]
215
247
  print("ShrinkWrap Benchmark Report")
216
248
  print("===========================")
@@ -4,6 +4,7 @@ Applies 5 schema-aware compaction strategies based on tool output characteristic
4
4
  """
5
5
 
6
6
  import json
7
+ from contextlib import contextmanager
7
8
  from itertools import islice
8
9
  from typing import Any, Dict, Tuple
9
10
  from shrinkwrap.engine.tokenizer import estimate_tokens
@@ -20,7 +21,20 @@ class CompactionEngine:
20
21
  self.record_stats = record_stats
21
22
  self.buffer = buffer or global_buffer
22
23
 
23
- def compact(self, raw_input: Any, source_type: str = "generic", tool_name: str = "generic_tool") -> Tuple[Any, str, int, int]:
24
+ @contextmanager
25
+ def batch_stats(self):
26
+ events = []
27
+
28
+ def collect(**event):
29
+ events.append(event)
30
+
31
+ yield collect
32
+ if events:
33
+ global_tracker.record_events(events)
34
+
35
+ def compact(self, raw_input: Any, source_type: str = "generic", tool_name: str = "generic_tool",
36
+ *, record_event=None) -> Tuple[Any, str, int, int]:
37
+ record_event = record_event or global_tracker.record_event
24
38
  structured = isinstance(raw_input, (dict, list))
25
39
  raw_str = json.dumps(raw_input, ensure_ascii=False, separators=(",", ":")) if structured else str(raw_input)
26
40
  if structured:
@@ -39,7 +53,7 @@ class CompactionEngine:
39
53
 
40
54
  if orig_tokens <= self.token_threshold:
41
55
  if self.record_stats:
42
- global_tracker.record_event(
56
+ record_event(
43
57
  orig_tokens=orig_tokens,
44
58
  comp_tokens=pass_tokens,
45
59
  orig_bytes=orig_bytes,
@@ -74,7 +88,7 @@ class CompactionEngine:
74
88
  comp_tokens, comp_bytes = pass_tokens, pass_bytes
75
89
 
76
90
  if self.record_stats:
77
- global_tracker.record_event(
91
+ record_event(
78
92
  orig_tokens=orig_tokens,
79
93
  comp_tokens=comp_tokens,
80
94
  orig_bytes=orig_bytes,
@@ -11,7 +11,7 @@ _ARRAY_INDEX = re.compile(r"(?:0|[1-9][0-9]*)\Z")
11
11
  _INVALID_ESCAPE = re.compile(r"~(?![01])")
12
12
 
13
13
 
14
- def select_pointer(data: Any, pointer: str = "") -> Any:
14
+ def select_pointer(data: Any, pointer: str = "", match=None) -> Any:
15
15
  """Resolve an RFC 6901 JSON Pointer, raising ValueError on failure."""
16
16
  if not isinstance(pointer, str) or (pointer and not pointer.startswith("/")):
17
17
  raise ValueError("pointer must be empty or start with '/'")
@@ -30,6 +30,19 @@ def select_pointer(data: Any, pointer: str = "") -> Any:
30
30
  selected = selected[int(token)]
31
31
  else:
32
32
  raise ValueError("pointer traverses a scalar value")
33
+ if match is not None:
34
+ if (not isinstance(match, dict) or set(match) != {"field", "value"}
35
+ or not all(isinstance(v, str) for v in match.values())):
36
+ raise ValueError("match requires a string field and string value")
37
+ if not isinstance(selected, list):
38
+ raise ValueError("match requires an array at pointer")
39
+ rows = (row for row in selected if isinstance(row, dict)
40
+ and row.get(match["field"]) == match["value"])
41
+ selected = next(rows, None)
42
+ if selected is None:
43
+ raise ValueError("no row matches that field and value")
44
+ if next(rows, None) is not None:
45
+ raise ValueError("multiple rows match that field and value")
33
46
  return selected
34
47
 
35
48
 
@@ -38,12 +51,12 @@ def render_value(value: Any) -> str:
38
51
 
39
52
 
40
53
  def retrieve_chunk(data: Any, pointer: str = "", offset: int = 0,
41
- limit: int = DEFAULT_CHUNK_CHARS) -> Dict[str, Any]:
54
+ limit: int = DEFAULT_CHUNK_CHARS, match=None) -> Dict[str, Any]:
42
55
  if type(offset) is not int or offset < 0:
43
56
  raise ValueError("offset must be a non-negative integer")
44
57
  if type(limit) is not int or not 1 <= limit <= MAX_CHUNK_CHARS:
45
58
  raise ValueError(f"limit must be between 1 and {MAX_CHUNK_CHARS}")
46
- text = render_value(select_pointer(data, pointer))
59
+ text = render_value(select_pointer(data, pointer, match))
47
60
  end = min(offset + limit, len(text))
48
61
  return {
49
62
  "pointer": pointer,
@@ -118,7 +118,6 @@ class TokenTracker:
118
118
  if os.path.exists(tmp_name):
119
119
  os.unlink(tmp_name)
120
120
 
121
- @_with_lock
122
121
  def record_event(
123
122
  self,
124
123
  orig_tokens: int,
@@ -131,13 +130,32 @@ class TokenTracker:
131
130
  harness: Optional[str] = None,
132
131
  session_id: Optional[str] = None
133
132
  ):
134
- harness = harness or detect_harness()
135
- session_id = session_id or detect_session_id()
133
+ self.record_events([dict(orig_tokens=orig_tokens, comp_tokens=comp_tokens,
134
+ orig_bytes=orig_bytes, comp_bytes=comp_bytes,
135
+ source_class=source_class, tool_name=tool_name, strategy=strategy,
136
+ harness=harness, session_id=session_id)])
137
+
138
+ @_with_lock
139
+ def record_events(self, events):
140
+ data = self._load()
141
+ harness = detect_harness()
142
+ session = detect_session_id()
143
+ for event in events:
144
+ self._apply_event(data, event.get("harness") or harness,
145
+ event.get("session_id") or session, event)
146
+ self._save(data)
147
+
148
+ @staticmethod
149
+ def _apply_event(data, harness, session_id, event):
150
+ orig_tokens = event["orig_tokens"]
151
+ comp_tokens = event["comp_tokens"]
152
+ orig_bytes = event["orig_bytes"]
153
+ comp_bytes = event["comp_bytes"]
154
+ tool_name = event["tool_name"]
136
155
  tokens_saved = max(0, orig_tokens - comp_tokens)
137
156
  bytes_saved = max(0, orig_bytes - comp_bytes)
138
157
  was_compacted = comp_tokens < orig_tokens
139
158
 
140
- data = self._load()
141
159
  t = data["totals"]
142
160
  t["total_invocations"] += 1
143
161
  if was_compacted:
@@ -178,8 +196,8 @@ class TokenTracker:
178
196
  "harness": harness,
179
197
  "session_id": session_id,
180
198
  "tool": tool_name,
181
- "source_class": source_class,
182
- "strategy": strategy,
199
+ "source_class": event["source_class"],
200
+ "strategy": event["strategy"],
183
201
  "orig_tokens": orig_tokens,
184
202
  "compacted_tokens": comp_tokens,
185
203
  "tokens_saved": tokens_saved,
@@ -188,8 +206,6 @@ class TokenTracker:
188
206
  data["history"].insert(0, history_entry)
189
207
  data["history"] = data["history"][:100]
190
208
 
191
- self._save(data)
192
-
193
209
  @_with_lock
194
210
  def get_stats(self) -> Dict[str, Any]:
195
211
  return self._load()