codemode-mcp 0.2.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.
@@ -0,0 +1,310 @@
1
+ """Connections to the real (upstream) MCP servers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import base64
7
+ import contextlib
8
+ import json
9
+ import logging
10
+ from contextlib import AsyncExitStack
11
+ from typing import Any
12
+
13
+ import mcp_types as types
14
+ from mcp import Client
15
+ from mcp.client.sse import sse_client
16
+ from mcp.client.stdio import StdioServerParameters
17
+ from mcp.client.streamable_http import streamable_http_client
18
+
19
+ from .catalog import Catalog, ToolSpec, is_wrapped_result, to_identifier
20
+ from .config import ServerConfig
21
+
22
+ log = logging.getLogger("codemode_mcp")
23
+
24
+
25
+ class UpstreamError(Exception):
26
+ """An upstream tool call failed (the message is shown to the model)."""
27
+
28
+
29
+ def _http_client(headers: dict[str, str] | None, auth: Any = None):
30
+ try:
31
+ from mcp.shared._httpx_utils import create_mcp_http_client
32
+
33
+ return create_mcp_http_client(headers=headers, auth=auth)
34
+ except ImportError: # pragma: no cover - private helper moved
35
+ import httpx2
36
+
37
+ return httpx2.AsyncClient(headers=headers, auth=auth, timeout=httpx2.Timeout(30, read=300))
38
+
39
+
40
+ def result_to_value(result: types.CallToolResult, wrapped: bool = False) -> Any:
41
+ """Convert an MCP tool result into a plain JSON value for sandboxed code."""
42
+ if result.is_error:
43
+ texts = [c.text for c in result.content if isinstance(c, types.TextContent)]
44
+ raise UpstreamError("\n".join(texts) or "tool returned an error")
45
+ if result.structured_content is not None:
46
+ sc = result.structured_content
47
+ if wrapped and isinstance(sc, dict) and list(sc) == ["result"]:
48
+ return sc["result"]
49
+ return sc
50
+ values: list[Any] = []
51
+ for c in result.content:
52
+ if isinstance(c, types.TextContent):
53
+ text = c.text
54
+ stripped = text.strip()
55
+ if stripped[:1] in ("{", "[") or stripped in ("true", "false", "null") or _is_number(stripped):
56
+ try:
57
+ values.append(json.loads(stripped))
58
+ continue
59
+ except json.JSONDecodeError:
60
+ pass
61
+ values.append(text)
62
+ elif isinstance(c, (types.ImageContent, types.AudioContent)):
63
+ values.append(
64
+ {
65
+ "type": c.type,
66
+ "mime_type": c.mime_type,
67
+ "data": c.data,
68
+ "size_bytes": len(base64.b64decode(c.data, validate=False)) if c.data else 0,
69
+ }
70
+ )
71
+ else:
72
+ values.append(c.model_dump(mode="json", by_alias=True, exclude_none=True))
73
+ if not values:
74
+ return None
75
+ return values[0] if len(values) == 1 else values
76
+
77
+
78
+ def _is_number(s: str) -> bool:
79
+ try:
80
+ float(s)
81
+ return True
82
+ except ValueError:
83
+ return False
84
+
85
+
86
+ class Upstreams:
87
+ """Owns one MCP ``Client`` per configured server and builds the tool catalog.
88
+
89
+ The connections live in a dedicated background task, so ``start()`` and ``close()``
90
+ may be called from different tasks (anyio cancel scopes must exit where they entered).
91
+ """
92
+
93
+ def __init__(self, servers: list[ServerConfig], tool_call_timeout: float = 60.0):
94
+ self.servers = servers
95
+ self.tool_call_timeout = tool_call_timeout
96
+ self._stack: AsyncExitStack | None = None
97
+ self._clients: dict[str, Client] = {}
98
+ self._configs = {s.name: s for s in servers}
99
+ self._known: set[tuple[str, str]] = set()
100
+ self._wrapped: set[tuple[str, str]] = set()
101
+ self._task: asyncio.Task[None] | None = None
102
+ self._stop: asyncio.Event | None = None
103
+ self.raw_tools: dict[tuple[str, str], types.Tool] = {}
104
+ self.catalog = Catalog([])
105
+
106
+ async def start(self, max_description_chars: int = 600) -> Catalog:
107
+ if self._task is not None:
108
+ return self.catalog
109
+ ready: asyncio.Future[None] = asyncio.get_running_loop().create_future()
110
+ self._stop = asyncio.Event()
111
+ self._task = asyncio.create_task(self._own_connections(ready, max_description_chars))
112
+ try:
113
+ await ready
114
+ except BaseException:
115
+ task, self._task = self._task, None
116
+ task.cancel()
117
+ with contextlib.suppress(BaseException):
118
+ await task
119
+ raise
120
+ return self.catalog
121
+
122
+ async def _own_connections(self, ready: asyncio.Future[None], max_description_chars: int) -> None:
123
+ try:
124
+ async with AsyncExitStack() as stack:
125
+ self._stack = stack
126
+ self.catalog = await self._connect_all(max_description_chars)
127
+ ready.set_result(None)
128
+ assert self._stop is not None
129
+ await self._stop.wait()
130
+ except BaseException as e:
131
+ if not ready.done():
132
+ if isinstance(e, asyncio.CancelledError):
133
+ ready.cancel()
134
+ raise
135
+ ready.set_exception(e)
136
+ return
137
+ raise
138
+ finally:
139
+ self._stack = None
140
+ self._clients.clear()
141
+
142
+ async def _connect_all(self, max_description_chars: int) -> Catalog:
143
+ specs: list[ToolSpec] = []
144
+ used_servers: set[str] = set()
145
+ for cfg in self.servers:
146
+ client = await self._connect(cfg)
147
+ self._clients[cfg.name] = client
148
+ py_server = to_identifier(cfg.name)
149
+ while py_server in used_servers:
150
+ py_server += "_"
151
+ used_servers.add(py_server)
152
+ used_tools: set[str] = set()
153
+ for tool in await self._list_tools(client):
154
+ if not cfg.allows(tool.name):
155
+ continue
156
+ py_name = to_identifier(tool.name)
157
+ while py_name in used_tools:
158
+ py_name += "_"
159
+ used_tools.add(py_name)
160
+ if is_wrapped_result(tool.output_schema):
161
+ self._wrapped.add((cfg.name, tool.name))
162
+ self.raw_tools[(cfg.name, tool.name)] = tool
163
+ specs.append(
164
+ ToolSpec.from_mcp(
165
+ cfg.name,
166
+ py_server,
167
+ py_name,
168
+ tool.name,
169
+ tool.description,
170
+ tool.input_schema,
171
+ tool.output_schema,
172
+ )
173
+ )
174
+ log.info("connected to %s (%d tools)", cfg.name, sum(1 for s in specs if s.server == cfg.name))
175
+ self._known = {(s.server, s.name) for s in specs}
176
+ return Catalog(specs, max_description_chars)
177
+
178
+ async def _connect(self, cfg: ServerConfig) -> Client:
179
+ assert self._stack is not None
180
+ if cfg.transport == "stdio":
181
+ assert cfg.command
182
+ target: Any = StdioServerParameters(command=cfg.command, args=cfg.args, env=cfg.env, cwd=cfg.cwd)
183
+ else:
184
+ auth = None
185
+ if cfg.oauth is not None:
186
+ from .oauth import build_oauth_provider
187
+
188
+ auth = build_oauth_provider(cfg)
189
+ if cfg.transport == "sse":
190
+ target = sse_client(cfg.url, headers=cfg.headers, auth=auth) # type: ignore[arg-type]
191
+ else:
192
+ http = await self._stack.enter_async_context(_http_client(cfg.headers, auth))
193
+ target = streamable_http_client(cfg.url, http_client=http) # type: ignore[arg-type]
194
+ try:
195
+ return await self._stack.enter_async_context(Client(target, read_timeout_seconds=self.tool_call_timeout))
196
+ except Exception as e:
197
+ raise RuntimeError(f"Failed to connect to MCP server {cfg.name!r}: {e}") from e
198
+
199
+ @staticmethod
200
+ async def _list_tools(client: Client) -> list[types.Tool]:
201
+ tools: list[types.Tool] = []
202
+ cursor = None
203
+ for _ in range(100):
204
+ page = await client.list_tools(cursor=cursor)
205
+ tools.extend(page.tools)
206
+ cursor = page.next_cursor
207
+ if not cursor:
208
+ break
209
+ return tools
210
+
211
+ def _client_for_tool(self, server: str, tool: str) -> Client:
212
+ client = self._clients.get(server)
213
+ if client is None:
214
+ raise UpstreamError(f"unknown server {server!r}")
215
+ cfg = self._configs[server]
216
+ if (server, tool) not in self._known or not cfg.allows(tool):
217
+ raise UpstreamError(f"tool {tool!r} is not available on server {server!r}")
218
+ return client
219
+
220
+ async def call_raw(self, server: str, tool: str, args: dict[str, Any]) -> types.CallToolResult:
221
+ """Call a tool and return the untouched MCP result (used for hybrid pass-through)."""
222
+ client = self._client_for_tool(server, tool)
223
+ try:
224
+ return await client.call_tool(tool, args)
225
+ except Exception as e:
226
+ raise UpstreamError(f"{type(e).__name__}: {e}") from e
227
+
228
+ async def call(self, server: str, tool: str, args: dict[str, Any]) -> Any:
229
+ result = await self.call_raw(server, tool, args)
230
+ return result_to_value(result, wrapped=(server, tool) in self._wrapped)
231
+
232
+ # -- resources & prompts ---------------------------------------------------------
233
+
234
+ def _supports(self, server: str, capability: str) -> bool:
235
+ client = self._clients.get(server)
236
+ if client is None:
237
+ return False
238
+ try:
239
+ return getattr(client.server_capabilities, capability, None) is not None
240
+ except Exception:
241
+ return False
242
+
243
+ def servers_with(self, capability: str) -> list[str]:
244
+ return [name for name in self._clients if self._supports(name, capability)]
245
+
246
+ async def list_resources(self, server: str | None = None) -> list[tuple[str, types.Resource]]:
247
+ out: list[tuple[str, types.Resource]] = []
248
+ for name in [server] if server else self.servers_with("resources"):
249
+ if not self._supports(name, "resources"):
250
+ continue
251
+ client = self._clients[name]
252
+ cursor = None
253
+ for _ in range(50):
254
+ page = await client.list_resources(cursor=cursor)
255
+ out.extend((name, r) for r in page.resources)
256
+ cursor = page.next_cursor
257
+ if not cursor:
258
+ break
259
+ return out
260
+
261
+ async def list_resource_templates(self) -> list[tuple[str, types.ResourceTemplate]]:
262
+ out: list[tuple[str, types.ResourceTemplate]] = []
263
+ for name in self.servers_with("resources"):
264
+ with contextlib.suppress(Exception):
265
+ page = await self._clients[name].list_resource_templates()
266
+ out.extend((name, t) for t in page.resource_templates)
267
+ return out
268
+
269
+ async def read_resource(self, uri: str, server: str | None = None) -> tuple[str, types.ReadResourceResult]:
270
+ candidates = [server] if server else self.servers_with("resources")
271
+ if server is None:
272
+ # Prefer the server that listed this exact URI.
273
+ owners = [name for name, r in await self.list_resources() if str(r.uri) == uri]
274
+ candidates = owners + [c for c in candidates if c not in owners]
275
+ errors = []
276
+ for name in candidates:
277
+ client = self._clients.get(name)
278
+ if client is None:
279
+ continue
280
+ try:
281
+ return name, await client.read_resource(uri)
282
+ except Exception as e:
283
+ errors.append(f"{name}: {e}")
284
+ raise UpstreamError(f"could not read resource {uri!r}" + (f" ({'; '.join(errors)})" if errors else ""))
285
+
286
+ async def list_prompts(self) -> list[tuple[str, types.Prompt]]:
287
+ out: list[tuple[str, types.Prompt]] = []
288
+ for name in self.servers_with("prompts"):
289
+ page = await self._clients[name].list_prompts()
290
+ out.extend((name, p) for p in page.prompts)
291
+ return out
292
+
293
+ async def get_prompt(self, server: str, name: str, arguments: dict[str, str] | None) -> types.GetPromptResult:
294
+ client = self._clients.get(server)
295
+ if client is None:
296
+ raise UpstreamError(f"unknown server {server!r}")
297
+ return await client.get_prompt(name, arguments)
298
+
299
+ async def close(self) -> None:
300
+ task, self._task = self._task, None
301
+ if task is None:
302
+ return
303
+ if self._stop is not None:
304
+ self._stop.set()
305
+ try:
306
+ await asyncio.wait_for(task, 15)
307
+ except (TimeoutError, asyncio.CancelledError):
308
+ task.cancel()
309
+ with contextlib.suppress(BaseException):
310
+ await task
codemode_mcp/usage.py ADDED
@@ -0,0 +1,290 @@
1
+ """Token accounting: what Code Mode actually used vs what classic MCP would have used.
2
+
3
+ Every ``run_code`` / ``search_tools`` / direct tool call is recorded in a local SQLite
4
+ database (no code, arguments or results are stored — only counts and tool names).
5
+
6
+ Estimation model (deliberately conservative towards classic MCP):
7
+
8
+ * **Code Mode tokens** for one call = Code Mode tool definitions (one LLM turn)
9
+ + the code / query the model wrote + the output returned to the model.
10
+ * **Classic MCP tokens** for the same work = for every upstream tool call: one LLM turn
11
+ carrying all classic tool definitions + the call arguments + the full raw result.
12
+ Re-sending of conversation history on later turns is *not* counted, so real classic
13
+ usage is usually higher than this estimate.
14
+
15
+ Measured numbers from real LLM runs (``codemode-mcp benchmark`` and the built-in agent
16
+ loops) are stored alongside, tagged ``measured``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import math
23
+ import os
24
+ import sqlite3
25
+ import threading
26
+ import time
27
+ import uuid
28
+ from dataclasses import asdict, dataclass, field
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+
33
+ def codemode_home() -> Path:
34
+ return Path(os.environ.get("CODEMODE_HOME") or Path.home() / ".codemode-mcp")
35
+
36
+
37
+ class Tokenizer:
38
+ """Counts tokens with tiktoken (o200k_base) when installed, else ~4 chars/token."""
39
+
40
+ def __init__(self, kind: str = "auto"):
41
+ self._enc = None
42
+ if kind in ("auto", "tiktoken"):
43
+ try:
44
+ import tiktoken
45
+
46
+ self._enc = tiktoken.get_encoding("o200k_base")
47
+ except Exception:
48
+ if kind == "tiktoken":
49
+ raise RuntimeError(
50
+ "tokenizer 'tiktoken' requested but tiktoken is not installed "
51
+ "(pip install 'codemode-mcp[tokens]')"
52
+ ) from None
53
+ self.name = "tiktoken:o200k_base" if self._enc else "chars/4"
54
+
55
+ def count(self, text: str) -> int:
56
+ if not text:
57
+ return 0
58
+ if self._enc is not None:
59
+ return len(self._enc.encode(text, disallowed_special=()))
60
+ return math.ceil(len(text) / 4)
61
+
62
+ def count_json(self, value: Any) -> int:
63
+ if isinstance(value, str):
64
+ return self.count(value)
65
+ return self.count(json.dumps(value, ensure_ascii=False, default=str))
66
+
67
+
68
+ @dataclass
69
+ class UsageEvent:
70
+ kind: str
71
+ """run_code | search_tools | direct | llm | benchmark"""
72
+ codemode_tokens: int = 0
73
+ classic_tokens: int = 0
74
+ upstream_calls: int = 0
75
+ tools: list[str] = field(default_factory=list)
76
+ ok: bool = True
77
+ duration_ms: int = 0
78
+ measured: bool = False
79
+ session: str = ""
80
+ details: dict[str, Any] = field(default_factory=dict)
81
+ ts: float = field(default_factory=time.time)
82
+
83
+ @property
84
+ def saved_tokens(self) -> int:
85
+ return self.classic_tokens - self.codemode_tokens
86
+
87
+
88
+ _SCHEMA = """
89
+ CREATE TABLE IF NOT EXISTS events (
90
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
91
+ ts REAL NOT NULL,
92
+ session TEXT NOT NULL,
93
+ kind TEXT NOT NULL,
94
+ codemode_tokens INTEGER NOT NULL,
95
+ classic_tokens INTEGER NOT NULL,
96
+ upstream_calls INTEGER NOT NULL,
97
+ tools TEXT NOT NULL,
98
+ ok INTEGER NOT NULL,
99
+ duration_ms INTEGER NOT NULL,
100
+ measured INTEGER NOT NULL,
101
+ details TEXT NOT NULL
102
+ );
103
+ CREATE INDEX IF NOT EXISTS events_ts ON events(ts);
104
+ """
105
+
106
+
107
+ class UsageStore:
108
+ """Thread-safe SQLite store of usage events."""
109
+
110
+ def __init__(self, path: str | os.PathLike[str] | None = None):
111
+ self.path = Path(path) if path else codemode_home() / "usage.db"
112
+ self.path.parent.mkdir(parents=True, exist_ok=True)
113
+ self._lock = threading.Lock()
114
+ self._conn = sqlite3.connect(self.path, check_same_thread=False, timeout=10)
115
+ self._conn.row_factory = sqlite3.Row
116
+ with self._lock:
117
+ self._conn.executescript(_SCHEMA)
118
+ self._conn.execute("PRAGMA journal_mode=WAL")
119
+
120
+ def record(self, e: UsageEvent) -> None:
121
+ with self._lock:
122
+ self._conn.execute(
123
+ "INSERT INTO events (ts, session, kind, codemode_tokens, classic_tokens, upstream_calls, tools, ok,"
124
+ " duration_ms, measured, details) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
125
+ (
126
+ e.ts,
127
+ e.session,
128
+ e.kind,
129
+ e.codemode_tokens,
130
+ e.classic_tokens,
131
+ e.upstream_calls,
132
+ json.dumps(e.tools),
133
+ int(e.ok),
134
+ e.duration_ms,
135
+ int(e.measured),
136
+ json.dumps(e.details, default=str),
137
+ ),
138
+ )
139
+ self._conn.commit()
140
+
141
+ def _where(self, since: float | None, kinds: tuple[str, ...] | None) -> tuple[str, list[Any]]:
142
+ clauses, args = [], []
143
+ if since is not None:
144
+ clauses.append("ts >= ?")
145
+ args.append(since)
146
+ if kinds:
147
+ clauses.append(f"kind IN ({','.join('?' * len(kinds))})")
148
+ args.extend(kinds)
149
+ return (" WHERE " + " AND ".join(clauses)) if clauses else "", args
150
+
151
+ def summary(self, since: float | None = None) -> dict[str, Any]:
152
+ """Aggregate estimated savings (tool activity) plus measured LLM/benchmark data."""
153
+ where, args = self._where(since, ("run_code", "search_tools", "direct"))
154
+ with self._lock:
155
+ row = self._conn.execute(
156
+ "SELECT COUNT(*) n, COALESCE(SUM(codemode_tokens),0) cm, COALESCE(SUM(classic_tokens),0) cl,"
157
+ f" COALESCE(SUM(upstream_calls),0) calls, COALESCE(SUM(1-ok),0) errors FROM events{where}",
158
+ args,
159
+ ).fetchone()
160
+ by_kind = self._conn.execute(
161
+ "SELECT kind, COUNT(*) n, SUM(codemode_tokens) cm, SUM(classic_tokens) cl, SUM(upstream_calls) calls"
162
+ f" FROM events{where} GROUP BY kind ORDER BY n DESC",
163
+ args,
164
+ ).fetchall()
165
+ days = self._conn.execute(
166
+ "SELECT date(ts, 'unixepoch', 'localtime') day, SUM(codemode_tokens) cm, SUM(classic_tokens) cl,"
167
+ f" COUNT(*) n FROM events{where} GROUP BY day ORDER BY day",
168
+ args,
169
+ ).fetchall()
170
+ tool_rows = self._conn.execute(f"SELECT tools FROM events{where}", args).fetchall()
171
+ mwhere, margs = self._where(since, ("llm",))
172
+ llm = self._conn.execute(
173
+ "SELECT COUNT(*) n, COALESCE(SUM(codemode_tokens),0) tokens,"
174
+ f" COALESCE(SUM(json_extract(details,'$.input_tokens')),0) inp,"
175
+ f" COALESCE(SUM(json_extract(details,'$.output_tokens')),0) outp FROM events{mwhere}",
176
+ margs,
177
+ ).fetchone()
178
+ tool_counts: dict[str, int] = {}
179
+ for r in tool_rows:
180
+ for t in json.loads(r["tools"]):
181
+ tool_counts[t] = tool_counts.get(t, 0) + 1
182
+ cm, cl = row["cm"], row["cl"]
183
+ return {
184
+ "calls": row["n"],
185
+ "upstream_calls": row["calls"],
186
+ "errors": row["errors"],
187
+ "codemode_tokens": cm,
188
+ "classic_tokens_estimate": cl,
189
+ "saved_tokens": cl - cm,
190
+ "saved_pct": round(100 * (cl - cm) / cl, 1) if cl else 0.0,
191
+ "by_kind": [dict(r) for r in by_kind],
192
+ "by_day": [dict(r) for r in days],
193
+ "top_tools": sorted(tool_counts.items(), key=lambda kv: -kv[1])[:15],
194
+ "llm": {"requests_logged": llm["n"], "input_tokens": llm["inp"], "output_tokens": llm["outp"]},
195
+ "benchmarks": self.benchmarks(since=since, limit=20),
196
+ }
197
+
198
+ def benchmarks(self, since: float | None = None, limit: int = 20) -> list[dict[str, Any]]:
199
+ where, args = self._where(since, ("benchmark",))
200
+ with self._lock:
201
+ rows = self._conn.execute(
202
+ f"SELECT ts, codemode_tokens, classic_tokens, ok, details FROM events{where} ORDER BY ts DESC LIMIT ?",
203
+ [*args, limit],
204
+ ).fetchall()
205
+ out = []
206
+ for r in rows:
207
+ d = json.loads(r["details"])
208
+ out.append(
209
+ {
210
+ "ts": r["ts"],
211
+ "codemode_tokens": r["codemode_tokens"],
212
+ "classic_tokens": r["classic_tokens"],
213
+ "saved_pct": round(100 * (1 - r["codemode_tokens"] / r["classic_tokens"]), 1)
214
+ if r["classic_tokens"]
215
+ else 0.0,
216
+ **d,
217
+ }
218
+ )
219
+ return out
220
+
221
+ def recent(self, limit: int = 50) -> list[dict[str, Any]]:
222
+ with self._lock:
223
+ rows = self._conn.execute("SELECT * FROM events ORDER BY ts DESC LIMIT ?", (limit,)).fetchall()
224
+ return [
225
+ {
226
+ **dict(r),
227
+ "tools": json.loads(r["tools"]),
228
+ "details": json.loads(r["details"]),
229
+ "ok": bool(r["ok"]),
230
+ "measured": bool(r["measured"]),
231
+ }
232
+ for r in rows
233
+ ]
234
+
235
+ def clear(self) -> int:
236
+ with self._lock:
237
+ n = self._conn.execute("DELETE FROM events").rowcount
238
+ self._conn.commit()
239
+ return n
240
+
241
+ def close(self) -> None:
242
+ with self._lock:
243
+ self._conn.close()
244
+
245
+
246
+ class UsageTracker:
247
+ """Computes per-call token accounting and writes it to a ``UsageStore``."""
248
+
249
+ def __init__(self, store: UsageStore | None, tokenizer: Tokenizer, session: str | None = None):
250
+ self.store = store
251
+ self.tokenizer = tokenizer
252
+ self.session = session or uuid.uuid4().hex[:12]
253
+ self.classic_defs_tokens = 0
254
+ self.codemode_defs_tokens = 0
255
+ self.totals = {"codemode_tokens": 0, "classic_tokens": 0, "calls": 0, "upstream_calls": 0}
256
+
257
+ def set_definitions(self, classic_defs: list[dict[str, Any]], codemode_defs: list[dict[str, Any]]) -> None:
258
+ self.classic_defs_tokens = self.tokenizer.count_json(classic_defs)
259
+ self.codemode_defs_tokens = self.tokenizer.count_json(codemode_defs)
260
+
261
+ def classic_call_cost(self, args: Any, result: Any) -> int:
262
+ """Tokens one upstream tool call would cost in a classic MCP agent loop."""
263
+ return self.classic_defs_tokens + self.tokenizer.count_json(args) + self.tokenizer.count_json(result) + 12
264
+
265
+ def record(self, event: UsageEvent) -> UsageEvent:
266
+ event.session = event.session or self.session
267
+ if not event.measured:
268
+ self.totals["codemode_tokens"] += event.codemode_tokens
269
+ self.totals["classic_tokens"] += event.classic_tokens
270
+ self.totals["calls"] += 1
271
+ self.totals["upstream_calls"] += event.upstream_calls
272
+ if self.store is not None:
273
+ try:
274
+ self.store.record(event)
275
+ except Exception: # never let accounting break tool execution
276
+ pass
277
+ return event
278
+
279
+ def session_summary(self) -> dict[str, Any]:
280
+ cm, cl = self.totals["codemode_tokens"], self.totals["classic_tokens"]
281
+ return {
282
+ **self.totals,
283
+ "saved_tokens": cl - cm,
284
+ "saved_pct": round(100 * (cl - cm) / cl, 1) if cl else 0.0,
285
+ "tokenizer": self.tokenizer.name,
286
+ }
287
+
288
+
289
+ def event_to_dict(e: UsageEvent) -> dict[str, Any]:
290
+ return {**asdict(e), "saved_tokens": e.saved_tokens}