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,291 @@
1
+ Metadata-Version: 2.4
2
+ Name: codemode-mcp
3
+ Version: 0.2.0
4
+ Summary: Code Mode for MCP: give LLMs every tool of every MCP server as a sandboxed Python API, for a fraction of the tokens.
5
+ Keywords: mcp,model-context-protocol,llm,agents,code-mode,tool-calling,pyodide,tokens
6
+ Author: roy-shivam164
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Framework :: AsyncIO
20
+ Classifier: Typing :: Typed
21
+ Requires-Dist: deno>=2.4
22
+ Requires-Dist: mcp>=2.3,<3
23
+ Requires-Dist: openai>=1.40 ; extra == 'all'
24
+ Requires-Dist: anthropic>=0.40 ; extra == 'all'
25
+ Requires-Dist: tiktoken>=0.7 ; extra == 'all'
26
+ Requires-Dist: anthropic>=0.40 ; extra == 'anthropic'
27
+ Requires-Dist: openai>=1.40 ; extra == 'openai'
28
+ Requires-Dist: tiktoken>=0.7 ; extra == 'tokens'
29
+ Requires-Python: >=3.11
30
+ Project-URL: Documentation, https://codemode-mcp.vercel.app/
31
+ Project-URL: Changelog, https://codemode-mcp.vercel.app/changelog/
32
+ Project-URL: Security policy, https://codemode-mcp.vercel.app/security/
33
+ Provides-Extra: all
34
+ Provides-Extra: anthropic
35
+ Provides-Extra: openai
36
+ Provides-Extra: tokens
37
+ Description-Content-Type: text/markdown
38
+
39
+ # codemode-mcp
40
+
41
+ **Code Mode for MCP, in Python.** Put any number of MCP servers behind one or two small
42
+ tools. The LLM writes a short Python script that calls your tools as typed async
43
+ functions; the script runs in a locked-down WebAssembly sandbox and only the final,
44
+ compact result goes back to the model. A built-in **savings dashboard** shows how many
45
+ tokens that saved compared with classic MCP.
46
+
47
+ **Documentation: <https://codemode-mcp.vercel.app/>**
48
+
49
+ ```
50
+ classic MCP codemode-mcp
51
+ LLM - tool schemas (every request, all tools) LLM - 1-2 tiny tool definitions
52
+ | <- result 1 (raw JSON into context) | -> run_code("""
53
+ | -> call 2 | for c in await shop.list_customers():
54
+ | <- result 2 (raw JSON into context) | ... await shop.get_orders(c["id"])
55
+ | ... N round-trips | top3 """)
56
+ | | <- [["Customer 8", 12086], ...] (only this)
57
+ ```
58
+
59
+ ## Why it saves tokens
60
+
61
+ | Cost driver | Classic MCP | codemode-mcp |
62
+ |---|---|---|
63
+ | Tool definitions | Every tool's JSON schema, on every request | Bounded at ~1-2k tokens regardless of API size; signatures fetched on demand |
64
+ | Intermediate results | Every raw result goes through the LLM context | Stays in the sandbox |
65
+ | Loops, filters, joins | One LLM turn per step | Plain Python in one execution |
66
+ | LLM round-trips | N | Usually 1-3 |
67
+
68
+ Measured with the bundled examples (tiktoken `o200k_base`):
69
+
70
+ | Scenario | Classic MCP | codemode-mcp | Saved |
71
+ |---|---|---|---|
72
+ | 306 tools: definitions per request (`codemode-mcp stats -c examples/mcp.big.json`) | 78,933 | 1,505 | **98.1%** |
73
+ | "Top 3 Indian customers by spend", 14 tool calls, total input (`python examples/benchmark.py`) | 8,463 | 1,302 | **84.6%** |
74
+
75
+ Run `codemode-mcp benchmark` to measure the same thing with your own servers, prompt and LLM.
76
+
77
+ ## Install
78
+
79
+ ```bash
80
+ pip install codemode-mcp # brings its own Deno runtime via the `deno` wheel
81
+ pip install "codemode-mcp[all]" # + OpenAI & Anthropic SDKs and tiktoken for exact token counts
82
+ codemode-mcp setup # one-time: downloads Pyodide (~10 MB) and checks the sandbox
83
+ ```
84
+
85
+ Or without installing: `uvx codemode-mcp serve -c mcp.json`, or Docker (see below).
86
+
87
+ ## Quick start: use it with the MCP client you already have
88
+
89
+ ```bash
90
+ codemode-mcp init --from claude # or cursor | vscode | windsurf | path/to/config.json
91
+ codemode-mcp init --from claude --install # also points Claude Desktop at codemode-mcp (keeps a backup)
92
+ ```
93
+
94
+ `init` copies your client's servers into `mcp.json` and prints, or with `--install`
95
+ writes, the single entry the client needs. Restart the client, and all your tools now go
96
+ through Code Mode. See [the client guide](https://codemode-mcp.vercel.app/guides/mcp-clients/) for manual configs for Claude
97
+ Desktop, VS Code, Cursor, Windsurf and others.
98
+
99
+ ## Configure
100
+
101
+ Use the same `mcp.json` format your MCP client uses, with an optional `codemode` block:
102
+
103
+ ```json
104
+ {
105
+ "mcpServers": {
106
+ "github": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"],
107
+ "env": {"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"}},
108
+ "linear": {"url": "https://mcp.linear.app/mcp", "oauth": true},
109
+ "docs": {"url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ${DOCS_TOKEN}"}},
110
+ "legacy": {"type": "sse", "url": "https://example.com/sse", "exclude_tools": ["drop_database"]}
111
+ },
112
+ "codemode": {
113
+ "require_approval": ["*.delete_*", "github.merge_pull_request"],
114
+ "expose_tools": ["github.get_me"],
115
+ "timeout": 30
116
+ }
117
+ }
118
+ ```
119
+
120
+ Per server:
121
+ - `${VAR}` and `${VAR:-default}` are filled in from environment variables.
122
+ - `include_tools` / `exclude_tools` limit which tools are available.
123
+ - `"disabled": true` skips the server.
124
+ - `"oauth": true` (or an object with `client_id`, `client_secret`, `scopes`, `redirect_port`) turns on OAuth sign-in for remote servers.
125
+
126
+ | `codemode` setting | Default | Meaning |
127
+ |---|---|---|
128
+ | `require_approval` | `[]` | `server.tool` globs that need a human "yes" before each call (see [Approvals](#approvals)) |
129
+ | `expose_tools` | `[]` | Hybrid mode: these tools are *also* exposed directly, as regular MCP tools |
130
+ | `persistent_state` | `false` | Keep Python variables between `run_code` calls |
131
+ | `timeout` | 30 | Seconds per `run_code` (paused while waiting for approval; the sandbox is reset if exceeded) |
132
+ | `tool_call_timeout` | 60 | Seconds per upstream tool call |
133
+ | `max_tool_calls` | 200 | Upstream calls allowed per `run_code` |
134
+ | `max_output_chars` | 20000 | Output returned to the LLM is truncated beyond this |
135
+ | `inline_catalog_tokens` | 1500 | If all signatures fit, embed them and expose only `run_code` |
136
+ | `inline_names_tokens` | 1500 | Otherwise embed the tool-name list if it fits |
137
+ | `max_search_results` / `max_description_chars` | 8 / 600 | Search output size |
138
+ | `usage_tracking` / `usage_db` | `true` / `~/.codemode-mcp/usage.db` | Token accounting for the dashboard (counts only) |
139
+ | `tokenizer` | `auto` | `tiktoken` if installed, else ~4 chars per token |
140
+ | `audit_log` | none | JSONL file recording each run's code, upstream calls (with arguments) and output |
141
+ | `memory_mb` | 512 | V8 heap limit of the sandbox process |
142
+
143
+ ## Use it
144
+
145
+ ### 1. As an MCP server (works with Claude Desktop, VS Code, Cursor, Copilot and others)
146
+
147
+ ```json
148
+ {"mcpServers": {"codemode": {"command": "codemode-mcp", "args": ["serve", "-c", "/path/to/mcp.json"]}}}
149
+ ```
150
+
151
+ The proxy exposes:
152
+ - `run_code`, plus `search_tools` when the catalog is large;
153
+ - any hybrid `expose_tools`;
154
+ - upstream **prompts and resources**, passed through unchanged.
155
+
156
+ `codemode-mcp serve --transport http --port 8000` serves Streamable HTTP, with the
157
+ dashboard at `/dashboard/`.
158
+
159
+ ### 2. As a Python library, with any LLM
160
+
161
+ ```python
162
+ import asyncio
163
+ from openai import AsyncOpenAI
164
+ from codemode_mcp import CodeMode
165
+
166
+
167
+ async def main():
168
+ async with CodeMode.from_config("mcp.json") as cm:
169
+ client = AsyncOpenAI()
170
+ messages = [
171
+ {"role": "system", "content": cm.system_prompt},
172
+ {"role": "user", "content": "Which of my repos have open PRs older than 30 days?"},
173
+ ]
174
+ while True:
175
+ resp = await client.chat.completions.create(model="gpt-4.1", messages=messages, tools=cm.tools("openai"))
176
+ msg = resp.choices[0].message
177
+ if not msg.tool_calls:
178
+ print(msg.content)
179
+ break
180
+ messages.append(msg)
181
+ for tc in msg.tool_calls:
182
+ messages.append(await cm.handle_openai_tool_call(tc))
183
+ print(cm.usage()) # {'codemode_tokens': ..., 'classic_tokens': ..., 'saved_pct': ...}
184
+
185
+
186
+ asyncio.run(main())
187
+ ```
188
+
189
+ You can also use the ready-made loops:
190
+ `await run_openai(cm, prompt, model=..., base_url=...)` (any OpenAI-compatible API,
191
+ including Ollama, OpenRouter, Azure and GitHub Models) or `await run_anthropic(cm, prompt, model=...)`.
192
+ Other frameworks only need `cm.tools(format)` (`openai`, `openai-responses`, `anthropic`
193
+ or `mcp`) and `await cm.call(name, arguments)`.
194
+
195
+ ### 3. From the CLI
196
+
197
+ ```bash
198
+ codemode-mcp chat -c mcp.json -m gpt-4.1-mini -v "Summarise my open issues"
199
+ codemode-mcp chat -c mcp.json -m llama3.1 --base-url http://localhost:11434/v1
200
+ codemode-mcp run -c mcp.json "len(await github.list_repos(owner='me'))"
201
+ codemode-mcp search -c mcp.json "create issue" # what the LLM sees from search_tools
202
+ codemode-mcp tools -c mcp.json --format anthropic
203
+ codemode-mcp login -c mcp.json linear # OAuth sign-in ahead of time (optional)
204
+ ```
205
+
206
+ ## Monitoring: see what you saved
207
+
208
+ ```bash
209
+ codemode-mcp usage # summary in the terminal (--range 1d|7d|30d|all, --json)
210
+ codemode-mcp dashboard # local web dashboard at http://127.0.0.1:8765
211
+ codemode-mcp serve --dashboard-port 8765 # dashboard alongside a stdio server
212
+ codemode-mcp benchmark -c mcp.json -m gpt-4.1-mini "Find my 3 biggest customers in India"
213
+ ```
214
+
215
+ The dashboard shows:
216
+ - tokens used by Code Mode against a conservative estimate for classic MCP;
217
+ - savings per day, by call type and by tool;
218
+ - recent activity;
219
+ - measured benchmarks.
220
+
221
+ `benchmark` runs **the same prompt through a real LLM twice**: once with classic tool
222
+ calling (every upstream tool exposed) and once with Code Mode. It reports the provider's
223
+ actual token counts, turns and answers, and records the result for the dashboard. How the
224
+ estimates are calculated, and their limits, is described in
225
+ [the monitoring guide](https://codemode-mcp.vercel.app/monitoring/). Only counts and tool names are stored, never
226
+ code, arguments or results.
227
+
228
+ ## What the model sees
229
+
230
+ ```python
231
+ class shop:
232
+ async def list_customers(
233
+ *, country: str | None = None, tier: Literal["free", "pro", "enterprise"] | None = None
234
+ ) -> list[dict]:
235
+ """List customers, optionally filtered by ISO country code and/or tier."""
236
+
237
+ async def get_orders(customer_id: int) -> list[dict]:
238
+ """Get all orders for a customer, including line items and totals."""
239
+ ```
240
+
241
+ Inside `run_code`:
242
+ - Each server is a global object, and its tools are async functions. Names are turned into
243
+ valid Python identifiers (`send-email` becomes `send_email`).
244
+ - `await resources.list()` and `await resources.read(uri)` give access to MCP resources.
245
+ - Top-level `await` and `asyncio.gather` work.
246
+ - The last expression is returned as JSON, along with any `print()` output.
247
+ - A failed tool call raises `ToolError`.
248
+
249
+ ## Approvals
250
+
251
+ Tools that match `require_approval` pause the script until a person answers:
252
+
253
+ - **MCP server mode:** the question goes to the user through MCP *elicitation*.
254
+ - On 2026-07-28+ connections the sandbox run is **suspended** and resumed after the
255
+ client's retry, so tool calls made before the approval point are never repeated.
256
+ - Clients that don't support elicitation get a clear error instead of a silent call.
257
+ - **CLI (`run`, `chat`):** a y/N prompt in the terminal.
258
+ - **Library:** pass `approval_callback=async (server, tool, args) -> bool`.
259
+
260
+ ## Security model
261
+
262
+ The model's code runs in **Pyodide (CPython compiled to WebAssembly) inside a Deno process
263
+ started with `--deny-net --deny-env --deny-run --deny-write --deny-ffi --deny-sys`**. It can
264
+ read only Deno's npm cache, which Pyodide needs in order to load. On top of that, the
265
+ Deno, `fetch` and other JavaScript globals are removed before user code runs.
266
+
267
+ - The only way out of the sandbox is a JSON channel to the host. The host calls only
268
+ catalogued, allowed tools, and checks approvals.
269
+ - Credentials, including OAuth tokens (stored in `~/.codemode-mcp/oauth`), stay in the host.
270
+ - Limits: wall-clock time, tool calls per run, output size and heap size.
271
+
272
+ See [the security policy](https://codemode-mcp.vercel.app/security/) for the threat model, and the test suite for escape
273
+ attempts: files, env, network, processes, NODEFS mounts and dynamic `import()`.
274
+
275
+ ## Docker
276
+
277
+ ```bash
278
+ docker build -t codemode-mcp .
279
+ docker run -p 8000:8000 -v $PWD/mcp.json:/config/mcp.json codemode-mcp # http://localhost:8000/mcp
280
+ ```
281
+
282
+ ## Development
283
+
284
+ ```bash
285
+ uv sync --all-extras
286
+ uv run pytest # 32 tests: sandbox, security, OAuth, approvals, proxy, usage, benchmark...
287
+ uv run ruff check . && uv run ruff format --check .
288
+ uv run python examples/benchmark.py
289
+ ```
290
+
291
+ See [the contributing guide](https://codemode-mcp.vercel.app/contributing/). Inspired by Cloudflare's [Code Mode](https://blog.cloudflare.com/code-mode-mcp/).
@@ -0,0 +1,22 @@
1
+ codemode_mcp/__init__.py,sha256=eDYDxkxezkjo_09CvIUC-R5Ic6i-BV6AoGUPvD7OAS4,472
2
+ codemode_mcp/__main__.py,sha256=wT62aXCuN7iwRPQoswnmeGiBS5Cou0CIBvMxbOTfvFs,33
3
+ codemode_mcp/agent.py,sha256=DYpgDPzj_qUxjbe_1UPdHSWvC69saJASNDCz8A9wnz4,4902
4
+ codemode_mcp/benchmark.py,sha256=KqHkF_JunLbG99zuKgoruwXWTqbyMCT7xe0YA8A0O2w,8399
5
+ codemode_mcp/catalog.py,sha256=XEBrQ9h6WVIGhQudYyqNWzeJKaNROoweAXgN6BkftL0,12505
6
+ codemode_mcp/cli.py,sha256=ee4pJVdRVXuchZZ9zJ7x2CD99jVAze-akIQbChdPUxs,16556
7
+ codemode_mcp/clients.py,sha256=V963S86eIijLC-9nHagE7SxhjKDeZx_0WoN8h-5akVg,4365
8
+ codemode_mcp/config.py,sha256=WIW-8z6X4TaZV81fg7dFJqCkMrtut6Lwk7VgnUYY1hQ,8064
9
+ codemode_mcp/core.py,sha256=QyvLctrsH_SUhJmEjfa0Gq-OeU1NphCaEXYIHZidt2w,24326
10
+ codemode_mcp/dashboard.py,sha256=gv52ng5wROGrybFRBevhACb6hehInr6JSEbNxIKsng8,9061
11
+ codemode_mcp/oauth.py,sha256=0VCsWamHCtqSptwhsJBC2fpkSyyd8KGeuxR0zMfHVsQ,8585
12
+ codemode_mcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ codemode_mcp/sandbox.py,sha256=CHI9tcOpy7ycGnrPt8BWc1Quzvs-xrIkpmDJac2giME,12757
14
+ codemode_mcp/sandbox_runner.ts,sha256=Mk7G3Ha4JM9R6umGXhmh77iC9PZIjHi9D0Ef1viiDhM,9164
15
+ codemode_mcp/server.py,sha256=SiCie6k7SLR4LmEVRUG-jUxare41C6t9SUYfC4JE2nc,11347
16
+ codemode_mcp/upstream.py,sha256=hUE7xx_AKtJ-qmaZDbS97os4Dem8OGJfqy5rqSPBTwA,12922
17
+ codemode_mcp/usage.py,sha256=hJiE9I9joq8FoWg43d2H91Lky_6v4OeKjvI1rzhZxdo,11727
18
+ codemode_mcp-0.2.0.dist-info/licenses/LICENSE,sha256=B23nXGG59xHp6LjIxmk8VTFpVVUFHwsG7zkEY79bLpQ,1083
19
+ codemode_mcp-0.2.0.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
20
+ codemode_mcp-0.2.0.dist-info/entry_points.txt,sha256=WoQPEiezpzdyMEjqmqJF85wdeoadZl6xvL78Xmdo1ZE,56
21
+ codemode_mcp-0.2.0.dist-info/METADATA,sha256=1K5quRmNxKtrVf7ep__EaGKq9DgSk_QRh-xwGWlOD6o,13461
22
+ codemode_mcp-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.12
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ codemode-mcp = codemode_mcp.cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 codemode-mcp contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.