contextgate-core 0.6.0__py3-none-any.whl
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.
- contextgate_core/__init__.py +48 -0
- contextgate_core/ab_compare.py +566 -0
- contextgate_core/bridge.py +345 -0
- contextgate_core/cli.py +560 -0
- contextgate_core/data_contracts.py +89 -0
- contextgate_core/downstream.py +165 -0
- contextgate_core/eval_retrieval.py +173 -0
- contextgate_core/gate.py +430 -0
- contextgate_core/gate_bench.py +148 -0
- contextgate_core/gateway.py +442 -0
- contextgate_core/hook.py +116 -0
- contextgate_core/ledger.py +228 -0
- contextgate_core/mcp_server.py +291 -0
- contextgate_core/pipeline.py +1756 -0
- contextgate_core/protocol.py +112 -0
- contextgate_core/py.typed +0 -0
- contextgate_core/registry.py +109 -0
- contextgate_core/repo_indexer.py +1128 -0
- contextgate_core/token_audit.py +242 -0
- contextgate_core-0.6.0.dist-info/METADATA +426 -0
- contextgate_core-0.6.0.dist-info/RECORD +25 -0
- contextgate_core-0.6.0.dist-info/WHEEL +5 -0
- contextgate_core-0.6.0.dist-info/entry_points.txt +5 -0
- contextgate_core-0.6.0.dist-info/licenses/LICENSE +21 -0
- contextgate_core-0.6.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Persistent savings ledger (SQLite, stdlib). One row per proxied request. Stores COUNTS ONLY: never prompt text, response
|
|
3
|
+
text, headers or credentials.
|
|
4
|
+
|
|
5
|
+
Honest accounting:
|
|
6
|
+
* saved_tokens = estimate(original request) - estimate(forwarded request), same estimator on both sides.
|
|
7
|
+
* The provider reports exact `usage.prompt_tokens` for what was FORWARDED. The ratio actual/estimate calibrates the
|
|
8
|
+
estimator, and calibrated savings = estimated savings x ratio. Both numbers are reported.
|
|
9
|
+
* USD uses a price table YOU supply (--prices FILE); nothing is hard-coded. It ignores cache discounts: an estimate.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import sqlite3
|
|
19
|
+
import statistics
|
|
20
|
+
import sys
|
|
21
|
+
import threading
|
|
22
|
+
import time
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
SCHEMA = 1
|
|
26
|
+
DEFAULT_PATH = os.environ.get("SMARTY_LEDGER") or os.path.join(os.path.expanduser("~"), ".smarty", "ledger.db")
|
|
27
|
+
AUDIT_PASS = 80
|
|
28
|
+
COLS = ("ts", "route", "host", "model", "profile", "stream", "applied", "raw_tokens", "fwd_tokens", "up_prompt_tokens",
|
|
29
|
+
"up_completion_tokens", "gate_ms", "upstream_ms", "status", "fallbacks", "protected_ok", "error", "audit_score",
|
|
30
|
+
"neg_ok", "entity_ok", "api", "up_cache_read_tokens", "up_cache_write_tokens")
|
|
31
|
+
_ADDED_LATER = {"api": "TEXT", "up_cache_read_tokens": "INTEGER", "up_cache_write_tokens": "INTEGER"} # migrated into old ledgers
|
|
32
|
+
DEFAULT_CACHE_MULT = {"read": 0.10, "write": 1.25} # multipliers on the input price: ASSUMPTIONS, override per model in --prices
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Ledger:
|
|
36
|
+
def __init__(self, path: str = DEFAULT_PATH) -> None:
|
|
37
|
+
self.path = path
|
|
38
|
+
if path != ":memory:":
|
|
39
|
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
|
40
|
+
self._lock = threading.Lock()
|
|
41
|
+
self._db = sqlite3.connect(path, check_same_thread=False)
|
|
42
|
+
self._db.row_factory = sqlite3.Row
|
|
43
|
+
with self._lock:
|
|
44
|
+
if path != ":memory:": # WAL: cheap commits off the request path, and `stats` can read while the gateway writes
|
|
45
|
+
self._db.execute("PRAGMA journal_mode=WAL")
|
|
46
|
+
self._db.execute("PRAGMA synchronous=NORMAL")
|
|
47
|
+
self._db.execute("CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT)")
|
|
48
|
+
self._db.execute(
|
|
49
|
+
"CREATE TABLE IF NOT EXISTS requests(id INTEGER PRIMARY KEY, ts REAL, route TEXT, host TEXT, model TEXT, "
|
|
50
|
+
"profile TEXT, stream INTEGER, applied INTEGER, raw_tokens INTEGER, fwd_tokens INTEGER, "
|
|
51
|
+
"up_prompt_tokens INTEGER, up_completion_tokens INTEGER, gate_ms REAL, upstream_ms REAL, status INTEGER, "
|
|
52
|
+
"fallbacks INTEGER, protected_ok INTEGER, error TEXT, audit_score INTEGER, neg_ok INTEGER, entity_ok INTEGER, "
|
|
53
|
+
"api TEXT, up_cache_read_tokens INTEGER, up_cache_write_tokens INTEGER)")
|
|
54
|
+
have = {r[1] for r in self._db.execute("PRAGMA table_info(requests)")}
|
|
55
|
+
for col, typ in _ADDED_LATER.items(): # migrate ledgers created before these columns existed
|
|
56
|
+
if col not in have:
|
|
57
|
+
self._db.execute(f"ALTER TABLE requests ADD COLUMN {col} {typ}")
|
|
58
|
+
self._db.execute("CREATE INDEX IF NOT EXISTS requests_ts ON requests(ts)")
|
|
59
|
+
self._db.execute("INSERT OR REPLACE INTO meta VALUES('schema', ?)", (str(SCHEMA),))
|
|
60
|
+
self._db.commit()
|
|
61
|
+
|
|
62
|
+
def record(self, **row: Any) -> None:
|
|
63
|
+
vals = {c: row.get(c) for c in COLS}
|
|
64
|
+
vals["ts"] = vals["ts"] if vals["ts"] is not None else time.time()
|
|
65
|
+
for b in ("stream", "applied", "protected_ok", "neg_ok", "entity_ok"):
|
|
66
|
+
if vals[b] is not None:
|
|
67
|
+
vals[b] = int(bool(vals[b]))
|
|
68
|
+
vals["error"] = (vals["error"] or "")[:200] or None # a class name / short reason, never content
|
|
69
|
+
with self._lock:
|
|
70
|
+
self._db.execute(f"INSERT INTO requests({','.join(COLS)}) VALUES({','.join('?' * len(COLS))})", [vals[c] for c in COLS])
|
|
71
|
+
self._db.commit()
|
|
72
|
+
|
|
73
|
+
def rows(self, since: float | None = None) -> list[sqlite3.Row]:
|
|
74
|
+
with self._lock:
|
|
75
|
+
if since is None:
|
|
76
|
+
return self._db.execute("SELECT * FROM requests ORDER BY ts").fetchall()
|
|
77
|
+
return self._db.execute("SELECT * FROM requests WHERE ts >= ? ORDER BY ts", (since,)).fetchall()
|
|
78
|
+
|
|
79
|
+
def close(self) -> None:
|
|
80
|
+
with self._lock:
|
|
81
|
+
self._db.close()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _price(prices: dict | None, model: str | None) -> dict | None:
|
|
85
|
+
if not prices:
|
|
86
|
+
return None
|
|
87
|
+
return prices.get(model or "") or prices.get("default")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _pct(vals: list[float], q: float) -> float:
|
|
91
|
+
return sorted(vals)[max(0, min(len(vals) - 1, int(round(q * (len(vals) - 1)))))] if vals else 0.0
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def summarize(rows: list[Any], prices: dict | None = None) -> dict[str, Any]:
|
|
95
|
+
n = len(rows)
|
|
96
|
+
if not n:
|
|
97
|
+
return {"requests": 0}
|
|
98
|
+
raw = sum(r["raw_tokens"] or 0 for r in rows)
|
|
99
|
+
fwd = sum(r["fwd_tokens"] or 0 for r in rows)
|
|
100
|
+
with_usage = [r for r in rows if r["up_prompt_tokens"] and r["fwd_tokens"]]
|
|
101
|
+
ratio = (sum(r["up_prompt_tokens"] for r in with_usage) / sum(r["fwd_tokens"] for r in with_usage)) if with_usage else None
|
|
102
|
+
saved = raw - fwd
|
|
103
|
+
out: dict[str, Any] = {
|
|
104
|
+
"requests": n, "gated": sum(1 for r in rows if r["applied"]), "passthrough": sum(1 for r in rows if not r["applied"]),
|
|
105
|
+
"est_tokens_original": raw, "est_tokens_forwarded": fwd, "est_tokens_saved": saved,
|
|
106
|
+
"est_saved_pct": round(100 * saved / raw, 2) if raw else 0.0,
|
|
107
|
+
"calibration_ratio": round(ratio, 3) if ratio else None, "calibration_samples": len(with_usage),
|
|
108
|
+
"calibrated_tokens_saved": round(saved * ratio) if ratio else None,
|
|
109
|
+
"upstream_prompt_tokens": sum(r["up_prompt_tokens"] or 0 for r in rows),
|
|
110
|
+
"upstream_completion_tokens": sum(r["up_completion_tokens"] or 0 for r in rows),
|
|
111
|
+
"gate_ms_mean": round(statistics.mean(r["gate_ms"] or 0 for r in rows), 2),
|
|
112
|
+
"gate_ms_p95": round(_pct([r["gate_ms"] or 0 for r in rows], 0.95), 2),
|
|
113
|
+
"upstream_ms_mean": round(statistics.mean(r["upstream_ms"] or 0 for r in rows), 1),
|
|
114
|
+
"fallback_to_original": sum(r["fallbacks"] or 0 for r in rows),
|
|
115
|
+
"protected_ok_rate": round(sum(1 for r in rows if r["protected_ok"] in (None, 1)) / n, 4),
|
|
116
|
+
"errors": sum(1 for r in rows if r["error"]), "upstream_errors": sum(1 for r in rows if (r["status"] or 0) >= 400),
|
|
117
|
+
}
|
|
118
|
+
aud = [r for r in rows if r["audit_score"] is not None]
|
|
119
|
+
if aud:
|
|
120
|
+
out["audited"] = len(aud)
|
|
121
|
+
out["audit_mean_score"] = round(statistics.mean(r["audit_score"] for r in aud), 1)
|
|
122
|
+
out["audit_pass_rate"] = round(sum(1 for r in aud if r["audit_score"] >= AUDIT_PASS) / len(aud), 4)
|
|
123
|
+
# a check that did not apply (None) is not a pass: rates are over the responses where the check actually ran
|
|
124
|
+
for key, col in (("negation_pass_rate", "neg_ok"), ("entity_pass_rate", "entity_ok")):
|
|
125
|
+
ran = [r for r in aud if r[col] is not None]
|
|
126
|
+
out[key] = round(sum(1 for r in ran if r[col] == 1) / len(ran), 4) if ran else None
|
|
127
|
+
out[key.replace("pass_rate", "checked")] = len(ran)
|
|
128
|
+
cr = sum(r["up_cache_read_tokens"] or 0 for r in rows)
|
|
129
|
+
cw = sum(r["up_cache_write_tokens"] or 0 for r in rows)
|
|
130
|
+
if cr or cw:
|
|
131
|
+
total_prompt = out["upstream_prompt_tokens"]
|
|
132
|
+
out.update({"upstream_cache_read_tokens": cr, "upstream_cache_write_tokens": cw,
|
|
133
|
+
"cache_read_share": round(cr / total_prompt, 4) if total_prompt else None})
|
|
134
|
+
if prices:
|
|
135
|
+
usd_saved = usd_spend = 0.0
|
|
136
|
+
priced = unpriced = 0
|
|
137
|
+
for r in rows:
|
|
138
|
+
p = _price(prices, r["model"])
|
|
139
|
+
if not p:
|
|
140
|
+
unpriced += 1
|
|
141
|
+
continue
|
|
142
|
+
priced += 1
|
|
143
|
+
k = ratio or 1.0
|
|
144
|
+
prompt = r["up_prompt_tokens"] or 0
|
|
145
|
+
eff = 1.0 # saved tokens are assumed to have the cache mix this request actually had
|
|
146
|
+
if prompt and (r["up_cache_read_tokens"] or r["up_cache_write_tokens"]):
|
|
147
|
+
rd, wr = r["up_cache_read_tokens"] or 0, r["up_cache_write_tokens"] or 0
|
|
148
|
+
eff = ((prompt - rd - wr) + rd * p.get("cache_read_mult", DEFAULT_CACHE_MULT["read"])
|
|
149
|
+
+ wr * p.get("cache_write_mult", DEFAULT_CACHE_MULT["write"])) / prompt
|
|
150
|
+
usd_saved += ((r["raw_tokens"] or 0) - (r["fwd_tokens"] or 0)) * k * eff / 1e6 * p["input_per_mtok"]
|
|
151
|
+
usd_spend += (r["up_prompt_tokens"] or 0) / 1e6 * p["input_per_mtok"] + \
|
|
152
|
+
(r["up_completion_tokens"] or 0) / 1e6 * p.get("output_per_mtok", 0)
|
|
153
|
+
out.update({"usd_input_saved_est": round(usd_saved, 6), "usd_spend_observed": round(usd_spend, 6),
|
|
154
|
+
"usd_priced_requests": priced, "usd_unpriced_requests": unpriced})
|
|
155
|
+
by: dict[str, dict] = {}
|
|
156
|
+
for key in ("model", "profile", "api"):
|
|
157
|
+
grp: dict[str, list] = {}
|
|
158
|
+
for r in rows:
|
|
159
|
+
grp.setdefault(r[key] or "?", []).append(r)
|
|
160
|
+
by[key] = {k: {"requests": len(v), "est_saved_pct": round(100 * (sum(x["raw_tokens"] or 0 for x in v) - sum(x["fwd_tokens"] or 0 for x in v))
|
|
161
|
+
/ max(1, sum(x["raw_tokens"] or 0 for x in v)), 2)} for k, v in grp.items()}
|
|
162
|
+
out["by_model"], out["by_profile"], out["by_api"] = by["model"], by["profile"], by["api"]
|
|
163
|
+
return out
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def format_summary(s: dict[str, Any]) -> str:
|
|
167
|
+
if not s.get("requests"):
|
|
168
|
+
return "no requests recorded yet"
|
|
169
|
+
L = [f"requests: {s['requests']} (gated {s['gated']}, passed through unchanged {s['passthrough']})",
|
|
170
|
+
f"tokens (estimated): {s['est_tokens_original']} original -> {s['est_tokens_forwarded']} forwarded = "
|
|
171
|
+
f"{s['est_tokens_saved']} saved ({s['est_saved_pct']}%)"]
|
|
172
|
+
if s.get("calibration_ratio"):
|
|
173
|
+
L.append(f"calibration vs provider usage: x{s['calibration_ratio']} over {s['calibration_samples']} requests -> "
|
|
174
|
+
f"~{s['calibrated_tokens_saved']} provider tokens saved")
|
|
175
|
+
else:
|
|
176
|
+
L.append("calibration: no upstream usage seen yet (savings above are estimator-only)")
|
|
177
|
+
if s.get("cache_read_share") is not None:
|
|
178
|
+
L.append(f"provider cache: {100 * s['cache_read_share']:.1f}% of prompt tokens were cache reads "
|
|
179
|
+
f"({s['upstream_cache_read_tokens']} read, {s['upstream_cache_write_tokens']} written)")
|
|
180
|
+
if "usd_input_saved_est" in s:
|
|
181
|
+
L.append(f"USD (your price table; estimate, saved tokens priced at the cache mix actually observed): ~${s['usd_input_saved_est']:.6f} "
|
|
182
|
+
f"input saved of ${s['usd_spend_observed']:.6f} observed spend ({s['usd_priced_requests']} priced, {s['usd_unpriced_requests']} unpriced requests; "
|
|
183
|
+
f"cache read/write multipliers assumed x{DEFAULT_CACHE_MULT['read']}/x{DEFAULT_CACHE_MULT['write']} unless set per model)")
|
|
184
|
+
L.append(f"gate overhead: {s['gate_ms_mean']} ms mean, {s['gate_ms_p95']} ms p95 (upstream mean {s['upstream_ms_mean']} ms)")
|
|
185
|
+
L.append(f"safety: protected-span verification fallbacks {s['fallback_to_original']}, protected_ok {100 * s['protected_ok_rate']:.2f}%, "
|
|
186
|
+
f"internal errors {s['errors']}, upstream errors {s['upstream_errors']}")
|
|
187
|
+
if "audit_mean_score" in s:
|
|
188
|
+
fmt = lambda v, n: f"{100 * v:.1f}% of {n}" if v is not None else "not applicable" # noqa: E731
|
|
189
|
+
L.append(f"post-audit ({s['audited']} responses): mean {s['audit_mean_score']}, pass rate {100 * s['audit_pass_rate']:.1f}%; "
|
|
190
|
+
f"negation check {fmt(s['negation_pass_rate'], s['negation_checked'])}, entity check "
|
|
191
|
+
f"{fmt(s['entity_pass_rate'], s['entity_checked'])}")
|
|
192
|
+
return "\n".join(L)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def parse_since(text: str | None) -> float | None:
|
|
196
|
+
if not text:
|
|
197
|
+
return None
|
|
198
|
+
m = re.fullmatch(r"(\d+)\s*([smhd])", text.strip().lower())
|
|
199
|
+
if not m:
|
|
200
|
+
raise ValueError("--since must look like 30m, 24h or 7d")
|
|
201
|
+
return time.time() - int(m.group(1)) * {"s": 1, "m": 60, "h": 3600, "d": 86400}[m.group(2)]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def main(argv: list[str] | None = None) -> int:
|
|
205
|
+
ap = argparse.ArgumentParser(prog="stats", description="Savings ledger report")
|
|
206
|
+
ap.add_argument("--ledger", default=DEFAULT_PATH)
|
|
207
|
+
ap.add_argument("--since", help="e.g. 24h, 7d")
|
|
208
|
+
ap.add_argument("--prices", help='JSON price table: {"model": {"input_per_mtok": 3, "output_per_mtok": 15}, "default": {...}}')
|
|
209
|
+
ap.add_argument("--json", action="store_true")
|
|
210
|
+
a = ap.parse_args(argv)
|
|
211
|
+
try:
|
|
212
|
+
since = parse_since(a.since)
|
|
213
|
+
prices = json.load(open(a.prices)) if a.prices else None
|
|
214
|
+
if not os.path.exists(a.ledger):
|
|
215
|
+
print(f"error: no ledger at {a.ledger} (run `serve` first)", file=sys.stderr)
|
|
216
|
+
return 2
|
|
217
|
+
except (ValueError, OSError) as exc:
|
|
218
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
219
|
+
return 2
|
|
220
|
+
led = Ledger(a.ledger)
|
|
221
|
+
s = summarize(led.rows(since), prices)
|
|
222
|
+
led.close()
|
|
223
|
+
print(json.dumps(s, indent=2) if a.json else format_summary(s))
|
|
224
|
+
return 0
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
if __name__ == "__main__":
|
|
228
|
+
sys.exit(main())
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NLP-Smarty MCP server (stdio, newline-delimited JSON-RPC 2.0). Zero third-party deps.
|
|
3
|
+
|
|
4
|
+
Exposes the deterministic, zero-LLM optimizer to any MCP client (Claude Code, Cursor, Copilot...).
|
|
5
|
+
Register: claude mcp add nlp-smarty -- ./NLP-start/bin/python /abs/path/mcp_server.py
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import traceback
|
|
15
|
+
from typing import Any, Callable
|
|
16
|
+
|
|
17
|
+
from .bridge import _build_raw_request
|
|
18
|
+
from .pipeline import _compress_tool_schema, _prune_external_context_mmr, audit_agent_response, optimize
|
|
19
|
+
from . import repo_indexer as ri
|
|
20
|
+
from .protocol import ProtocolError, __version__, validate_request
|
|
21
|
+
|
|
22
|
+
SERVER_INFO = {"name": "nlp-smarty", "version": __version__}
|
|
23
|
+
SUPPORTED_PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05")
|
|
24
|
+
|
|
25
|
+
# Sent once per session in the initialize result; the client adds it to the agent's context. Keep it short: it is paid
|
|
26
|
+
# on every session. The "nlp-smarty index:" prefix is a marker that ab_compare.py uses to confirm delivery.
|
|
27
|
+
INSTRUCTIONS = (
|
|
28
|
+
"nlp-smarty index: this repo's symbols are indexed with exact line spans. To locate code, call smarty_get_context "
|
|
29
|
+
"(describe the task) or smarty_find_symbol (a name); for usages call smarty_find_references; then smarty_get_slice "
|
|
30
|
+
"to read only the lines you need. A <retrieved_context> block may already be in your prompt; use these tools for "
|
|
31
|
+
"what it does not cover. Results are lexical and can be incomplete: fall back to grep if they come back empty."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def server_instructions() -> str | None:
|
|
36
|
+
"""OFF by default: in a 5-run live test the agent never used the tools even with these instructions (it never loaded
|
|
37
|
+
the deferred tools), so they only cost ~100 tokens per session. Opt in with SMARTY_MCP_INSTRUCTIONS=on|1|true."""
|
|
38
|
+
if os.environ.get("SMARTY_MCP_INSTRUCTIONS", "off").strip().lower() in ("on", "1", "true", "yes"):
|
|
39
|
+
return INSTRUCTIONS
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
_PIPELINE_PROPS: dict[str, Any] = {
|
|
43
|
+
"text": {"type": "string", "description": "Raw prompt / task text."},
|
|
44
|
+
"context_chunks": {"type": "array", "items": {"type": "string"}, "description": "RAG chunks to prune via MMR."},
|
|
45
|
+
"conversation_history": {
|
|
46
|
+
"type": "array",
|
|
47
|
+
"items": {"type": "object", "properties": {"role": {"type": "string"}, "content": {"type": "string"}},
|
|
48
|
+
"required": ["role", "content"]},
|
|
49
|
+
},
|
|
50
|
+
"compression_intensity": {"type": "string", "enum": ["AUTO", "LIGHT", "MEDIUM", "AGGRESSIVE"]},
|
|
51
|
+
"max_total_tokens": {"type": "integer", "minimum": 0},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _text_result(obj: Any, is_error: bool = False) -> dict[str, Any]:
|
|
56
|
+
return {"content": [{"type": "text", "text": json.dumps(obj, indent=2)}], "isError": is_error}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _tool_optimize(args: dict[str, Any]) -> Any:
|
|
60
|
+
validate_request({"command": "optimize", **args})
|
|
61
|
+
compiled = optimize(_build_raw_request(args), few_shot_k=int(args.get("few_shot_k", 2)))
|
|
62
|
+
return {
|
|
63
|
+
"status": compiled.status,
|
|
64
|
+
"clarification_request": compiled.clarification_request,
|
|
65
|
+
"payload": compiled.payload,
|
|
66
|
+
"trace": dataclasses.asdict(compiled.trace),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _tool_audit(args: dict[str, Any]) -> Any:
|
|
71
|
+
validate_request({"command": "audit_pair", **args})
|
|
72
|
+
resp = args.get("response")
|
|
73
|
+
if not isinstance(resp, str):
|
|
74
|
+
raise ProtocolError("INVALID_REQUEST", "'response' must be a string")
|
|
75
|
+
compiled = optimize(_build_raw_request(args))
|
|
76
|
+
return audit_agent_response(resp, compiled.trace)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _tool_compress_context(args: dict[str, Any]) -> Any:
|
|
80
|
+
query, chunks = args.get("query"), args.get("chunks")
|
|
81
|
+
if not isinstance(query, str) or not isinstance(chunks, list) or not all(isinstance(c, str) for c in chunks):
|
|
82
|
+
raise ProtocolError("INVALID_REQUEST", "'query' (string) and 'chunks' (list of strings) are required")
|
|
83
|
+
text, kept = _prune_external_context_mmr(
|
|
84
|
+
query, chunks, int(args.get("context_budget", 160)), int(args.get("top_k", 3)))
|
|
85
|
+
return {"context": text, "kept_indices": kept}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _tool_compress_schema(args: dict[str, Any]) -> Any:
|
|
89
|
+
schema = args.get("schema")
|
|
90
|
+
if not isinstance(schema, (dict, str)):
|
|
91
|
+
raise ProtocolError("INVALID_REQUEST", "'schema' must be a JSON object or string")
|
|
92
|
+
compressed, saved = _compress_tool_schema(schema)
|
|
93
|
+
return {"compressed_schema": compressed, "tokens_saved": saved}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
TOOLS: dict[str, tuple[dict[str, Any], Callable[[dict[str, Any]], Any]]] = {
|
|
97
|
+
"smarty_optimize": ({
|
|
98
|
+
"name": "smarty_optimize",
|
|
99
|
+
"description": "Deterministically compress/normalize a prompt (+context, history, tools) into a token-budgeted compiled payload with an optimization trace. Zero-LLM.",
|
|
100
|
+
"inputSchema": {"type": "object", "properties": _PIPELINE_PROPS, "required": ["text"]},
|
|
101
|
+
}, _tool_optimize),
|
|
102
|
+
"smarty_audit_response": ({
|
|
103
|
+
"name": "smarty_audit_response",
|
|
104
|
+
"description": "Score (0-100) an LLM/agent response against the original prompt for format compliance, entity fidelity and negation adherence.",
|
|
105
|
+
"inputSchema": {"type": "object", "properties": {**_PIPELINE_PROPS, "response": {"type": "string"}},
|
|
106
|
+
"required": ["text", "response"]},
|
|
107
|
+
}, _tool_audit),
|
|
108
|
+
"smarty_compress_context": ({
|
|
109
|
+
"name": "smarty_compress_context",
|
|
110
|
+
"description": "Select the most query-relevant, non-redundant chunks (BM25+TF-IDF+MMR) within a token budget.",
|
|
111
|
+
"inputSchema": {"type": "object", "properties": {
|
|
112
|
+
"query": {"type": "string"}, "chunks": {"type": "array", "items": {"type": "string"}},
|
|
113
|
+
"context_budget": {"type": "integer", "minimum": 0}, "top_k": {"type": "integer", "minimum": 1}},
|
|
114
|
+
"required": ["query", "chunks"]},
|
|
115
|
+
}, _tool_compress_context),
|
|
116
|
+
"smarty_compress_tool_schema": ({
|
|
117
|
+
"name": "smarty_compress_tool_schema",
|
|
118
|
+
"description": "Compress an OpenAI/MCP JSON tool schema, stripping verbose prose while preserving structure; returns tokens saved.",
|
|
119
|
+
"inputSchema": {"type": "object", "properties": {"schema": {"type": ["object", "string"]}},
|
|
120
|
+
"required": ["schema"]},
|
|
121
|
+
}, _tool_compress_schema),
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ── repo-intelligence tools (root is fixed server-side: SMARTY_ROOT or cwd; never agent-supplied) ──
|
|
126
|
+
def _root() -> str:
|
|
127
|
+
return os.path.abspath(os.environ.get("SMARTY_ROOT") or os.getcwd())
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _int(args: dict[str, Any], key: str, default: int, lo: int, hi: int) -> int:
|
|
131
|
+
v = args.get(key, default)
|
|
132
|
+
if not isinstance(v, int) or isinstance(v, bool) or not lo <= v <= hi:
|
|
133
|
+
raise ProtocolError("INVALID_REQUEST", f"'{key}' must be an integer in [{lo}, {hi}]")
|
|
134
|
+
return v
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _tool_get_context(args: dict[str, Any]) -> Any:
|
|
138
|
+
q = args.get("query")
|
|
139
|
+
if not isinstance(q, str) or not q.strip():
|
|
140
|
+
raise ProtocolError("INVALID_REQUEST", "'query' must be a non-empty string")
|
|
141
|
+
out = ri.build_capsule(_root(), q, token_budget=_int(args, "token_budget", 450, 100, 4000),
|
|
142
|
+
k=_int(args, "k", 5, 1, 15))
|
|
143
|
+
return {"capsule": out["capsule"], "tokens": out["tokens"], "confidence": out["confidence"],
|
|
144
|
+
"reason": out["reason"],
|
|
145
|
+
"symbols": [f"{h['path']}:L{h['start']}-{h['end']} {h['name']}" for h in out["hits"]]}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _tool_repo_map(args: dict[str, Any]) -> Any:
|
|
149
|
+
return {"repo_map": ri.repo_map(_root(), _int(args, "token_budget", 800, 100, 8000))}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _tool_find_symbol(args: dict[str, Any]) -> Any:
|
|
153
|
+
n = args.get("name")
|
|
154
|
+
if not isinstance(n, str) or not n.strip():
|
|
155
|
+
raise ProtocolError("INVALID_REQUEST", "'name' must be a non-empty string")
|
|
156
|
+
return {"matches": ri.find_symbol(_root(), n, _int(args, "limit", 10, 1, 50))}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _tool_find_references(args: dict[str, Any]) -> Any:
|
|
160
|
+
n = args.get("name")
|
|
161
|
+
if not isinstance(n, str) or not n.strip():
|
|
162
|
+
raise ProtocolError("INVALID_REQUEST", "'name' must be a non-empty string")
|
|
163
|
+
inc = args.get("include_tests", True)
|
|
164
|
+
if not isinstance(inc, bool):
|
|
165
|
+
raise ProtocolError("INVALID_REQUEST", "'include_tests' must be a boolean")
|
|
166
|
+
try:
|
|
167
|
+
out = ri.find_references(_root(), n, _int(args, "limit", 40, 1, 200), _int(args, "token_budget", 700, 100, 4000), inc)
|
|
168
|
+
except ValueError as exc:
|
|
169
|
+
raise ProtocolError("INVALID_REQUEST", str(exc))
|
|
170
|
+
return {"text": out["text"], "counts": out["counts"], "truncated": out["truncated"]}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _tool_get_slice(args: dict[str, Any]) -> Any:
|
|
174
|
+
path = args.get("path")
|
|
175
|
+
if not isinstance(path, str) or not path:
|
|
176
|
+
raise ProtocolError("INVALID_REQUEST", "'path' must be a non-empty string")
|
|
177
|
+
start, end = _int(args, "start", 1, 1, 10**7), _int(args, "end", 1, 1, 10**7)
|
|
178
|
+
if end < start or end - start > 400:
|
|
179
|
+
raise ProtocolError("INVALID_REQUEST", "need start <= end and at most 400 lines")
|
|
180
|
+
try:
|
|
181
|
+
return ri.get_slice(_root(), path, start, end, context=_int(args, "context", 0, 0, 50))
|
|
182
|
+
except (ValueError, OSError) as exc:
|
|
183
|
+
raise ProtocolError("INVALID_REQUEST", str(exc))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
_obj = lambda props, req: {"type": "object", "properties": props, "required": req} # noqa: E731
|
|
187
|
+
TOOLS.update({
|
|
188
|
+
"smarty_get_context": ({
|
|
189
|
+
"name": "smarty_get_context",
|
|
190
|
+
"description": "Budgeted code slices (file:Lstart-Lend) most relevant to a task, from the local index. Use before grepping/reading files.",
|
|
191
|
+
"inputSchema": _obj({"query": {"type": "string"}, "token_budget": {"type": "integer"}, "k": {"type": "integer"}},
|
|
192
|
+
["query"]),
|
|
193
|
+
}, _tool_get_context),
|
|
194
|
+
"smarty_repo_map": ({
|
|
195
|
+
"name": "smarty_repo_map",
|
|
196
|
+
"description": "Compact map of files and top-level symbols with line spans; modified files first.",
|
|
197
|
+
"inputSchema": _obj({"token_budget": {"type": "integer"}}, []),
|
|
198
|
+
}, _tool_repo_map),
|
|
199
|
+
"smarty_find_symbol": ({
|
|
200
|
+
"name": "smarty_find_symbol",
|
|
201
|
+
"description": "Locate a symbol by name (exact, prefix, or Class.method suffix); returns path and line span.",
|
|
202
|
+
"inputSchema": _obj({"name": {"type": "string"}, "limit": {"type": "integer"}}, ["name"]),
|
|
203
|
+
}, _tool_find_symbol),
|
|
204
|
+
"smarty_find_references": ({
|
|
205
|
+
"name": "smarty_find_references",
|
|
206
|
+
"description": "Where a symbol is used: definitions, then callers, then other mentions as file:line, ranked and "
|
|
207
|
+
"token-budgeted. Use instead of grep to find usages.",
|
|
208
|
+
"inputSchema": _obj({"name": {"type": "string"}, "limit": {"type": "integer"}, "token_budget": {"type": "integer"},
|
|
209
|
+
"include_tests": {"type": "boolean"}}, ["name"]),
|
|
210
|
+
}, _tool_find_references),
|
|
211
|
+
"smarty_get_slice": ({
|
|
212
|
+
"name": "smarty_get_slice",
|
|
213
|
+
"description": "Numbered lines start..end (max 400) of a workspace file; secrets redacted.",
|
|
214
|
+
"inputSchema": _obj({"path": {"type": "string"}, "start": {"type": "integer"}, "end": {"type": "integer"},
|
|
215
|
+
"context": {"type": "integer"}}, ["path", "start", "end"]),
|
|
216
|
+
}, _tool_get_slice),
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
RESOURCES = [{"uri": "smarty://repo_map", "name": "repo_map", "mimeType": "text/markdown",
|
|
220
|
+
"description": "Compact repo symbol map with line spans."}]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def handle_message(msg: Any) -> dict[str, Any] | None:
|
|
224
|
+
"""Return a JSON-RPC response, or None for notifications."""
|
|
225
|
+
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
|
|
226
|
+
return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid Request"}}
|
|
227
|
+
method, mid, params = msg.get("method"), msg.get("id"), msg.get("params") or {}
|
|
228
|
+
is_notification = "id" not in msg
|
|
229
|
+
|
|
230
|
+
def ok(result: Any) -> dict[str, Any]:
|
|
231
|
+
return {"jsonrpc": "2.0", "id": mid, "result": result}
|
|
232
|
+
|
|
233
|
+
def err(code: int, message: str) -> dict[str, Any]:
|
|
234
|
+
return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}}
|
|
235
|
+
|
|
236
|
+
if is_notification:
|
|
237
|
+
return None
|
|
238
|
+
if method == "initialize":
|
|
239
|
+
requested = params.get("protocolVersion")
|
|
240
|
+
version = requested if requested in SUPPORTED_PROTOCOLS else SUPPORTED_PROTOCOLS[0]
|
|
241
|
+
result: dict[str, Any] = {"protocolVersion": version,
|
|
242
|
+
"capabilities": {"tools": {"listChanged": False}, "resources": {}},
|
|
243
|
+
"serverInfo": SERVER_INFO}
|
|
244
|
+
instructions = server_instructions()
|
|
245
|
+
if instructions:
|
|
246
|
+
result["instructions"] = instructions
|
|
247
|
+
return ok(result)
|
|
248
|
+
if method == "ping":
|
|
249
|
+
return ok({})
|
|
250
|
+
if method == "resources/list":
|
|
251
|
+
return ok({"resources": RESOURCES})
|
|
252
|
+
if method == "resources/read":
|
|
253
|
+
if params.get("uri") != "smarty://repo_map":
|
|
254
|
+
return err(-32002, f"Unknown resource: {params.get('uri')}")
|
|
255
|
+
return ok({"contents": [{"uri": "smarty://repo_map", "mimeType": "text/markdown",
|
|
256
|
+
"text": ri.repo_map(_root(), 1200)}]})
|
|
257
|
+
if method == "tools/list":
|
|
258
|
+
return ok({"tools": [t[0] for t in TOOLS.values()]})
|
|
259
|
+
if method == "tools/call":
|
|
260
|
+
name = params.get("name")
|
|
261
|
+
if name not in TOOLS:
|
|
262
|
+
return err(-32602, f"Unknown tool: {name}")
|
|
263
|
+
args = params.get("arguments") or {}
|
|
264
|
+
if not isinstance(args, dict):
|
|
265
|
+
return err(-32602, "arguments must be an object")
|
|
266
|
+
try:
|
|
267
|
+
return ok(_text_result(TOOLS[name][1](args)))
|
|
268
|
+
except ProtocolError as exc:
|
|
269
|
+
return ok(_text_result({"error_code": exc.code, "error": exc.message}, is_error=True))
|
|
270
|
+
except Exception as exc: # tool failures are reported in-band per MCP spec
|
|
271
|
+
sys.stderr.write(f"[NLP-Smarty MCP] {exc}\n{traceback.format_exc()}\n")
|
|
272
|
+
return ok(_text_result({"error_code": "INTERNAL_ERROR", "error": str(exc)}, is_error=True))
|
|
273
|
+
return err(-32601, f"Method not found: {method}")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def main() -> None:
|
|
277
|
+
for line in sys.stdin:
|
|
278
|
+
line = line.strip()
|
|
279
|
+
if not line:
|
|
280
|
+
continue
|
|
281
|
+
try:
|
|
282
|
+
resp = handle_message(json.loads(line))
|
|
283
|
+
except json.JSONDecodeError:
|
|
284
|
+
resp = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
|
|
285
|
+
if resp is not None:
|
|
286
|
+
sys.stdout.write(json.dumps(resp) + "\n")
|
|
287
|
+
sys.stdout.flush()
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
if __name__ == "__main__":
|
|
291
|
+
main()
|