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,19 @@
1
+ """Code Mode for MCP: expose MCP servers to LLMs as a sandboxed Python API."""
2
+
3
+ from .config import Config, ConfigError, ServerConfig, Settings
4
+ from .core import CodeMode
5
+ from .sandbox import DenoSandbox, ExecResult
6
+ from .usage import UsageEvent, UsageStore
7
+
8
+ __all__ = [
9
+ "CodeMode",
10
+ "Config",
11
+ "ConfigError",
12
+ "DenoSandbox",
13
+ "ExecResult",
14
+ "ServerConfig",
15
+ "Settings",
16
+ "UsageEvent",
17
+ "UsageStore",
18
+ ]
19
+ __version__ = "0.2.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
codemode_mcp/agent.py ADDED
@@ -0,0 +1,127 @@
1
+ """Minimal agent loops wiring ``CodeMode`` to an LLM.
2
+
3
+ These are conveniences; ``CodeMode.tools()`` + ``CodeMode.call()`` work with any framework.
4
+ Install the provider SDK you need: ``pip install "codemode-mcp[openai]"`` or ``[anthropic]``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from .core import CodeMode
14
+
15
+
16
+ @dataclass
17
+ class AgentResult:
18
+ text: str
19
+ turns: int
20
+ input_tokens: int = 0
21
+ output_tokens: int = 0
22
+ tool_calls: list[dict[str, Any]] = field(default_factory=list)
23
+
24
+
25
+ async def run_openai(
26
+ cm: CodeMode,
27
+ prompt: str,
28
+ *,
29
+ model: str,
30
+ client: Any = None,
31
+ base_url: str | None = None,
32
+ api_key: str | None = None,
33
+ system: str | None = None,
34
+ max_turns: int = 12,
35
+ on_event: Callable[[str, Any], None] | None = None,
36
+ record_usage: bool = True,
37
+ ) -> AgentResult:
38
+ """Run a tool-calling loop against any OpenAI-compatible Chat Completions API
39
+ (OpenAI, Azure, GitHub Models, OpenRouter, Ollama, vLLM, LM Studio, ...)."""
40
+ if client is None:
41
+ from openai import AsyncOpenAI
42
+
43
+ client = AsyncOpenAI(base_url=base_url, api_key=api_key)
44
+ messages: list[dict[str, Any]] = [
45
+ {"role": "system", "content": (system + "\n\n" if system else "") + cm.system_prompt},
46
+ {"role": "user", "content": prompt},
47
+ ]
48
+ tools = cm.tools("openai")
49
+ result = AgentResult(text="", turns=0)
50
+ for _ in range(max_turns):
51
+ result.turns += 1
52
+ resp = await client.chat.completions.create(model=model, messages=messages, tools=tools)
53
+ if resp.usage:
54
+ result.input_tokens += resp.usage.prompt_tokens or 0
55
+ result.output_tokens += resp.usage.completion_tokens or 0
56
+ if record_usage:
57
+ cm.record_llm_usage(model, resp.usage.prompt_tokens or 0, resp.usage.completion_tokens or 0)
58
+ msg = resp.choices[0].message
59
+ if not msg.tool_calls:
60
+ result.text = msg.content or ""
61
+ return result
62
+ messages.append(msg.model_dump(exclude_none=True))
63
+ for tc in msg.tool_calls:
64
+ if on_event:
65
+ on_event("tool_call", {"name": tc.function.name, "arguments": tc.function.arguments})
66
+ reply = await cm.handle_openai_tool_call(tc)
67
+ result.tool_calls.append(
68
+ {"name": tc.function.name, "arguments": tc.function.arguments, "output": reply["content"]}
69
+ )
70
+ if on_event:
71
+ on_event("tool_result", reply["content"])
72
+ messages.append(reply)
73
+ result.text = "(stopped: max_turns reached)"
74
+ return result
75
+
76
+
77
+ async def run_anthropic(
78
+ cm: CodeMode,
79
+ prompt: str,
80
+ *,
81
+ model: str,
82
+ client: Any = None,
83
+ api_key: str | None = None,
84
+ system: str | None = None,
85
+ max_turns: int = 12,
86
+ max_tokens: int = 4096,
87
+ on_event: Callable[[str, Any], None] | None = None,
88
+ record_usage: bool = True,
89
+ ) -> AgentResult:
90
+ """Run a tool-calling loop against the Anthropic Messages API."""
91
+ if client is None:
92
+ from anthropic import AsyncAnthropic
93
+
94
+ client = AsyncAnthropic(api_key=api_key)
95
+ messages: list[dict[str, Any]] = [{"role": "user", "content": prompt}]
96
+ tools = cm.tools("anthropic")
97
+ result = AgentResult(text="", turns=0)
98
+ for _ in range(max_turns):
99
+ result.turns += 1
100
+ resp = await client.messages.create(
101
+ model=model,
102
+ max_tokens=max_tokens,
103
+ system=(system + "\n\n" if system else "") + cm.system_prompt,
104
+ messages=messages,
105
+ tools=tools,
106
+ )
107
+ result.input_tokens += resp.usage.input_tokens
108
+ result.output_tokens += resp.usage.output_tokens
109
+ if record_usage:
110
+ cm.record_llm_usage(model, resp.usage.input_tokens, resp.usage.output_tokens)
111
+ uses = [b for b in resp.content if b.type == "tool_use"]
112
+ if not uses:
113
+ result.text = "".join(b.text for b in resp.content if b.type == "text")
114
+ return result
115
+ messages.append({"role": "assistant", "content": [b.model_dump(exclude_none=True) for b in resp.content]})
116
+ results = []
117
+ for block in uses:
118
+ if on_event:
119
+ on_event("tool_call", {"name": block.name, "arguments": block.input})
120
+ reply = await cm.handle_anthropic_tool_use(block)
121
+ result.tool_calls.append({"name": block.name, "arguments": block.input, "output": reply["content"]})
122
+ if on_event:
123
+ on_event("tool_result", reply["content"])
124
+ results.append(reply)
125
+ messages.append({"role": "user", "content": results})
126
+ result.text = "(stopped: max_turns reached)"
127
+ return result
@@ -0,0 +1,230 @@
1
+ """Head-to-head benchmark: the same prompt via classic MCP tool calling vs Code Mode.
2
+
3
+ Both runs use the same model and the same upstream servers; token counts come from the
4
+ LLM provider's usage reports, so the comparison is *measured*, not estimated. Results are
5
+ stored in the usage database and shown on the dashboard.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import time
12
+ from dataclasses import asdict, dataclass
13
+ from typing import Any
14
+
15
+ from .agent import run_anthropic, run_openai
16
+ from .core import CodeMode
17
+ from .usage import UsageEvent
18
+
19
+
20
+ @dataclass
21
+ class RunStats:
22
+ answer: str
23
+ turns: int
24
+ tool_calls: int
25
+ input_tokens: int
26
+ output_tokens: int
27
+ seconds: float
28
+
29
+ @property
30
+ def total(self) -> int:
31
+ return self.input_tokens + self.output_tokens
32
+
33
+
34
+ @dataclass
35
+ class BenchmarkResult:
36
+ prompt: str
37
+ model: str
38
+ classic: RunStats
39
+ codemode: RunStats
40
+
41
+ @property
42
+ def saved_pct(self) -> float:
43
+ return round(100 * (1 - self.codemode.total / self.classic.total), 1) if self.classic.total else 0.0
44
+
45
+ def to_dict(self) -> dict[str, Any]:
46
+ return {
47
+ "prompt": self.prompt,
48
+ "model": self.model,
49
+ "saved_pct": self.saved_pct,
50
+ "classic": asdict(self.classic),
51
+ "codemode": asdict(self.codemode),
52
+ }
53
+
54
+
55
+ def _classic_name(server: str, tool: str) -> str:
56
+ return f"{server}__{tool}"[:64]
57
+
58
+
59
+ async def _classic_openai(cm: CodeMode, prompt: str, model: str, client: Any, max_turns: int) -> RunStats:
60
+ specs = {_classic_name(t.py_server, t.py_name): t for t in cm.catalog.tools}
61
+ tools = [
62
+ {
63
+ "type": "function",
64
+ "function": {
65
+ "name": n,
66
+ "description": t.description or t.name,
67
+ "parameters": t.input_schema or {"type": "object", "properties": {}},
68
+ },
69
+ }
70
+ for n, t in specs.items()
71
+ ]
72
+ messages: list[dict[str, Any]] = [{"role": "user", "content": prompt}]
73
+ stats = RunStats("", 0, 0, 0, 0, 0.0)
74
+ start = time.perf_counter()
75
+ for _ in range(max_turns):
76
+ stats.turns += 1
77
+ resp = await client.chat.completions.create(model=model, messages=messages, tools=tools)
78
+ if resp.usage:
79
+ stats.input_tokens += resp.usage.prompt_tokens or 0
80
+ stats.output_tokens += resp.usage.completion_tokens or 0
81
+ msg = resp.choices[0].message
82
+ if not msg.tool_calls:
83
+ stats.answer = msg.content or ""
84
+ break
85
+ messages.append(msg.model_dump(exclude_none=True))
86
+ for tc in msg.tool_calls:
87
+ stats.tool_calls += 1
88
+ messages.append(
89
+ {
90
+ "role": "tool",
91
+ "tool_call_id": tc.id,
92
+ "content": await _classic_call(cm, specs, tc.function.name, tc.function.arguments),
93
+ }
94
+ )
95
+ else:
96
+ stats.answer = "(stopped: max_turns reached)"
97
+ stats.seconds = round(time.perf_counter() - start, 2)
98
+ return stats
99
+
100
+
101
+ async def _classic_anthropic(cm: CodeMode, prompt: str, model: str, client: Any, max_turns: int) -> RunStats:
102
+ specs = {_classic_name(t.py_server, t.py_name): t for t in cm.catalog.tools}
103
+ tools = [
104
+ {
105
+ "name": n,
106
+ "description": t.description or t.name,
107
+ "input_schema": t.input_schema or {"type": "object", "properties": {}},
108
+ }
109
+ for n, t in specs.items()
110
+ ]
111
+ messages: list[dict[str, Any]] = [{"role": "user", "content": prompt}]
112
+ stats = RunStats("", 0, 0, 0, 0, 0.0)
113
+ start = time.perf_counter()
114
+ for _ in range(max_turns):
115
+ stats.turns += 1
116
+ resp = await client.messages.create(model=model, max_tokens=4096, messages=messages, tools=tools)
117
+ stats.input_tokens += resp.usage.input_tokens
118
+ stats.output_tokens += resp.usage.output_tokens
119
+ uses = [b for b in resp.content if b.type == "tool_use"]
120
+ if not uses:
121
+ stats.answer = "".join(b.text for b in resp.content if b.type == "text")
122
+ break
123
+ messages.append({"role": "assistant", "content": [b.model_dump(exclude_none=True) for b in resp.content]})
124
+ results = []
125
+ for b in uses:
126
+ stats.tool_calls += 1
127
+ results.append(
128
+ {"type": "tool_result", "tool_use_id": b.id, "content": await _classic_call(cm, specs, b.name, b.input)}
129
+ )
130
+ messages.append({"role": "user", "content": results})
131
+ else:
132
+ stats.answer = "(stopped: max_turns reached)"
133
+ stats.seconds = round(time.perf_counter() - start, 2)
134
+ return stats
135
+
136
+
137
+ async def _classic_call(cm: CodeMode, specs: dict[str, Any], name: str, arguments: Any) -> str:
138
+ spec = specs.get(name)
139
+ if spec is None:
140
+ return f"Error: unknown tool {name!r}"
141
+ try:
142
+ args = json.loads(arguments or "{}") if isinstance(arguments, str) else dict(arguments or {})
143
+ result = await cm.upstreams.call_raw(spec.server, spec.name, args)
144
+ except Exception as e: # noqa: BLE001
145
+ return f"Error: {e}"
146
+ from .core import content_to_text
147
+
148
+ return content_to_text(result)
149
+
150
+
151
+ async def run_benchmark(
152
+ cm: CodeMode,
153
+ prompt: str,
154
+ *,
155
+ model: str,
156
+ provider: str = "openai",
157
+ client: Any = None,
158
+ base_url: str | None = None,
159
+ api_key: str | None = None,
160
+ max_turns: int = 25,
161
+ ) -> BenchmarkResult:
162
+ if client is None:
163
+ if provider == "anthropic":
164
+ from anthropic import AsyncAnthropic
165
+
166
+ client = AsyncAnthropic(api_key=api_key)
167
+ else:
168
+ from openai import AsyncOpenAI
169
+
170
+ client = AsyncOpenAI(base_url=base_url, api_key=api_key)
171
+
172
+ if provider == "anthropic":
173
+ classic = await _classic_anthropic(cm, prompt, model, client, max_turns)
174
+ else:
175
+ classic = await _classic_openai(cm, prompt, model, client, max_turns)
176
+
177
+ start = time.perf_counter()
178
+ runner = run_anthropic if provider == "anthropic" else run_openai
179
+ res = await runner(cm, prompt, model=model, client=client, max_turns=max_turns, record_usage=False)
180
+ codemode = RunStats(
181
+ res.text,
182
+ res.turns,
183
+ len(res.tool_calls),
184
+ res.input_tokens,
185
+ res.output_tokens,
186
+ round(time.perf_counter() - start, 2),
187
+ )
188
+
189
+ result = BenchmarkResult(prompt, model, classic, codemode)
190
+ cm.tracker.record(
191
+ UsageEvent(
192
+ kind="benchmark",
193
+ measured=True,
194
+ codemode_tokens=codemode.total,
195
+ classic_tokens=classic.total,
196
+ upstream_calls=classic.tool_calls,
197
+ ok=True,
198
+ duration_ms=int(1000 * (classic.seconds + codemode.seconds)),
199
+ details={
200
+ "prompt": prompt[:200],
201
+ "model": model,
202
+ "provider": provider,
203
+ "classic_turns": classic.turns,
204
+ "codemode_turns": codemode.turns,
205
+ "classic_input": classic.input_tokens,
206
+ "classic_output": classic.output_tokens,
207
+ "codemode_input": codemode.input_tokens,
208
+ "codemode_output": codemode.output_tokens,
209
+ },
210
+ )
211
+ )
212
+ return result
213
+
214
+
215
+ def format_result(r: BenchmarkResult) -> str:
216
+ rows = [
217
+ ("LLM turns", r.classic.turns, r.codemode.turns),
218
+ ("tool calls seen by LLM", r.classic.tool_calls, r.codemode.tool_calls),
219
+ ("input tokens", r.classic.input_tokens, r.codemode.input_tokens),
220
+ ("output tokens", r.classic.output_tokens, r.codemode.output_tokens),
221
+ ("total tokens", r.classic.total, r.codemode.total),
222
+ ("seconds", r.classic.seconds, r.codemode.seconds),
223
+ ]
224
+ lines = [f"Model: {r.model}", f"{'':26}{'classic MCP':>14}{'Code Mode':>14}"]
225
+ lines += [
226
+ f"{label:26}{a:>14,}{b:>14,}" if isinstance(a, int) else f"{label:26}{a:>14}{b:>14}" for label, a, b in rows
227
+ ]
228
+ lines.append(f"\nCode Mode used {r.saved_pct}% {'fewer' if r.saved_pct >= 0 else 'MORE'} tokens (measured).")
229
+ lines.append(f"\nClassic answer:\n{r.classic.answer.strip()}\n\nCode Mode answer:\n{r.codemode.answer.strip()}")
230
+ return "\n".join(lines)