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.
codemode_mcp/core.py ADDED
@@ -0,0 +1,550 @@
1
+ """The public ``CodeMode`` API: wrap MCP servers behind ``search_tools`` + ``run_code``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import fnmatch
7
+ import json
8
+ import logging
9
+ import os
10
+ import time
11
+ from collections.abc import Awaitable, Callable
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import mcp_types as types
16
+
17
+ from .catalog import Catalog, ToolSpec, estimate_tokens
18
+ from .config import Config, ServerConfig, Settings
19
+ from .sandbox import DenoSandbox, ExecResult
20
+ from .upstream import UpstreamError, Upstreams
21
+ from .usage import Tokenizer, UsageEvent, UsageStore, UsageTracker
22
+
23
+ SEARCH_TOOL = "search_tools"
24
+ RUN_TOOL = "run_code"
25
+
26
+ Approver = Callable[[str, str, dict[str, Any]], Awaitable[bool]]
27
+ """``async (server, tool, args) -> bool``: return True to allow a call that needs approval."""
28
+
29
+
30
+ class CodeMode:
31
+ """Expose any number of MCP servers to an LLM through two small tools.
32
+
33
+ Example::
34
+
35
+ async with CodeMode.from_config("mcp.json") as cm:
36
+ tools = cm.tools(format="openai")
37
+ ... # give `tools` to your LLM, then for each tool call:
38
+ output = await cm.call(name, arguments)
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ config: Config | dict[str, Any] | str | os.PathLike[str],
44
+ *,
45
+ settings: Settings | None = None,
46
+ approval_callback: Approver | None = None,
47
+ usage_store: UsageStore | None = None,
48
+ ):
49
+ self.config = config if isinstance(config, Config) else Config.load(config)
50
+ if settings is not None:
51
+ self.config.settings = settings
52
+ self.settings = self.config.settings
53
+ self.upstreams = Upstreams(self.config.servers, tool_call_timeout=self.settings.tool_call_timeout)
54
+ self.sandbox = DenoSandbox(deno_path=self.settings.deno_path, memory_mb=self.settings.memory_mb)
55
+ self.approval_callback = approval_callback
56
+ self.tokenizer = Tokenizer(self.settings.tokenizer)
57
+ if usage_store is None and self.settings.usage_tracking:
58
+ try:
59
+ usage_store = UsageStore(self.settings.usage_db)
60
+ except Exception as e: # noqa: BLE001 - accounting must never block tool use
61
+ logging.getLogger("codemode_mcp").warning("usage tracking disabled: %s", e)
62
+ self.usage_store = usage_store
63
+ self.tracker = UsageTracker(usage_store, self.tokenizer)
64
+ self.last_run: ExecResult | None = None
65
+ self.last_event: UsageEvent | None = None
66
+ self._direct: dict[str, ToolSpec] = {}
67
+ self._started = False
68
+
69
+ @classmethod
70
+ def from_config(
71
+ cls,
72
+ path: str | os.PathLike[str] | dict[str, Any],
73
+ *,
74
+ approval_callback: Approver | None = None,
75
+ usage_store: UsageStore | None = None,
76
+ **settings: Any,
77
+ ) -> CodeMode:
78
+ config = Config.load(path)
79
+ if settings:
80
+ config.settings = Settings.from_dict({**config.settings.__dict__, **settings})
81
+ return cls(config, approval_callback=approval_callback, usage_store=usage_store)
82
+
83
+ @classmethod
84
+ def from_servers(
85
+ cls,
86
+ servers: dict[str, dict[str, Any]],
87
+ *,
88
+ approval_callback: Approver | None = None,
89
+ usage_store: UsageStore | None = None,
90
+ **settings: Any,
91
+ ) -> CodeMode:
92
+ """Build from an ``mcpServers``-style mapping without a config file."""
93
+ config = Config([ServerConfig.from_dict(k, v) for k, v in servers.items()], Settings.from_dict(settings))
94
+ return cls(config, approval_callback=approval_callback, usage_store=usage_store)
95
+
96
+ # -- lifecycle -------------------------------------------------------------------
97
+
98
+ async def start(self) -> CodeMode:
99
+ if self._started:
100
+ return self
101
+ catalog = await self.upstreams.start(self.settings.max_description_chars)
102
+ try:
103
+ await self.sandbox.start(catalog.sandbox_specs())
104
+ except BaseException:
105
+ await self.upstreams.close()
106
+ raise
107
+ self._direct = {
108
+ f"{t.py_server}__{t.py_name}"[:64]: t
109
+ for t in catalog.tools
110
+ if any(_matches(p, t) for p in self.settings.expose_tools)
111
+ }
112
+ self.tracker.set_definitions(self.classic_tool_definitions(), self.tool_definitions())
113
+ self._started = True
114
+ return self
115
+
116
+ async def close(self) -> None:
117
+ self._started = False
118
+ try:
119
+ await self.sandbox.close()
120
+ finally:
121
+ await self.upstreams.close()
122
+
123
+ async def __aenter__(self) -> CodeMode:
124
+ return await self.start()
125
+
126
+ async def __aexit__(self, *exc: object) -> None:
127
+ await self.close()
128
+
129
+ @property
130
+ def catalog(self) -> Catalog:
131
+ return self.upstreams.catalog
132
+
133
+ # -- what the LLM sees -----------------------------------------------------------
134
+
135
+ @property
136
+ def inline_catalog(self) -> bool:
137
+ """True when all tool stubs are small enough to embed (search_tools not needed)."""
138
+ return estimate_tokens(self.catalog.render()) <= self.settings.inline_catalog_tokens
139
+
140
+ def _run_code_description(self) -> str:
141
+ servers = ", ".join(self.catalog.servers) or "(none)"
142
+ intro = (
143
+ "Run Python code in a secure sandbox to accomplish a task with the available tools. "
144
+ "Prefer ONE run_code call that does all the work (loops, filtering, joining data across tools) "
145
+ "over many small calls.\n\n"
146
+ f"Each MCP server is a global object ({servers}); its tools are async functions, e.g. "
147
+ "`data = await server.tool_name(arg=value)`. Results are plain Python values (dict/list/str). "
148
+ "Top-level `await` and `asyncio.gather` work. Only the standard library is available; there is no "
149
+ "network or file access except via the tools. A failed tool call raises `ToolError`."
150
+ )
151
+ if self.upstreams.servers_with("resources"):
152
+ intro += " MCP resources: `await resources.list()`, `await resources.read(uri)`."
153
+ if self.settings.persistent_state:
154
+ intro += " Variables persist between run_code calls."
155
+ intro += (
156
+ "\n\nReturn ONLY what you need: the value of the last expression is returned as JSON, and print() "
157
+ "output is returned too. Don't print large raw tool results; extract the relevant fields in code."
158
+ )
159
+ if self.inline_catalog:
160
+ return f"{intro}\n\nAvailable tools:\n```python\n{self.catalog.render()}\n```"
161
+ names = self.catalog.render_names()
162
+ if estimate_tokens(names) <= self.settings.inline_names_tokens:
163
+ listing = f"Available tools (call `{SEARCH_TOOL}` to get exact signatures before use):\n{names}"
164
+ else:
165
+ listing = (
166
+ f"Servers: {self.catalog.render_servers()}. "
167
+ f"Call `{SEARCH_TOOL}` to discover tools and their exact signatures before use."
168
+ )
169
+ return f"{intro}\n\n{listing}"
170
+
171
+ def tool_definitions(self) -> list[dict[str, Any]]:
172
+ """Provider-neutral definitions: ``name``, ``description``, ``input_schema``."""
173
+ defs = []
174
+ if not self.inline_catalog:
175
+ defs.append(
176
+ {
177
+ "name": SEARCH_TOOL,
178
+ "description": (
179
+ "Search the available tools by keywords (e.g. 'create issue', 'list dns records') and get "
180
+ "their Python signatures and docs, for use inside run_code. Pass an exact name like "
181
+ "'server.tool' to fetch one tool."
182
+ ),
183
+ "input_schema": {
184
+ "type": "object",
185
+ "properties": {
186
+ "query": {"type": "string", "description": "Keywords describing the capability you need"},
187
+ "limit": {
188
+ "type": "integer",
189
+ "description": f"Max results (default {self.settings.max_search_results})",
190
+ },
191
+ },
192
+ "required": ["query"],
193
+ },
194
+ }
195
+ )
196
+ defs.append(
197
+ {
198
+ "name": RUN_TOOL,
199
+ "description": self._run_code_description(),
200
+ "input_schema": {
201
+ "type": "object",
202
+ "properties": {"code": {"type": "string", "description": "Python source code to execute"}},
203
+ "required": ["code"],
204
+ },
205
+ }
206
+ )
207
+ for name, spec in self._direct.items():
208
+ defs.append(
209
+ {
210
+ "name": name,
211
+ "description": spec.description or spec.name,
212
+ "input_schema": spec.input_schema or {"type": "object", "properties": {}},
213
+ }
214
+ )
215
+ return defs
216
+
217
+ def classic_tool_definitions(self) -> list[dict[str, Any]]:
218
+ """What a classic MCP client would send: every upstream tool, verbatim."""
219
+ out = []
220
+ for (server, name), tool in self.upstreams.raw_tools.items():
221
+ if any(t.server == server and t.name == name for t in self.catalog.tools):
222
+ out.append({"name": name, "description": tool.description or "", "inputSchema": tool.input_schema})
223
+ return out
224
+
225
+ def tools(self, format: str = "openai") -> list[dict[str, Any]]:
226
+ """Tool definitions in a provider's format: ``openai``, ``openai-responses``, ``anthropic`` or ``mcp``."""
227
+ defs = self.tool_definitions()
228
+ if format == "openai":
229
+ return [
230
+ {
231
+ "type": "function",
232
+ "function": {"name": d["name"], "description": d["description"], "parameters": d["input_schema"]},
233
+ }
234
+ for d in defs
235
+ ]
236
+ if format == "openai-responses":
237
+ return [
238
+ {
239
+ "type": "function",
240
+ "name": d["name"],
241
+ "description": d["description"],
242
+ "parameters": d["input_schema"],
243
+ }
244
+ for d in defs
245
+ ]
246
+ if format == "anthropic":
247
+ return defs
248
+ if format == "mcp":
249
+ return [
250
+ {"name": d["name"], "description": d["description"], "inputSchema": d["input_schema"]} for d in defs
251
+ ]
252
+ raise ValueError(f"unknown tool format {format!r}")
253
+
254
+ @property
255
+ def direct_tools(self) -> dict[str, ToolSpec]:
256
+ return dict(self._direct)
257
+
258
+ @property
259
+ def system_prompt(self) -> str:
260
+ """Optional short system-prompt addendum that nudges models toward efficient use."""
261
+ return (
262
+ "You can use external tools by writing Python with the `run_code` tool. Plan the whole task, "
263
+ "then write a single script that calls the tools, processes the data and returns only the final, "
264
+ "compact answer. Use `search_tools` first if you don't yet know the exact tool signatures."
265
+ )
266
+
267
+ # -- tool execution --------------------------------------------------------------
268
+
269
+ async def call(self, name: str, arguments: dict[str, Any] | str | None, *, approver: Approver | None = None) -> str:
270
+ """Execute one of the exposed tools and return text for the LLM."""
271
+ if isinstance(arguments, str):
272
+ arguments = json.loads(arguments or "{}")
273
+ arguments = arguments or {}
274
+ if name == SEARCH_TOOL:
275
+ return self.search_tools(str(arguments.get("query", "")), arguments.get("limit"))
276
+ if name == RUN_TOOL:
277
+ return await self.run_code(str(arguments.get("code", "")), approver=approver)
278
+ if name in self._direct:
279
+ try:
280
+ result = await self.call_direct(name, arguments, approver=approver)
281
+ except UpstreamError as e:
282
+ return f"Error: {e}"
283
+ return content_to_text(result)
284
+ return f"Error: unknown tool {name!r}. Available: {', '.join(d['name'] for d in self.tool_definitions())}"
285
+
286
+ def search_tools(self, query: str, limit: int | None = None) -> str:
287
+ start = time.perf_counter()
288
+ limit = int(limit or self.settings.max_search_results)
289
+ hits = self.catalog.search(query, limit=max(1, min(limit, 50)))
290
+ if not hits:
291
+ names = self.catalog.render_names()[:2000]
292
+ out = f"No tools matched {query!r}. Servers: {self.catalog.render_servers()}.\n{names}"
293
+ else:
294
+ out = "```python\n" + self.catalog.render(hits) + "\n```"
295
+ self.last_event = self.tracker.record(
296
+ UsageEvent(
297
+ kind="search_tools",
298
+ codemode_tokens=self.tracker.codemode_defs_tokens
299
+ + self.tokenizer.count(query)
300
+ + self.tokenizer.count(out),
301
+ classic_tokens=0,
302
+ details={"hits": len(hits)},
303
+ duration_ms=int(1000 * (time.perf_counter() - start)),
304
+ )
305
+ )
306
+ return out
307
+
308
+ async def run_code(self, code: str, *, approver: Approver | None = None) -> str:
309
+ if not self._started:
310
+ raise RuntimeError("CodeMode is not started; use `async with CodeMode(...)` or `await cm.start()`")
311
+ start = time.perf_counter()
312
+ classic = 0
313
+
314
+ async def handler(server: str, tool: str, args: dict[str, Any]) -> Any:
315
+ nonlocal classic
316
+ if server == "__codemode__":
317
+ return await self._builtin(tool, args)
318
+ value: Any = None
319
+ try:
320
+ await self._check_approval(server, tool, args, approver)
321
+ value = await self.upstreams.call(server, tool, args)
322
+ return value
323
+ finally:
324
+ classic += self.tracker.classic_call_cost(args, value)
325
+
326
+ result = await self.sandbox.execute(
327
+ code,
328
+ handler,
329
+ timeout=self.settings.timeout,
330
+ max_calls=self.settings.max_tool_calls,
331
+ persist=self.settings.persistent_state,
332
+ )
333
+ self.last_run = result
334
+ output = self._format(result)
335
+ upstream = [c for c in result.calls if c.server != "__codemode__"]
336
+ duration = int(1000 * (time.perf_counter() - start))
337
+ self.last_event = self.tracker.record(
338
+ UsageEvent(
339
+ kind="run_code",
340
+ codemode_tokens=self.tracker.codemode_defs_tokens
341
+ + self.tokenizer.count(code)
342
+ + self.tokenizer.count(output),
343
+ classic_tokens=classic,
344
+ upstream_calls=len(upstream),
345
+ tools=sorted({f"{c.server}.{c.tool}" for c in upstream}),
346
+ ok=result.ok,
347
+ duration_ms=duration,
348
+ )
349
+ )
350
+ self._audit(code, result, output, duration)
351
+ return output
352
+
353
+ async def call_direct(
354
+ self, name: str, arguments: dict[str, Any], *, approver: Approver | None = None
355
+ ) -> types.CallToolResult:
356
+ """Call a hybrid-mode (directly exposed) tool, returning the raw MCP result."""
357
+ spec = self._direct[name]
358
+ start = time.perf_counter()
359
+ await self._check_approval(spec.server, spec.name, arguments, approver)
360
+ result = await self.upstreams.call_raw(spec.server, spec.name, arguments)
361
+ payload = self.tokenizer.count_json(arguments) + self.tokenizer.count(content_to_text(result))
362
+ self.last_event = self.tracker.record(
363
+ UsageEvent(
364
+ kind="direct",
365
+ codemode_tokens=self.tracker.codemode_defs_tokens + payload,
366
+ classic_tokens=self.tracker.classic_defs_tokens + payload,
367
+ upstream_calls=1,
368
+ tools=[f"{spec.server}.{spec.name}"],
369
+ ok=not result.is_error,
370
+ duration_ms=int(1000 * (time.perf_counter() - start)),
371
+ )
372
+ )
373
+ return result
374
+
375
+ async def reset_state(self) -> None:
376
+ """Forget variables kept by ``persistent_state``."""
377
+ await self.sandbox.reset_state()
378
+
379
+ def needs_approval(self, server: str, tool: str) -> bool:
380
+ spec = next((t for t in self.catalog.tools if t.server == server and t.name == tool), None)
381
+ names = [f"{server}.{tool}"] + ([spec.qualified_name] if spec else [])
382
+ return any(fnmatch.fnmatchcase(n, p) for p in self.settings.require_approval for n in names)
383
+
384
+ async def _check_approval(self, server: str, tool: str, args: dict[str, Any], approver: Approver | None) -> None:
385
+ if not self.needs_approval(server, tool):
386
+ return
387
+ approver = approver or self.approval_callback
388
+ if approver is None:
389
+ raise UpstreamError(
390
+ f"{server}.{tool} requires human approval, but no approver is available "
391
+ "(the client does not support elicitation and no approval_callback is set)"
392
+ )
393
+ try:
394
+ async with self.sandbox.paused():
395
+ allowed = await approver(server, tool, args)
396
+ except Exception as e: # noqa: BLE001
397
+ raise UpstreamError(f"approval for {server}.{tool} failed: {e}") from e
398
+ if not allowed:
399
+ raise UpstreamError(f"{server}.{tool} was denied by the user")
400
+
401
+ async def _builtin(self, name: str, args: dict[str, Any]) -> Any:
402
+ if name == "list_resources":
403
+ items = await self.upstreams.list_resources(args.get("server"))
404
+ return [
405
+ {"server": s, "uri": str(r.uri), "name": r.name, "description": r.description, "mime_type": r.mime_type}
406
+ for s, r in items
407
+ ]
408
+ if name == "read_resource":
409
+ _, res = await self.upstreams.read_resource(str(args["uri"]), args.get("server"))
410
+ parts = []
411
+ for c in res.contents:
412
+ if isinstance(c, types.TextResourceContents):
413
+ parts.append(c.text)
414
+ else:
415
+ parts.append(
416
+ {
417
+ "uri": str(c.uri),
418
+ "mime_type": c.mime_type,
419
+ "blob": c.blob,
420
+ "size_bytes": len(base64.b64decode(c.blob or "")),
421
+ }
422
+ )
423
+ return parts[0] if len(parts) == 1 else parts
424
+ raise UpstreamError(f"unknown builtin {name!r}")
425
+
426
+ def _format(self, r: ExecResult) -> str:
427
+ parts = []
428
+ if r.stdout.strip():
429
+ parts.append(r.stdout.rstrip())
430
+ if r.ok:
431
+ if r.has_result:
432
+ value = r.result if isinstance(r.result, str) else json.dumps(r.result, ensure_ascii=False, default=str)
433
+ parts.append(value)
434
+ if not parts:
435
+ parts.append("(no output; end your code with an expression or print() to return data)")
436
+ else:
437
+ parts.append(f"Error: {r.error}")
438
+ text = "\n".join(parts)
439
+ limit = self.settings.max_output_chars
440
+ if len(text) > limit:
441
+ text = (
442
+ text[:limit]
443
+ + f"\n... [truncated {len(text) - limit} chars; return less data, e.g. filter or summarise in code]"
444
+ )
445
+ return text
446
+
447
+ def _audit(self, code: str, r: ExecResult, output: str, duration_ms: int) -> None:
448
+ if not self.settings.audit_log:
449
+ return
450
+ entry = {
451
+ "ts": time.time(),
452
+ "session": self.tracker.session,
453
+ "ok": r.ok,
454
+ "duration_ms": duration_ms,
455
+ "code": code,
456
+ "output": output[:5000],
457
+ "calls": [
458
+ {"server": c.server, "tool": c.tool, "args": c.args, "ok": c.ok, "error": c.error} for c in r.calls
459
+ ],
460
+ }
461
+ try:
462
+ path = Path(self.settings.audit_log).expanduser()
463
+ path.parent.mkdir(parents=True, exist_ok=True)
464
+ with path.open("a", encoding="utf-8") as f:
465
+ f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
466
+ except OSError:
467
+ pass
468
+
469
+ # -- provider helpers ------------------------------------------------------------
470
+
471
+ async def handle_openai_tool_call(self, tool_call: Any) -> dict[str, Any]:
472
+ """Run an OpenAI Chat Completions ``tool_call`` and return the ``role=tool`` message."""
473
+ fn = _get(tool_call, "function")
474
+ output = await self.call(_get(fn, "name"), _get(fn, "arguments"))
475
+ return {"role": "tool", "tool_call_id": _get(tool_call, "id"), "content": output}
476
+
477
+ async def handle_anthropic_tool_use(self, block: Any) -> dict[str, Any]:
478
+ """Run an Anthropic ``tool_use`` content block and return the ``tool_result`` block."""
479
+ output = await self.call(_get(block, "name"), _get(block, "input"))
480
+ return {
481
+ "type": "tool_result",
482
+ "tool_use_id": _get(block, "id"),
483
+ "content": output,
484
+ "is_error": output.startswith("Error:"),
485
+ }
486
+
487
+ # -- accounting ------------------------------------------------------------------
488
+
489
+ def record_llm_usage(self, model: str, input_tokens: int, output_tokens: int, **details: Any) -> None:
490
+ """Log provider-reported token usage of one LLM request (shown as measured data)."""
491
+ self.tracker.record(
492
+ UsageEvent(
493
+ kind="llm",
494
+ measured=True,
495
+ codemode_tokens=input_tokens + output_tokens,
496
+ details={"model": model, "input_tokens": input_tokens, "output_tokens": output_tokens, **details},
497
+ )
498
+ )
499
+
500
+ def usage(self) -> dict[str, Any]:
501
+ """Token accounting for this ``CodeMode`` instance (since start)."""
502
+ return self.tracker.session_summary()
503
+
504
+ def stats(self) -> dict[str, Any]:
505
+ """Context cost of tool definitions per LLM request: classic MCP vs Code Mode."""
506
+ classic = self.tokenizer.count_json(self.classic_tool_definitions())
507
+ codemode = self.tokenizer.count_json(self.tool_definitions())
508
+ return {
509
+ "servers": len(self.catalog.servers),
510
+ "tools": len(self.catalog),
511
+ "classic_mcp_tokens": classic,
512
+ "codemode_tokens": codemode,
513
+ "mode": "inline" if self.inline_catalog else "search",
514
+ "direct_tools": len(self._direct),
515
+ "saved_pct": round(100 * (1 - codemode / classic), 1) if classic else 0.0,
516
+ "tokenizer": self.tokenizer.name,
517
+ }
518
+
519
+
520
+ def _matches(pattern: str, spec: ToolSpec) -> bool:
521
+ return fnmatch.fnmatchcase(f"{spec.server}.{spec.name}", pattern) or fnmatch.fnmatchcase(
522
+ spec.qualified_name, pattern
523
+ )
524
+
525
+
526
+ def content_to_text(result: types.CallToolResult) -> str:
527
+ if result.structured_content is not None and not result.is_error:
528
+ sc = result.structured_content
529
+ if isinstance(sc, dict) and list(sc) == ["result"]:
530
+ sc = sc["result"]
531
+ return sc if isinstance(sc, str) else json.dumps(sc, ensure_ascii=False, default=str)
532
+ parts = []
533
+ for c in result.content:
534
+ if isinstance(c, types.TextContent):
535
+ parts.append(c.text)
536
+ else:
537
+ parts.append(json.dumps(c.model_dump(mode="json", exclude_none=True))[:2000])
538
+ text = "\n".join(parts)
539
+ return ("Error: " + text) if result.is_error else text
540
+
541
+
542
+ def _get(obj: Any, key: str) -> Any:
543
+ return obj.get(key) if isinstance(obj, dict) else getattr(obj, key)
544
+
545
+
546
+ def default_config_path() -> Path | None:
547
+ for candidate in (Path("mcp.json"), Path(".mcp.json"), Path(".vscode/mcp.json")):
548
+ if candidate.exists():
549
+ return candidate
550
+ return None