cap-shield 0.3.0__tar.gz → 0.4.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cap-shield
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Context selection and compression for AI agents — measured, not estimated
5
5
  Project-URL: Homepage, https://cap-shield-robin.fly.dev
6
6
  Project-URL: Documentation, https://cap-shield-robin.fly.dev/docs/quickstart
@@ -87,3 +87,41 @@ Conflating them is the most common misunderstanding about this product.
87
87
  ## Full documentation
88
88
 
89
89
  <https://cap-shield-robin.fly.dev/docs/quickstart>
90
+
91
+
92
+ <!-- mcp-name: io.github.robinlidberg-dot/cap-shield -->
93
+
94
+ ## MCP server
95
+
96
+ The package also contains an MCP server. Five tools, no extra
97
+ dependencies, and two of them work without an account.
98
+
99
+ ```bash
100
+ pip install cap-shield
101
+ ```
102
+
103
+ ```json
104
+ {
105
+ "mcpServers": {
106
+ "cap-shield": {
107
+ "command": "python",
108
+ "args": ["-m", "cap_mcp"],
109
+ "env": {
110
+ "CAP_SHIELD_API_KEY": "cap_live_..."
111
+ }
112
+ }
113
+ }
114
+ }
115
+ ```
116
+
117
+ The `env` block is only needed for `remember` and `assemble_context`.
118
+ Leave it out and `measure_traffic` and `list_packages` still work.
119
+
120
+ Source and docs: https://github.com/robinlidberg-dot/cap-shield-mcp
121
+
122
+ The server can also be fetched as a single file, for anyone who would
123
+ rather not install a package:
124
+
125
+ ```bash
126
+ curl -O https://cap-shield-robin.fly.dev/cap_mcp.py
127
+ ```
@@ -1,71 +1,109 @@
1
- # cap-shield
2
-
3
- Context selection for AI agents. **Measured, not estimated.**
4
-
5
- ```bash
6
- pip install cap-shield
7
- ```
8
-
9
- ```python
10
- from cap_shield import CapShield
11
-
12
- cap = CapShield(api_key="cap_live_...")
13
-
14
- cap.remember("support", "Customer reports a delayed parcel, order 4471")
15
- ctx = cap.context("support", "what did the customer complain about?")
16
-
17
- print(ctx.text) # send this to your model
18
- print(ctx.saving_pct, "%") # how much you did not send
19
- print(ctx.left_behind) # ...and how many entries were left behind
20
- ```
21
-
22
- ## What this does
23
-
24
- Your agent's history grows every turn, and the whole thing is billed on
25
- every call. This selects what answers the question and leaves the rest.
26
-
27
- Measured on our corpus with `cl100k_base`: **80.5 %** of context not sent
28
- at a 1000-token budget. Measured on LongMemEval-S, 500 questions:
29
- **93.8 %** retrieval recall against **51.9 %** for word matching.
30
-
31
- That second number is the one that matters. A saving is worthless if what
32
- was dropped is what your agent needed — so we publish both.
33
-
34
- ## What this does not do
35
-
36
- It does not call your model. `ctx.text` goes to Claude, GPT or whatever
37
- you use. This library never sees your model provider's keys.
38
-
39
- It is not a proxy. Your uptime does not depend on ours for the model call
40
- itself.
41
-
42
- ## Measure before you commit
43
-
44
- **No account, no key:**
45
-
46
- ```python
47
- from cap_shield import measure, print_measurement
48
-
49
- print_measurement(measure(
50
- texts=["...your actual messages..."],
51
- query="what your agent would search for"))
52
- ```
53
-
54
- Runs on your own traffic and stores nothing — the text is compressed in
55
- memory, the numbers computed, and everything discarded. No dictionary is
56
- trained on it.
57
-
58
- Rate limited to 20 measurements per hour per IP. Enough to evaluate, not
59
- enough to use the service for free.
60
-
61
- ## Two mechanisms, deliberately separate
62
-
63
- `context()` saves **tokens** — what your model is billed for.
64
- `pack()` saves **bytes** — bandwidth and storage. The packet is
65
- decompressed before the model sees it, so it saves no tokens.
66
-
67
- Conflating them is the most common misunderstanding about this product.
68
-
69
- ## Full documentation
70
-
71
- <https://cap-shield-robin.fly.dev/docs/quickstart>
1
+ # cap-shield
2
+
3
+ Context selection for AI agents. **Measured, not estimated.**
4
+
5
+ ```bash
6
+ pip install cap-shield
7
+ ```
8
+
9
+ ```python
10
+ from cap_shield import CapShield
11
+
12
+ cap = CapShield(api_key="cap_live_...")
13
+
14
+ cap.remember("support", "Customer reports a delayed parcel, order 4471")
15
+ ctx = cap.context("support", "what did the customer complain about?")
16
+
17
+ print(ctx.text) # send this to your model
18
+ print(ctx.saving_pct, "%") # how much you did not send
19
+ print(ctx.left_behind) # ...and how many entries were left behind
20
+ ```
21
+
22
+ ## What this does
23
+
24
+ Your agent's history grows every turn, and the whole thing is billed on
25
+ every call. This selects what answers the question and leaves the rest.
26
+
27
+ Measured on our corpus with `cl100k_base`: **80.5 %** of context not sent
28
+ at a 1000-token budget. Measured on LongMemEval-S, 500 questions:
29
+ **93.8 %** retrieval recall against **51.9 %** for word matching.
30
+
31
+ That second number is the one that matters. A saving is worthless if what
32
+ was dropped is what your agent needed — so we publish both.
33
+
34
+ ## What this does not do
35
+
36
+ It does not call your model. `ctx.text` goes to Claude, GPT or whatever
37
+ you use. This library never sees your model provider's keys.
38
+
39
+ It is not a proxy. Your uptime does not depend on ours for the model call
40
+ itself.
41
+
42
+ ## Measure before you commit
43
+
44
+ **No account, no key:**
45
+
46
+ ```python
47
+ from cap_shield import measure, print_measurement
48
+
49
+ print_measurement(measure(
50
+ texts=["...your actual messages..."],
51
+ query="what your agent would search for"))
52
+ ```
53
+
54
+ Runs on your own traffic and stores nothing — the text is compressed in
55
+ memory, the numbers computed, and everything discarded. No dictionary is
56
+ trained on it.
57
+
58
+ Rate limited to 20 measurements per hour per IP. Enough to evaluate, not
59
+ enough to use the service for free.
60
+
61
+ ## Two mechanisms, deliberately separate
62
+
63
+ `context()` saves **tokens** — what your model is billed for.
64
+ `pack()` saves **bytes** — bandwidth and storage. The packet is
65
+ decompressed before the model sees it, so it saves no tokens.
66
+
67
+ Conflating them is the most common misunderstanding about this product.
68
+
69
+ ## Full documentation
70
+
71
+ <https://cap-shield-robin.fly.dev/docs/quickstart>
72
+
73
+
74
+ <!-- mcp-name: io.github.robinlidberg-dot/cap-shield -->
75
+
76
+ ## MCP server
77
+
78
+ The package also contains an MCP server. Five tools, no extra
79
+ dependencies, and two of them work without an account.
80
+
81
+ ```bash
82
+ pip install cap-shield
83
+ ```
84
+
85
+ ```json
86
+ {
87
+ "mcpServers": {
88
+ "cap-shield": {
89
+ "command": "python",
90
+ "args": ["-m", "cap_mcp"],
91
+ "env": {
92
+ "CAP_SHIELD_API_KEY": "cap_live_..."
93
+ }
94
+ }
95
+ }
96
+ }
97
+ ```
98
+
99
+ The `env` block is only needed for `remember` and `assemble_context`.
100
+ Leave it out and `measure_traffic` and `list_packages` still work.
101
+
102
+ Source and docs: https://github.com/robinlidberg-dot/cap-shield-mcp
103
+
104
+ The server can also be fetched as a single file, for anyone who would
105
+ rather not install a package:
106
+
107
+ ```bash
108
+ curl -O https://cap-shield-robin.fly.dev/cap_mcp.py
109
+ ```
@@ -0,0 +1,316 @@
1
+ """
2
+ CAP-Shield — MCP-server
3
+ ========================
4
+ Gör tjänsten upptäckbar för AI-agenter.
5
+
6
+ VARFÖR DENNA FINNS:
7
+ /.well-known/cap-shield.json beskriver hela ytan maskinläsbart, men
8
+ hjälper bara någon som REDAN känner till domänen. Ingen agent letar
9
+ där spontant.
10
+
11
+ Fyra register avgör synligheten i praktiken — mcp.so, smithery.ai,
12
+ glama.ai och awesome-mcp-servers — och de listar MCP-servrar. Ett
13
+ REST-API syns inte där, hur välbeskrivet det än är.
14
+
15
+ Det här är alltså inte ett nytt API. Det är samma API med ett omslag
16
+ som gör att en agent kan hitta det.
17
+
18
+ VARFÖR INGET MCP-SDK:
19
+ Protokollet är JSON-RPC 2.0 över stdio. Ett SDK sparar femtio rader
20
+ och lägger till ett beroende som måste hållas synkat med
21
+ protokollversionen. För en server med fem verktyg är det fel affär.
22
+
23
+ KÖR:
24
+ python cap_mcp.py
25
+
26
+ KONFIGURATION i en agents mcp-inställningar:
27
+ {
28
+ "mcpServers": {
29
+ "cap-shield": {
30
+ "command": "python",
31
+ "args": ["/sökväg/till/cap_mcp.py"],
32
+ "env": {"CAP_SHIELD_API_KEY": "cap_live_..."}
33
+ }
34
+ }
35
+ }
36
+
37
+ Utan nyckel fungerar bara measure — och det är avsiktligt. En agent ska
38
+ kunna MÄTA innan någon registrerar sig.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import os
45
+ import sys
46
+ from typing import Any
47
+
48
+ BAS = os.environ.get("CAP_SHIELD_URL", "https://cap-shield-robin.fly.dev")
49
+ PROTOKOLL = "2024-11-05"
50
+ VERSION = "0.1.0"
51
+
52
+
53
+ # ----------------------------------------------------------------------
54
+ # Verktygen
55
+ # ----------------------------------------------------------------------
56
+ # BESKRIVNINGARNA ÄR RIKTADE TILL EN MODELL, inte till en människa.
57
+ # En agent väljer verktyg på beskrivningen ensam — den ser ingen
58
+ # dokumentation, inget exempel och ingen landningssida. Därför står det
59
+ # rakt ut vad varje verktyg INTE gör, så att den inte väljer fel.
60
+ VERKTYG = [
61
+ {
62
+ "name": "measure_traffic",
63
+ "description": (
64
+ "Measure how much of your own agent traffic could be saved. "
65
+ "NO ACCOUNT OR KEY NEEDED — use this first. Returns byte "
66
+ "savings over the wire and, if a query is given, token savings "
67
+ "from selective context retrieval. Nothing is stored: the text "
68
+ "is compressed in memory and discarded. Rate limited to 20 "
69
+ "calls per hour per IP."
70
+ ),
71
+ "inputSchema": {
72
+ "type": "object",
73
+ "properties": {
74
+ "texts": {
75
+ "type": "array", "items": {"type": "string"},
76
+ "description": "Your actual messages. 200 max.",
77
+ },
78
+ "query": {
79
+ "type": "string",
80
+ "description": (
81
+ "Optional. What your agent would search its memory "
82
+ "for. Given this, token savings are measured too."),
83
+ },
84
+ "dict_id": {
85
+ "type": "string", "default": "finance",
86
+ "description": (
87
+ "Which trained dictionary to measure against. Call "
88
+ "list_packages to see the options and their measured "
89
+ "figures."),
90
+ },
91
+ },
92
+ "required": ["texts"],
93
+ },
94
+ },
95
+ {
96
+ "name": "list_packages",
97
+ "description": (
98
+ "List the available dictionaries with their MEASURED "
99
+ "compression, including the ones that perform badly. Each entry "
100
+ "says whether it works one message at a time or only batched, "
101
+ "and how many messages came out LARGER. No key needed."
102
+ ),
103
+ "inputSchema": {"type": "object", "properties": {}},
104
+ },
105
+ {
106
+ "name": "remember",
107
+ "description": (
108
+ "Store a memory entry for later retrieval. REQUIRES A KEY. "
109
+ "This does not call any language model — it stores text in an "
110
+ "isolated per-tenant archive. Use assemble_context to get "
111
+ "relevant entries back."
112
+ ),
113
+ "inputSchema": {
114
+ "type": "object",
115
+ "properties": {
116
+ "namespace": {"type": "string",
117
+ "description": "Groups related memories."},
118
+ "text": {"type": "string"},
119
+ "item_id": {
120
+ "type": "string",
121
+ "description": (
122
+ "Optional. Same id overwrites the entry. Omit for "
123
+ "a generated one."),
124
+ },
125
+ },
126
+ "required": ["namespace", "text"],
127
+ },
128
+ },
129
+ {
130
+ "name": "assemble_context",
131
+ "description": (
132
+ "Retrieve the memory entries that answer a question, within a "
133
+ "token budget. REQUIRES A KEY. Send the returned 'context' to "
134
+ "your language model INSTEAD of the whole history. "
135
+ "This does not call a model itself — it selects what to send. "
136
+ "The budget is a ceiling, not a target: selection stops where "
137
+ "relevance runs out, often well below it. The response says "
138
+ "how many entries were left behind and why."
139
+ ),
140
+ "inputSchema": {
141
+ "type": "object",
142
+ "properties": {
143
+ "namespace": {"type": "string"},
144
+ "query": {"type": "string",
145
+ "description": "What you need context about."},
146
+ "token_budget": {"type": "integer", "default": 2000},
147
+ },
148
+ "required": ["namespace", "query"],
149
+ },
150
+ },
151
+ {
152
+ "name": "get_account",
153
+ "description": (
154
+ "Get an account and an API key. Requires an email address. "
155
+ "The key is returned ONCE and cannot be shown again — store it "
156
+ "immediately. Beta quotas are low by design; they are hard "
157
+ "stops, never overage billing."
158
+ ),
159
+ "inputSchema": {
160
+ "type": "object",
161
+ "properties": {
162
+ "email": {"type": "string"},
163
+ "traffic": {
164
+ "type": "string",
165
+ "description": "Optional. What your agent sends.",
166
+ },
167
+ },
168
+ "required": ["email"],
169
+ },
170
+ },
171
+ ]
172
+
173
+
174
+ def _nyckel() -> str:
175
+ return os.environ.get("CAP_SHIELD_API_KEY", "").strip()
176
+
177
+
178
+ def _anrop(vag: str, kropp: dict | None = None, metod: str = "POST",
179
+ kraver_nyckel: bool = True) -> dict:
180
+ """HTTP mot gatewayen. Använder urllib — inget extra beroende."""
181
+ import urllib.error
182
+ import urllib.request
183
+
184
+ huvuden = {"Content-Type": "application/json",
185
+ "User-Agent": f"cap-shield-mcp/{VERSION}"}
186
+ if kraver_nyckel:
187
+ n = _nyckel()
188
+ if not n:
189
+ return {"error": (
190
+ "No API key. Set CAP_SHIELD_API_KEY in the server's env, "
191
+ "or call get_account to obtain one. The measure_traffic "
192
+ "and list_packages tools work without a key.")}
193
+ huvuden["Authorization"] = f"Bearer {n}"
194
+
195
+ data = json.dumps(kropp).encode("utf-8") if kropp is not None else None
196
+ req = urllib.request.Request(f"{BAS}{vag}", data=data,
197
+ headers=huvuden, method=metod)
198
+ try:
199
+ with urllib.request.urlopen(req, timeout=60) as r:
200
+ return json.loads(r.read().decode("utf-8"))
201
+ except urllib.error.HTTPError as exc:
202
+ try:
203
+ return {"error": json.loads(exc.read().decode("utf-8"))}
204
+ except Exception:
205
+ return {"error": f"HTTP {exc.code}"}
206
+ except Exception as exc:
207
+ return {"error": f"Could not reach {BAS}: {exc}"}
208
+
209
+
210
+ def kor_verktyg(namn: str, arg: dict) -> dict:
211
+ if namn == "measure_traffic":
212
+ kropp = {"texts": arg.get("texts", []),
213
+ "dict_id": arg.get("dict_id", "finance")}
214
+ if arg.get("query"):
215
+ kropp["query"] = arg["query"]
216
+ return _anrop("/api/v1/try", kropp, kraver_nyckel=False)
217
+
218
+ if namn == "list_packages":
219
+ return _anrop("/api/v1/catalog/status", metod="GET",
220
+ kraver_nyckel=False)
221
+
222
+ if namn == "remember":
223
+ import uuid
224
+ return _anrop("/api/v1/memory/put", {
225
+ "namespace": arg["namespace"],
226
+ "item_id": arg.get("item_id") or uuid.uuid4().hex[:16],
227
+ "text": arg["text"]})
228
+
229
+ if namn == "assemble_context":
230
+ return _anrop("/api/v1/memory/assemble", {
231
+ "namespace": arg["namespace"], "query": arg["query"],
232
+ "token_budget": arg.get("token_budget", 2000)})
233
+
234
+ if namn == "get_account":
235
+ kropp = {"email": arg["email"]}
236
+ if arg.get("traffic"):
237
+ kropp["traffic"] = arg["traffic"]
238
+ return _anrop("/api/v1/beta-signup", kropp, kraver_nyckel=False)
239
+
240
+ return {"error": f"Unknown tool: {namn}"}
241
+
242
+
243
+ # ----------------------------------------------------------------------
244
+ # JSON-RPC över stdio
245
+ # ----------------------------------------------------------------------
246
+ def hantera(begaran: dict) -> dict | None:
247
+ """Ett meddelande in, ett svar ut. None för notifieringar."""
248
+ metod = begaran.get("method", "")
249
+ rid = begaran.get("id")
250
+
251
+ if metod == "initialize":
252
+ return _svar(rid, {
253
+ "protocolVersion": PROTOKOLL,
254
+ "capabilities": {"tools": {}},
255
+ "serverInfo": {"name": "cap-shield", "version": VERSION},
256
+ })
257
+
258
+ if metod == "notifications/initialized":
259
+ return None # notifiering, inget svar
260
+
261
+ if metod == "tools/list":
262
+ return _svar(rid, {"tools": VERKTYG})
263
+
264
+ if metod == "tools/call":
265
+ p = begaran.get("params", {})
266
+ try:
267
+ resultat = kor_verktyg(p.get("name", ""), p.get("arguments", {}))
268
+ except KeyError as exc:
269
+ resultat = {"error": f"Missing required argument: {exc}"}
270
+ except Exception as exc:
271
+ resultat = {"error": f"{type(exc).__name__}: {exc}"}
272
+ return _svar(rid, {"content": [
273
+ {"type": "text",
274
+ "text": json.dumps(resultat, ensure_ascii=False, indent=2)}]})
275
+
276
+ if rid is None:
277
+ return None # okänd notifiering — tig
278
+ return {"jsonrpc": "2.0", "id": rid,
279
+ "error": {"code": -32601, "message": f"Unknown method: {metod}"}}
280
+
281
+
282
+ def _svar(rid: Any, resultat: dict) -> dict:
283
+ return {"jsonrpc": "2.0", "id": rid, "result": resultat}
284
+
285
+
286
+ def main() -> None:
287
+ """Läs rad för rad från stdin, svara på stdout.
288
+
289
+ ALL LOGGNING TILL STDERR. Stdout är protokollkanalen — en enda
290
+ print() där bryter kommunikationen, och felet ser ut som att servern
291
+ hängt sig.
292
+ """
293
+ print(f"cap-shield MCP server, {len(VERKTYG)} tools, target {BAS}",
294
+ file=sys.stderr)
295
+
296
+ try:
297
+ for rad in sys.stdin:
298
+ rad = rad.strip()
299
+ if not rad:
300
+ continue
301
+ try:
302
+ begaran = json.loads(rad)
303
+ except json.JSONDecodeError:
304
+ continue
305
+ svar = hantera(begaran)
306
+ if svar is not None:
307
+ sys.stdout.write(json.dumps(svar, ensure_ascii=False) + "\n")
308
+ sys.stdout.flush()
309
+ except (KeyboardInterrupt, BrokenPipeError):
310
+ # En agent som stänger servern ska inte se ett stackspår i sin
311
+ # logg. Avslut är inte ett fel — det är hur en MCP-server dör.
312
+ pass
313
+
314
+
315
+ if __name__ == "__main__":
316
+ main()
@@ -34,7 +34,7 @@ import os
34
34
  from dataclasses import dataclass, field
35
35
  from typing import Any, Iterable
36
36
 
37
- __version__ = "0.3.0"
37
+ __version__ = "0.4.0"
38
38
  BAS = "https://cap-shield-robin.fly.dev"
39
39
  TIMEOUT = 30.0
40
40
 
@@ -35,7 +35,11 @@ path = "cap_shield.py"
35
35
  # cap_gain.py MÅSTE med. Utan den misslyckas import cap_gain tyst för
36
36
  # alla som installerar via pip, och räknaren finns bara för den som
37
37
  # byggde från källa — alltså ingen.
38
- only-include = ["cap_shield.py", "cap_gain.py"]
38
+ # cap_mcp.py MÅSTE med: den är MCP-servern, och det officiella
39
+ # registret verifierar installationsvägen mot PyPI. Utan den finns
40
+ # servern bara via curl, vilket registret inte accepterar — och
41
+ # användaren får två installationsvägar i stället för en.
42
+ only-include = ["cap_shield.py", "cap_gain.py", "cap_mcp.py"]
39
43
  sources = ["."]
40
44
 
41
45
  # KÄLLDISTRIBUTIONEN MÅSTE OCKSÅ BEGRÄNSAS.
@@ -47,5 +51,6 @@ sources = ["."]
47
51
  # Utan detta laddas dessutom gatewayen, korpusen och mätverktygen upp
48
52
  # publikt, vilket är en helt annan sorts problem än storleken.
49
53
  [tool.hatch.build.targets.sdist]
50
- only-include = ["cap_shield.py", "cap_gain.py", "README_SDK.md",
54
+ only-include = ["cap_shield.py", "cap_gain.py", "cap_mcp.py",
55
+ "README_SDK.md",
51
56
  "pyproject.toml"]
File without changes