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/cli.py ADDED
@@ -0,0 +1,395 @@
1
+ """Command line interface: ``codemode-mcp <command>``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import contextlib
8
+ import json
9
+ import logging
10
+ import os
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from .config import Config, ConfigError
17
+ from .core import CodeMode, default_config_path
18
+
19
+
20
+ def _config_arg(value: str | None) -> str:
21
+ if value:
22
+ return value
23
+ found = default_config_path()
24
+ if found is None:
25
+ raise SystemExit(
26
+ "No config given and no mcp.json found. Use --config path/to/mcp.json "
27
+ "(or create one with `codemode-mcp init --from claude`)"
28
+ )
29
+ return str(found)
30
+
31
+
32
+ def _usage_store(config: str | None):
33
+ from .usage import UsageStore
34
+
35
+ path = None
36
+ cfg = config or (str(default_config_path()) if default_config_path() else None)
37
+ if cfg:
38
+ with contextlib.suppress(Exception):
39
+ path = Config.load(cfg).settings.usage_db
40
+ return UsageStore(path)
41
+
42
+
43
+ async def _terminal_approver(server: str, tool: str, args: dict[str, Any]) -> bool:
44
+ print(f"\n[approval] {server}.{tool} {json.dumps(args, ensure_ascii=False)[:500]}", file=sys.stderr)
45
+ answer = await asyncio.to_thread(input, "Allow this call? [y/N] ")
46
+ return answer.strip().lower() in ("y", "yes")
47
+
48
+
49
+ # -- commands ---------------------------------------------------------------------------
50
+
51
+
52
+ async def _stats(args: argparse.Namespace) -> None:
53
+ async with CodeMode.from_config(_config_arg(args.config), usage_tracking=False) as cm:
54
+ s = cm.stats()
55
+ if args.json:
56
+ print(json.dumps(s, indent=2))
57
+ return
58
+ print(f"Servers: {s['servers']} Tools: {s['tools']} Strategy: {s['mode']} Tokenizer: {s['tokenizer']}")
59
+ print(f"Tool-definition tokens per LLM request, classic MCP : {s['classic_mcp_tokens']:>9,}")
60
+ print(f"Tool-definition tokens per LLM request, Code Mode : {s['codemode_tokens']:>9,}")
61
+ print(f"Saved per request (definitions only) : {s['saved_pct']:>8}%")
62
+ print("Intermediate tool results also stay in the sandbox. See `codemode-mcp usage` for real savings.")
63
+
64
+
65
+ async def _search(args: argparse.Namespace) -> None:
66
+ async with CodeMode.from_config(_config_arg(args.config), usage_tracking=False) as cm:
67
+ print(cm.search_tools(args.query, args.limit))
68
+
69
+
70
+ async def _run(args: argparse.Namespace) -> None:
71
+ code = Path(args.file).read_text(encoding="utf-8") if args.file else args.code
72
+ if not code:
73
+ raise SystemExit("Provide code as an argument or with --file")
74
+ async with CodeMode.from_config(_config_arg(args.config), approval_callback=_terminal_approver) as cm:
75
+ print(await cm.run_code(code))
76
+ ev = cm.last_event
77
+ if cm.last_run and ev:
78
+ calls = [f"{c.server}.{c.tool}" for c in cm.last_run.calls]
79
+ shown = ", ".join(calls[:6]) + (" ..." if len(calls) > 6 else "")
80
+ print(
81
+ f"\n[{len(calls)} tool call(s){': ' + shown if calls else ''}]"
82
+ f" [tokens: Code Mode {ev.codemode_tokens:,} vs classic ~{ev.classic_tokens:,}]",
83
+ file=sys.stderr,
84
+ )
85
+
86
+
87
+ async def _tools(args: argparse.Namespace) -> None:
88
+ async with CodeMode.from_config(_config_arg(args.config), usage_tracking=False) as cm:
89
+ print(json.dumps(cm.tools(args.format), indent=2))
90
+
91
+
92
+ async def _setup(args: argparse.Namespace) -> None:
93
+ from .sandbox import DenoSandbox
94
+
95
+ print("Preparing sandbox (first run downloads Pyodide, ~10 MB)...")
96
+ sb = DenoSandbox()
97
+
98
+ async def no_tools(server: str, tool: str, a: dict) -> None:
99
+ raise RuntimeError("no tools configured")
100
+
101
+ try:
102
+ r = await sb.execute("import sys; f'Python {sys.version.split()[0]} ready'", no_tools, timeout=120)
103
+ finally:
104
+ await sb.close()
105
+ print(r.result if r.ok else f"Sandbox failed: {r.error}")
106
+ if not r.ok:
107
+ raise SystemExit(1)
108
+
109
+
110
+ async def _chat(args: argparse.Namespace) -> None:
111
+ from . import agent
112
+
113
+ def on_event(kind: str, payload: Any) -> None:
114
+ if not args.verbose:
115
+ return
116
+ if kind == "tool_call":
117
+ arg = payload["arguments"]
118
+ if isinstance(arg, str):
119
+ with contextlib.suppress(Exception):
120
+ arg = json.loads(arg)
121
+ body = arg.get("code") if isinstance(arg, dict) and "code" in arg else json.dumps(arg)
122
+ print(f"\n--- {payload['name']} ---\n{body}", file=sys.stderr)
123
+ else:
124
+ text = str(payload)
125
+ print(f"--- result ---\n{text[:1500]}{'...' if len(text) > 1500 else ''}", file=sys.stderr)
126
+
127
+ async with CodeMode.from_config(_config_arg(args.config), approval_callback=_terminal_approver) as cm:
128
+ while True:
129
+ prompt = args.prompt or (await asyncio.to_thread(input, "\nyou> ")).strip()
130
+ if not prompt:
131
+ return
132
+ api_key = os.environ.get(args.api_key_env) if args.api_key_env else None
133
+ if args.provider == "anthropic":
134
+ res = await agent.run_anthropic(cm, prompt, model=args.model, api_key=api_key, on_event=on_event)
135
+ else:
136
+ res = await agent.run_openai(
137
+ cm, prompt, model=args.model, base_url=args.base_url, api_key=api_key, on_event=on_event
138
+ )
139
+ print(f"\n{res.text}")
140
+ s = cm.usage()
141
+ print(
142
+ f"\n[{res.turns} LLM turns, {res.input_tokens:,} in + {res.output_tokens:,} out tokens | "
143
+ f"tool activity: Code Mode {s['codemode_tokens']:,} vs classic ~{s['classic_tokens']:,} "
144
+ f"({s['saved_pct']}% saved)]",
145
+ file=sys.stderr,
146
+ )
147
+ if args.prompt:
148
+ return
149
+
150
+
151
+ async def _benchmark(args: argparse.Namespace) -> None:
152
+ from .benchmark import format_result, run_benchmark
153
+
154
+ async with CodeMode.from_config(_config_arg(args.config)) as cm:
155
+ api_key = os.environ.get(args.api_key_env) if args.api_key_env else None
156
+ result = await run_benchmark(
157
+ cm,
158
+ args.prompt,
159
+ model=args.model,
160
+ provider=args.provider,
161
+ base_url=args.base_url,
162
+ api_key=api_key,
163
+ max_turns=args.max_turns,
164
+ )
165
+ print(json.dumps(result.to_dict(), indent=2) if args.json else format_result(result))
166
+
167
+
168
+ async def _usage(args: argparse.Namespace) -> None:
169
+ from .dashboard import RANGES
170
+
171
+ store = _usage_store(args.config)
172
+ if args.clear:
173
+ print(f"Deleted {store.clear()} usage records from {store.path}")
174
+ return
175
+ seconds = RANGES[args.range]
176
+ s = store.summary(since=None if seconds is None else time.time() - seconds)
177
+ if args.json:
178
+ print(json.dumps(s, indent=2))
179
+ return
180
+ label = {"1d": "last 24h", "7d": "last 7 days", "30d": "last 30 days", "all": "all time"}[args.range]
181
+ print(f"codemode-mcp usage ({label}) - {store.path}\n")
182
+ print(f" Code Mode calls {s['calls']:>12,} upstream tool calls {s['upstream_calls']:,}")
183
+ print(f" Code Mode tokens {s['codemode_tokens']:>12,}")
184
+ print(f" Classic MCP (estimate) {s['classic_tokens_estimate']:>12,}")
185
+ print(f" Saved {s['saved_tokens']:>12,} ({s['saved_pct']}%)")
186
+ if s["by_kind"]:
187
+ print("\n by type calls Code Mode classic est.")
188
+ for k in s["by_kind"]:
189
+ print(f" {k['kind']:<12}{k['n']:>8,}{k['cm']:>14,}{k['cl']:>15,}")
190
+ if s["top_tools"]:
191
+ print("\n top tools: " + ", ".join(f"{t} ({n})" for t, n in s["top_tools"][:8]))
192
+ if s["llm"]["requests_logged"]:
193
+ llm = s["llm"]
194
+ print(
195
+ f"\n measured LLM usage: {llm['requests_logged']:,} requests, {llm['input_tokens']:,} in + "
196
+ f"{llm['output_tokens']:,} out tokens"
197
+ )
198
+ if s["benchmarks"]:
199
+ print("\n benchmarks (measured) model classic Code Mode saved")
200
+ for b in s["benchmarks"][:10]:
201
+ print(
202
+ f" {(b.get('prompt') or '')[:34]:<36}{(b.get('model') or '')[:18]:<18}"
203
+ f"{b['classic_tokens']:>10,}{b['codemode_tokens']:>12,}{b['saved_pct']:>7}%"
204
+ )
205
+ print("\nEstimates are conservative; see `codemode-mcp dashboard` and the README for the method.")
206
+
207
+
208
+ async def _dashboard(args: argparse.Namespace) -> None:
209
+ from .dashboard import serve_dashboard
210
+
211
+ store = _usage_store(args.config)
212
+ url = f"http://{args.host}:{args.port}/"
213
+ print(f"codemode-mcp dashboard: {url} (data: {store.path}) Ctrl+C to stop")
214
+ if not args.no_open:
215
+ import webbrowser
216
+
217
+ asyncio.get_running_loop().call_later(1.0, webbrowser.open, url)
218
+ await serve_dashboard(store, host=args.host, port=args.port)
219
+
220
+
221
+ async def _init(args: argparse.Namespace) -> None:
222
+ from . import clients
223
+
224
+ out = Path(args.output).expanduser()
225
+ if args.source:
226
+ kind, path = clients.resolve_client(args.source)
227
+ servers = clients.import_servers(kind, path)
228
+ clients.write_codemode_config(servers, out)
229
+ print(f"Imported {len(servers)} server(s) from {path} into {out}: {', '.join(servers) or '(none)'}")
230
+ else:
231
+ kind, path = "generic", None
232
+ if not out.exists():
233
+ clients.write_codemode_config({}, out)
234
+ print(f'Created {out}. Add your servers under "mcpServers".')
235
+ if args.install:
236
+ if path is None:
237
+ raise SystemExit("--install needs --from CLIENT")
238
+ backup = clients.install_into_client(kind, path, out)
239
+ print(f"Updated {path} to use codemode-mcp (backup: {backup}). Restart the client to apply.")
240
+ else:
241
+ entry = clients.serve_entry(out, kind)
242
+ key = "servers" if kind == "vscode" else "mcpServers"
243
+ print(
244
+ "\nPoint your MCP client at codemode-mcp with:\n"
245
+ + json.dumps({key: {clients.SERVER_NAME: entry}}, indent=2)
246
+ )
247
+ if args.source:
248
+ print("\n(or rerun with --install to update the client config automatically; a backup is kept)")
249
+
250
+
251
+ async def _login(args: argparse.Namespace) -> None:
252
+ from .oauth import FileTokenStorage, token_path
253
+ from .upstream import Upstreams
254
+
255
+ config = Config.load(_config_arg(args.config))
256
+ cfg = next((s for s in config.servers if s.name == args.server), None)
257
+ if cfg is None:
258
+ raise SystemExit(f"No server named {args.server!r} in the config")
259
+ if cfg.oauth is None:
260
+ raise SystemExit(f'Server {args.server!r} is not configured for OAuth (add "oauth": true)')
261
+ if args.logout:
262
+ FileTokenStorage(token_path(cfg)).clear()
263
+ print(f"Removed stored credentials for {cfg.name}")
264
+ return
265
+ ups = Upstreams([cfg], tool_call_timeout=config.settings.tool_call_timeout)
266
+ try:
267
+ catalog = await ups.start()
268
+ finally:
269
+ await ups.close()
270
+ print(f"Signed in to {cfg.name}: {len(catalog)} tools available. Tokens stored in {token_path(cfg)}")
271
+
272
+
273
+ def main(argv: list[str] | None = None) -> None:
274
+ parser = argparse.ArgumentParser(prog="codemode-mcp", description="Code Mode for MCP: fewer tokens, same tools.")
275
+ parser.add_argument("-v", "--verbose", action="store_true")
276
+ parser.add_argument("--version", action="version", version=f"%(prog)s {_version()}")
277
+ sub = parser.add_subparsers(dest="command", required=True)
278
+
279
+ def add(name: str, help: str) -> argparse.ArgumentParser:
280
+ p = sub.add_parser(name, help=help)
281
+ p.add_argument("-c", "--config", help="mcp.json path (default: ./mcp.json, ./.mcp.json, ./.vscode/mcp.json)")
282
+ return p
283
+
284
+ def llm_args(p: argparse.ArgumentParser) -> None:
285
+ p.add_argument("-m", "--model", required=True)
286
+ p.add_argument(
287
+ "--provider",
288
+ choices=["openai", "anthropic"],
289
+ default="openai",
290
+ help="'openai' covers any OpenAI-compatible API via --base-url",
291
+ )
292
+ p.add_argument("--base-url", help="OpenAI-compatible endpoint (Ollama, OpenRouter, GitHub Models, ...)")
293
+ p.add_argument("--api-key-env", help="Env var holding the API key (default: provider SDK default)")
294
+
295
+ p = add("serve", "Run as an MCP server proxying the configured servers")
296
+ p.add_argument("--transport", choices=["stdio", "http"], default="stdio")
297
+ p.add_argument("--host", default="127.0.0.1")
298
+ p.add_argument("--port", type=int, default=8000)
299
+ p.add_argument("--dashboard-port", type=int, help="Also serve the usage dashboard on this port")
300
+
301
+ p = add("stats", "Compare tool-definition token cost: classic MCP vs Code Mode")
302
+ p.add_argument("--json", action="store_true")
303
+
304
+ p = add("usage", "Show token usage and savings recorded so far")
305
+ p.add_argument("--range", choices=["1d", "7d", "30d", "all"], default="7d")
306
+ p.add_argument("--json", action="store_true")
307
+ p.add_argument("--clear", action="store_true", help="Delete all recorded usage")
308
+
309
+ p = add("dashboard", "Open the local savings dashboard in your browser")
310
+ p.add_argument("--host", default="127.0.0.1")
311
+ p.add_argument("--port", type=int, default=8765)
312
+ p.add_argument("--no-open", action="store_true")
313
+
314
+ p = add("benchmark", "Run a prompt via classic MCP and via Code Mode with a real LLM; compare measured tokens")
315
+ p.add_argument("prompt")
316
+ llm_args(p)
317
+ p.add_argument("--max-turns", type=int, default=25)
318
+ p.add_argument("--json", action="store_true")
319
+
320
+ p = add("search", "Search tools and print their Python signatures")
321
+ p.add_argument("query")
322
+ p.add_argument("--limit", type=int, default=8)
323
+
324
+ p = add("run", "Execute Python code against the configured tools")
325
+ p.add_argument("code", nargs="?")
326
+ p.add_argument("-f", "--file")
327
+
328
+ p = add("tools", "Print the tool definitions given to the LLM")
329
+ p.add_argument("--format", default="openai", choices=["openai", "openai-responses", "anthropic", "mcp"])
330
+
331
+ p = add("chat", "Chat with an LLM that uses the tools through Code Mode")
332
+ p.add_argument("prompt", nargs="?", help="One-shot prompt (omit for interactive mode)")
333
+ llm_args(p)
334
+
335
+ p = sub.add_parser("init", help="Create mcp.json, optionally importing servers from an MCP client")
336
+ p.add_argument("--from", dest="source", help="claude | cursor | vscode | windsurf | path/to/config.json")
337
+ p.add_argument("-o", "--output", default="mcp.json")
338
+ p.add_argument("--install", action="store_true", help="Point the client at codemode-mcp (keeps a backup)")
339
+
340
+ p = add("login", "Sign in to an OAuth-protected remote MCP server")
341
+ p.add_argument("server")
342
+ p.add_argument("--logout", action="store_true", help="Forget stored credentials instead")
343
+
344
+ sub.add_parser("setup", help="Download Pyodide and verify the sandbox works")
345
+
346
+ args = parser.parse_args(argv)
347
+ logging.basicConfig(
348
+ level=logging.DEBUG if args.verbose else logging.WARNING,
349
+ stream=sys.stderr,
350
+ format="%(levelname)s %(name)s: %(message)s",
351
+ )
352
+ if args.command == "serve":
353
+ from .server import serve
354
+
355
+ runner = serve(
356
+ _config_arg(args.config),
357
+ transport=args.transport,
358
+ host=args.host,
359
+ port=args.port,
360
+ dashboard_port=args.dashboard_port,
361
+ )
362
+ else:
363
+ runner = {
364
+ "stats": _stats,
365
+ "search": _search,
366
+ "run": _run,
367
+ "tools": _tools,
368
+ "chat": _chat,
369
+ "setup": _setup,
370
+ "usage": _usage,
371
+ "dashboard": _dashboard,
372
+ "benchmark": _benchmark,
373
+ "init": _init,
374
+ "login": _login,
375
+ }[args.command](args)
376
+ try:
377
+ asyncio.run(runner)
378
+ except ConfigError as e:
379
+ raise SystemExit(f"Config error: {e}") from None
380
+ except (FileNotFoundError, ValueError) as e:
381
+ if args.verbose:
382
+ raise
383
+ raise SystemExit(f"Error: {e}") from None
384
+ except KeyboardInterrupt:
385
+ pass
386
+
387
+
388
+ def _version() -> str:
389
+ from . import __version__
390
+
391
+ return __version__
392
+
393
+
394
+ if __name__ == "__main__":
395
+ main()
@@ -0,0 +1,106 @@
1
+ """Import MCP servers from popular clients and point those clients at codemode-mcp."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import sys
9
+ import time
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ SERVER_NAME = "codemode"
14
+
15
+
16
+ def _appdata() -> Path:
17
+ return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
18
+
19
+
20
+ def client_config_paths() -> dict[str, list[Path]]:
21
+ home = Path.home()
22
+ if sys.platform == "win32":
23
+ claude = [_appdata() / "Claude" / "claude_desktop_config.json"]
24
+ vscode_user = [_appdata() / "Code" / "User" / "mcp.json"]
25
+ elif sys.platform == "darwin":
26
+ claude = [home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"]
27
+ vscode_user = [home / "Library" / "Application Support" / "Code" / "User" / "mcp.json"]
28
+ else:
29
+ claude = [home / ".config" / "Claude" / "claude_desktop_config.json"]
30
+ vscode_user = [home / ".config" / "Code" / "User" / "mcp.json"]
31
+ return {
32
+ "claude": claude,
33
+ "cursor": [Path(".cursor") / "mcp.json", home / ".cursor" / "mcp.json"],
34
+ "vscode": [Path(".vscode") / "mcp.json", *vscode_user],
35
+ "windsurf": [home / ".codeium" / "windsurf" / "mcp_config.json"],
36
+ }
37
+
38
+
39
+ def _servers_key(client: str, data: dict[str, Any]) -> str:
40
+ if "servers" in data and "mcpServers" not in data:
41
+ return "servers"
42
+ return "servers" if client == "vscode" and "mcpServers" not in data else "mcpServers"
43
+
44
+
45
+ def resolve_client(source: str) -> tuple[str, Path]:
46
+ """Return (client kind, existing config path) for a client name or a file path."""
47
+ candidate = Path(source).expanduser()
48
+ if candidate.suffix == ".json" or candidate.exists():
49
+ if not candidate.exists():
50
+ raise FileNotFoundError(f"{candidate} does not exist")
51
+ kind = "vscode" if candidate.parent.name == ".vscode" or candidate.parent.name == "User" else "generic"
52
+ return kind, candidate
53
+ paths = client_config_paths().get(source.lower())
54
+ if paths is None:
55
+ raise ValueError(f"unknown client {source!r}; use one of {', '.join(client_config_paths())} or a file path")
56
+ for p in paths:
57
+ if p.exists():
58
+ return source.lower(), p
59
+ raise FileNotFoundError(f"no {source} MCP config found (looked in: {', '.join(str(p) for p in paths)})")
60
+
61
+
62
+ def serve_entry(config_path: Path, client: str) -> dict[str, Any]:
63
+ entry: dict[str, Any] = {
64
+ "command": sys.executable,
65
+ "args": ["-m", "codemode_mcp", "serve", "-c", str(config_path.resolve())],
66
+ }
67
+ if client == "vscode":
68
+ entry = {"type": "stdio", **entry}
69
+ return entry
70
+
71
+
72
+ def import_servers(client: str, path: Path) -> dict[str, Any]:
73
+ data = json.loads(path.read_text(encoding="utf-8"))
74
+ servers = dict(data.get(_servers_key(client, data)) or {})
75
+ # Don't import ourselves.
76
+ return {
77
+ name: spec
78
+ for name, spec in servers.items()
79
+ if not (isinstance(spec, dict) and "codemode_mcp" in " ".join(map(str, spec.get("args") or [])))
80
+ }
81
+
82
+
83
+ def write_codemode_config(servers: dict[str, Any], out: Path) -> dict[str, Any]:
84
+ existing: dict[str, Any] = {}
85
+ if out.exists():
86
+ existing = json.loads(out.read_text(encoding="utf-8"))
87
+ merged = dict(existing.get("mcpServers") or {})
88
+ for name, spec in servers.items():
89
+ spec = {k: v for k, v in spec.items() if k != "type" or v in ("http", "sse", "streamable-http")}
90
+ merged[name] = spec
91
+ existing["mcpServers"] = merged
92
+ existing.setdefault("codemode", {})
93
+ out.parent.mkdir(parents=True, exist_ok=True)
94
+ out.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
95
+ return existing
96
+
97
+
98
+ def install_into_client(client: str, path: Path, config_path: Path) -> Path:
99
+ """Replace the client's servers with a single codemode entry. Returns the backup path."""
100
+ data = json.loads(path.read_text(encoding="utf-8"))
101
+ key = _servers_key(client, data)
102
+ backup = path.with_name(f"{path.name}.bak-{time.strftime('%Y%m%d-%H%M%S')}")
103
+ shutil.copy2(path, backup)
104
+ data[key] = {SERVER_NAME: serve_entry(config_path, client)}
105
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
106
+ return backup