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,237 @@
1
+ // Sandbox worker: runs model-written Python inside Pyodide (WebAssembly) under Deno.
2
+ //
3
+ // The host launches this with no network, env, write, run, ffi or sys permissions (read
4
+ // access is limited to Deno's npm cache so Pyodide can load). The only way out of the
5
+ // sandbox is this line-delimited JSON protocol on stdin/stdout:
6
+ //
7
+ // host -> sandbox {"type":"install","specs":[...]} (tool stubs, once)
8
+ // host -> sandbox {"type":"exec","id":..,"code":..}
9
+ // sandbox -> host {"type":"call","exec_id":..,"call_id":..,"server":..,"tool":..,"args":{..}}
10
+ // host -> sandbox {"type":"call_result","call_id":..,"ok":true,"value":..} | {..,"ok":false,"error":".."}
11
+ // sandbox -> host {"type":"done","id":..,"ok":..,"stdout":..,"result":..,"error":..}
12
+ import { loadPyodide } from "npm:pyodide@314.0.8";
13
+
14
+ const D = (globalThis as any).Deno;
15
+ const stdout = D.stdout;
16
+ const stdinReadable: ReadableStream<Uint8Array> = D.stdin.readable;
17
+ const encoder = new TextEncoder();
18
+ function send(msg: unknown) {
19
+ const data = encoder.encode(JSON.stringify(msg) + "\n");
20
+ let off = 0;
21
+ while (off < data.length) off += stdout.writeSync(data.subarray(off));
22
+ }
23
+
24
+ const pending = new Map<number, { resolve: (v: string) => void; reject: (e: Error) => void }>();
25
+ let nextCallId = 1;
26
+ let currentExec: string | null = null;
27
+ let outBuf: string[] = [];
28
+
29
+ const pyodide = await loadPyodide({
30
+ stdout: (s: string) => outBuf.push(s),
31
+ stderr: (s: string) => outBuf.push(s),
32
+ });
33
+
34
+ const bridge = (server: string, tool: string, argsJson: string) => {
35
+ if (currentExec === null) return Promise.reject(new Error("no active execution"));
36
+ const call_id = nextCallId++;
37
+ return new Promise<string>((resolve, reject) => {
38
+ pending.set(call_id, { resolve, reject });
39
+ send({ type: "call", exec_id: currentExec, call_id, server, tool, args: JSON.parse(argsJson) });
40
+ });
41
+ };
42
+
43
+ // Defence in depth: Python can reach JS globals through the `js` module, so remove Deno's
44
+ // API surface (Deno's permission flags are the primary barrier) and pass the bridge in
45
+ // directly instead of exposing it as a global.
46
+ for (const name of ["Deno", "fetch", "WebSocket", "XMLHttpRequest", "EventSource", "Worker"]) {
47
+ try {
48
+ delete (globalThis as any)[name];
49
+ } catch { /* non-configurable */ }
50
+ try {
51
+ Object.defineProperty(globalThis, name, { value: undefined, configurable: false, writable: false });
52
+ } catch { /* ignore */ }
53
+ }
54
+
55
+ pyodide.runPython(`
56
+ import ast, inspect, json, sys
57
+
58
+ for _m in ("pyodide.http", "pyodide_js", "micropip"):
59
+ sys.modules.pop(_m, None)
60
+
61
+ class ToolError(Exception):
62
+ """Raised inside sandboxed code when an upstream tool call fails."""
63
+
64
+ _bridge = None
65
+
66
+ async def _codemode_call(server, tool, args):
67
+ try:
68
+ raw = await _bridge(server, tool, json.dumps(args, default=str))
69
+ except Exception as e:
70
+ msg = str(e)
71
+ for prefix in ("Error: ", "JsException: "):
72
+ if msg.startswith(prefix):
73
+ msg = msg[len(prefix):]
74
+ raise ToolError(f"{server}.{tool}: {msg}") from None
75
+ return json.loads(raw)
76
+
77
+ class _Namespace:
78
+ def __init__(self, name, funcs):
79
+ self.__dict__.update(funcs)
80
+ self._name = name
81
+ def __repr__(self):
82
+ return f"<tools of server {self._name!r}: {', '.join(k for k in self.__dict__ if not k.startswith('_'))}>"
83
+ def __getattr__(self, item):
84
+ raise AttributeError(f"server {self._name!r} has no tool {item!r}; use search_tools to find tool names")
85
+
86
+ _MISSING = object()
87
+
88
+ def _make_tool(spec):
89
+ server, tool, params = spec["server"], spec["tool"], spec["params"]
90
+ py_to_orig = {py: orig for py, orig, _ in params}
91
+ order = [py for py, _, _ in params]
92
+ required = [py for py, _, req in params if req]
93
+ qual = f"{spec['py_server']}.{spec['py_name']}"
94
+
95
+ async def call(*args, **kwargs):
96
+ if len(args) > len(order):
97
+ raise TypeError(f"{qual}() takes at most {len(order)} positional arguments")
98
+ given = dict(zip(order, args))
99
+ for k, v in kwargs.items():
100
+ if k in given:
101
+ raise TypeError(f"{qual}() got multiple values for argument {k!r}")
102
+ given[k] = v
103
+ missing = [r for r in required if given.get(r, _MISSING) is _MISSING]
104
+ if missing:
105
+ raise TypeError(f"{qual}() missing required argument(s): {', '.join(missing)}")
106
+ payload = {py_to_orig.get(k, k): v for k, v in given.items() if v is not None or k in required}
107
+ return await _codemode_call(server, tool, payload)
108
+
109
+ call.__name__ = spec["py_name"]
110
+ call.__qualname__ = qual
111
+ call.__doc__ = spec.get("doc") or None
112
+ return call
113
+
114
+ _servers = {}
115
+
116
+ def _codemode_install(specs_json):
117
+ global _servers
118
+ grouped = {}
119
+ for spec in json.loads(specs_json):
120
+ grouped.setdefault(spec["py_server"], {})[spec["py_name"]] = _make_tool(spec)
121
+ _servers = grouped
122
+
123
+ _SENTINEL = object()
124
+ _persistent_ns = None
125
+
126
+ class _Resources:
127
+ """Read MCP resources exposed by the upstream servers."""
128
+ async def list(self, server=None):
129
+ return await _codemode_call("__codemode__", "list_resources", {"server": server})
130
+ async def read(self, uri, server=None):
131
+ return await _codemode_call("__codemode__", "read_resource", {"uri": uri, "server": server})
132
+ def __repr__(self):
133
+ return "<resources: await resources.list(server=None), await resources.read(uri, server=None)>"
134
+
135
+ def _fresh_ns():
136
+ ns = {"ToolError": ToolError, "__name__": "__main__", "resources": _Resources()}
137
+ for name, funcs in _servers.items():
138
+ ns[name] = _Namespace(name, funcs)
139
+ return ns
140
+
141
+ def _codemode_reset():
142
+ global _persistent_ns
143
+ _persistent_ns = None
144
+
145
+ async def _codemode_run(code, persist=False):
146
+ """Run model code; a trailing expression becomes the result."""
147
+ global _persistent_ns
148
+ if persist:
149
+ if _persistent_ns is None:
150
+ _persistent_ns = _fresh_ns()
151
+ ns = _persistent_ns
152
+ ns.pop("__codemode_result__", None)
153
+ else:
154
+ ns = _fresh_ns()
155
+ tree = ast.parse(code, "<code>", "exec")
156
+ if tree.body and isinstance(tree.body[-1], ast.Expr):
157
+ last = tree.body[-1]
158
+ tree.body[-1] = ast.Assign(targets=[ast.Name("__codemode_result__", ast.Store())], value=last.value)
159
+ ast.fix_missing_locations(tree)
160
+ compiled = compile(tree, "<code>", "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
161
+ ret = eval(compiled, ns)
162
+ if inspect.iscoroutine(ret):
163
+ await ret
164
+ value = ns.get("__codemode_result__", _SENTINEL)
165
+ if value is _SENTINEL or value is None:
166
+ return None
167
+ try:
168
+ return json.dumps(value, default=str, ensure_ascii=False)
169
+ except Exception:
170
+ return json.dumps(repr(value))
171
+ `);
172
+
173
+ pyodide.globals.set("_bridge", bridge);
174
+ const runPy = pyodide.globals.get("_codemode_run");
175
+ const installPy = pyodide.globals.get("_codemode_install");
176
+ const resetPy = pyodide.globals.get("_codemode_reset");
177
+
178
+ function cleanError(e: unknown): string {
179
+ let err = String((e as Error)?.message ?? e);
180
+ const idx = err.indexOf('File "<code>"');
181
+ if (idx >= 0) err = "Traceback (most recent call last):\n " + err.slice(idx);
182
+ return err.trim();
183
+ }
184
+
185
+ async function runExec(msg: { id: string; code: string; persist?: boolean }) {
186
+ currentExec = msg.id;
187
+ outBuf = [];
188
+ try {
189
+ const result = await runPy(msg.code, !!msg.persist);
190
+ send({ type: "done", id: msg.id, ok: true, stdout: outBuf.join("\n"), result: result ?? null });
191
+ } catch (e) {
192
+ send({ type: "done", id: msg.id, ok: false, stdout: outBuf.join("\n"), error: cleanError(e) });
193
+ } finally {
194
+ currentExec = null;
195
+ for (const [, p] of pending) p.reject(new Error("execution finished"));
196
+ pending.clear();
197
+ }
198
+ }
199
+
200
+ send({ type: "ready" });
201
+
202
+ const decoder = new TextDecoder();
203
+ let buf = "";
204
+ let queue: Promise<void> = Promise.resolve();
205
+ for await (const chunk of stdinReadable) {
206
+ buf += decoder.decode(chunk, { stream: true });
207
+ let nl: number;
208
+ while ((nl = buf.indexOf("\n")) >= 0) {
209
+ const line = buf.slice(0, nl).trim();
210
+ buf = buf.slice(nl + 1);
211
+ if (!line) continue;
212
+ const msg = JSON.parse(line);
213
+ if (msg.type === "install") {
214
+ queue = queue.then(() => {
215
+ try {
216
+ installPy(JSON.stringify(msg.specs));
217
+ send({ type: "installed", count: msg.specs.length });
218
+ } catch (e) {
219
+ send({ type: "installed", error: cleanError(e) });
220
+ }
221
+ });
222
+ } else if (msg.type === "exec") {
223
+ queue = queue.then(() => runExec(msg));
224
+ } else if (msg.type === "reset") {
225
+ queue = queue.then(() => {
226
+ resetPy();
227
+ send({ type: "reset_done" });
228
+ });
229
+ } else if (msg.type === "call_result") {
230
+ const p = pending.get(msg.call_id);
231
+ if (!p) continue;
232
+ pending.delete(msg.call_id);
233
+ if (msg.ok) p.resolve(JSON.stringify(msg.value ?? null));
234
+ else p.reject(new Error(msg.error ?? "tool call failed"));
235
+ }
236
+ }
237
+ }
codemode_mcp/server.py ADDED
@@ -0,0 +1,267 @@
1
+ """Run Code Mode as an MCP server that proxies other MCP servers.
2
+
3
+ Exposes ``search_tools`` (large catalogs) + ``run_code``, any hybrid ``expose_tools``, and
4
+ passes upstream prompts and resources straight through. Tool calls that match
5
+ ``require_approval`` are confirmed with the user through MCP elicitation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import logging
13
+ import secrets
14
+ import sys
15
+ from typing import Any
16
+
17
+ import mcp_types as types
18
+ from mcp.server import Server, ServerRequestContext
19
+ from mcp.server.elicitation import elicit_with_validation
20
+ from mcp_types.version import MODERN_PROTOCOL_VERSIONS
21
+ from pydantic import BaseModel, Field
22
+
23
+ from .core import Approver, CodeMode
24
+ from .upstream import UpstreamError
25
+
26
+ log = logging.getLogger("codemode_mcp")
27
+
28
+
29
+ class _Approval(BaseModel):
30
+ approve: bool = Field(description="Allow this tool call?")
31
+
32
+
33
+ def _approval_message(server: str, tool: str, args: dict[str, Any]) -> str:
34
+ return (
35
+ f"The assistant wants to call {server}.{tool} with:\n"
36
+ f"{json.dumps(args, indent=2, ensure_ascii=False, default=str)[:1500]}\n\nAllow it?"
37
+ )
38
+
39
+
40
+ def elicitation_approver(ctx: ServerRequestContext[Any]) -> Approver:
41
+ """Legacy (<= 2025-11-25) connections: ask mid-call over the back-channel."""
42
+
43
+ async def approve(server: str, tool: str, args: dict[str, Any]) -> bool:
44
+ result = await elicit_with_validation(
45
+ session=ctx.session,
46
+ message=_approval_message(server, tool, args),
47
+ schema=_Approval,
48
+ related_request_id=ctx.request_id,
49
+ )
50
+ return result.action == "accept" and bool(result.data.approve) # type: ignore[union-attr]
51
+
52
+ return approve
53
+
54
+
55
+ class _SuspendedRun:
56
+ """A tool call whose sandbox execution is paused waiting for the user's approval.
57
+
58
+ Modern (2026-07-28+) connections have no server->client back-channel: we answer the
59
+ ``tools/call`` with ``InputRequiredResult`` and keep the run suspended (no re-execution,
60
+ so no repeated side effects) until the client retries with the user's answer.
61
+ """
62
+
63
+ def __init__(self, timeout: float):
64
+ self.timeout = timeout
65
+ self.task: asyncio.Task[types.CallToolResult] | None = None
66
+ self.answer: asyncio.Future[bool] | None = None
67
+ self.question: str = ""
68
+ self.asked = asyncio.Event()
69
+
70
+ async def approve(self, server: str, tool: str, args: dict[str, Any]) -> bool:
71
+ self.answer = asyncio.get_running_loop().create_future()
72
+ self.question = _approval_message(server, tool, args)
73
+ self.asked.set()
74
+ try:
75
+ return await asyncio.wait_for(self.answer, self.timeout)
76
+ except TimeoutError:
77
+ return False
78
+
79
+ async def next_step(self, state_id: str) -> types.CallToolResult | types.InputRequiredResult:
80
+ assert self.task is not None
81
+ asked = asyncio.ensure_future(self.asked.wait())
82
+ try:
83
+ await asyncio.wait({self.task, asked}, return_when=asyncio.FIRST_COMPLETED)
84
+ finally:
85
+ asked.cancel()
86
+ if self.task.done():
87
+ return self.task.result()
88
+ self.asked.clear()
89
+ return types.InputRequiredResult(
90
+ input_requests={
91
+ "approval": types.ElicitRequest(
92
+ params=types.ElicitRequestFormParams(
93
+ message=self.question, requested_schema=_Approval.model_json_schema()
94
+ )
95
+ )
96
+ },
97
+ request_state=state_id,
98
+ )
99
+
100
+
101
+ def _text(text: str, is_error: bool = False) -> types.CallToolResult:
102
+ return types.CallToolResult(content=[types.TextContent(type="text", text=text)], is_error=is_error)
103
+
104
+
105
+ def build_server(cm: CodeMode, name: str = "codemode", approval_timeout: float = 300.0) -> Server[Any]:
106
+ """Create a low-level MCP server for a started ``CodeMode``."""
107
+ suspended: dict[str, _SuspendedRun] = {}
108
+
109
+ async def list_tools(
110
+ ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
111
+ ) -> types.ListToolsResult:
112
+ return types.ListToolsResult(
113
+ tools=[
114
+ types.Tool(name=d["name"], description=d["description"], input_schema=d["input_schema"])
115
+ for d in cm.tool_definitions()
116
+ ]
117
+ )
118
+
119
+ async def execute(name: str, args: dict[str, Any], approver: Approver) -> types.CallToolResult:
120
+ try:
121
+ if name in cm.direct_tools:
122
+ return await cm.call_direct(name, args, approver=approver)
123
+ text = await cm.call(name, args, approver=approver)
124
+ except UpstreamError as e:
125
+ return _text(f"Error: {e}", True)
126
+ return _text(text, text.startswith("Error:"))
127
+
128
+ async def call_tool(
129
+ ctx: ServerRequestContext[Any], params: types.CallToolRequestParams
130
+ ) -> types.CallToolResult | types.InputRequiredResult:
131
+ args = dict(params.arguments or {})
132
+ if cm.approval_callback is not None or not cm.settings.require_approval:
133
+ return await execute(params.name, args, cm.approval_callback or elicitation_approver(ctx))
134
+ if ctx.protocol_version not in MODERN_PROTOCOL_VERSIONS:
135
+ return await execute(params.name, args, elicitation_approver(ctx))
136
+
137
+ run = suspended.get(params.request_state or "")
138
+ if run is not None:
139
+ reply = (params.input_responses or {}).get("approval")
140
+ allowed = (
141
+ isinstance(reply, types.ElicitResult)
142
+ and reply.action == "accept"
143
+ and bool((reply.content or {}).get("approve"))
144
+ )
145
+ if run.answer is not None and not run.answer.done():
146
+ run.answer.set_result(allowed)
147
+ state_id = params.request_state or ""
148
+ else:
149
+ run = _SuspendedRun(approval_timeout)
150
+ run.task = asyncio.create_task(execute(params.name, args, run.approve))
151
+ state_id = secrets.token_urlsafe(16)
152
+ suspended[state_id] = run
153
+ # Forget abandoned runs (client never retried) a while after they finish.
154
+ run.task.add_done_callback(
155
+ lambda _t, sid=state_id: asyncio.get_running_loop().call_later(600, suspended.pop, sid, None)
156
+ )
157
+ result = await run.next_step(state_id)
158
+ if not isinstance(result, types.InputRequiredResult):
159
+ suspended.pop(state_id, None)
160
+ return result
161
+
162
+ handlers: dict[str, Any] = {"on_list_tools": list_tools, "on_call_tool": call_tool}
163
+
164
+ if cm.upstreams.servers_with("prompts"):
165
+
166
+ async def _prompt_index() -> dict[str, tuple[str, types.Prompt]]:
167
+ prompts = await cm.upstreams.list_prompts()
168
+ counts: dict[str, int] = {}
169
+ for _, p in prompts:
170
+ counts[p.name] = counts.get(p.name, 0) + 1
171
+ return {(p.name if counts[p.name] == 1 else f"{s}__{p.name}"): (s, p) for s, p in prompts}
172
+
173
+ async def list_prompts(
174
+ ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
175
+ ) -> types.ListPromptsResult:
176
+ index = await _prompt_index()
177
+ return types.ListPromptsResult(prompts=[p.model_copy(update={"name": n}) for n, (_, p) in index.items()])
178
+
179
+ async def get_prompt(
180
+ ctx: ServerRequestContext[Any], params: types.GetPromptRequestParams
181
+ ) -> types.GetPromptResult:
182
+ index = await _prompt_index()
183
+ if params.name not in index:
184
+ raise ValueError(f"unknown prompt {params.name!r}")
185
+ server, prompt = index[params.name]
186
+ return await cm.upstreams.get_prompt(server, prompt.name, params.arguments)
187
+
188
+ handlers.update(on_list_prompts=list_prompts, on_get_prompt=get_prompt)
189
+
190
+ if cm.upstreams.servers_with("resources"):
191
+
192
+ async def list_resources(
193
+ ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
194
+ ) -> types.ListResourcesResult:
195
+ return types.ListResourcesResult(resources=[r for _, r in await cm.upstreams.list_resources()])
196
+
197
+ async def list_templates(
198
+ ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
199
+ ) -> types.ListResourceTemplatesResult:
200
+ return types.ListResourceTemplatesResult(
201
+ resource_templates=[t for _, t in await cm.upstreams.list_resource_templates()]
202
+ )
203
+
204
+ async def read_resource(
205
+ ctx: ServerRequestContext[Any], params: types.ReadResourceRequestParams
206
+ ) -> types.ReadResourceResult:
207
+ _, result = await cm.upstreams.read_resource(str(params.uri))
208
+ return result
209
+
210
+ handlers.update(
211
+ on_list_resources=list_resources, on_list_resource_templates=list_templates, on_read_resource=read_resource
212
+ )
213
+
214
+ from . import __version__
215
+
216
+ return Server(name, version=__version__, instructions=cm.system_prompt, **handlers)
217
+
218
+
219
+ async def serve(
220
+ config: str,
221
+ *,
222
+ transport: str = "stdio",
223
+ host: str = "127.0.0.1",
224
+ port: int = 8000,
225
+ dashboard_port: int | None = None,
226
+ ) -> None:
227
+ async with CodeMode.from_config(config) as cm:
228
+ server = build_server(cm)
229
+ dash: Any = None
230
+ dash_task: asyncio.Task[None] | None = None
231
+ if dashboard_port and cm.usage_store is not None:
232
+ from .dashboard import dashboard_server
233
+
234
+ dash = dashboard_server(cm.usage_store, host=host, port=dashboard_port)
235
+ dash_task = asyncio.create_task(dash.serve())
236
+ print(f"[codemode-mcp] dashboard: http://{host}:{dashboard_port}/", file=sys.stderr, flush=True)
237
+ try:
238
+ if transport == "stdio":
239
+ from mcp.server.stdio import stdio_server
240
+
241
+ async with stdio_server() as (read, write):
242
+ await server.run(read, write, server.create_initialization_options())
243
+ elif transport == "http":
244
+ import uvicorn
245
+
246
+ routes: list[Any] = []
247
+ if cm.usage_store is not None:
248
+ from .dashboard import dashboard_routes
249
+
250
+ routes = dashboard_routes(cm.usage_store, prefix="/dashboard")
251
+ app = server.streamable_http_app(host=host, custom_starlette_routes=routes)
252
+ print(
253
+ f"[codemode-mcp] MCP endpoint: http://{host}:{port}/mcp"
254
+ + (f" dashboard: http://{host}:{port}/dashboard/" if routes else ""),
255
+ file=sys.stderr,
256
+ flush=True,
257
+ )
258
+ await uvicorn.Server(uvicorn.Config(app, host=host, port=port, log_level="warning")).serve()
259
+ else:
260
+ raise ValueError(f"unknown transport {transport!r}")
261
+ finally:
262
+ if dash is not None and dash_task is not None:
263
+ dash.should_exit = True
264
+ try:
265
+ await asyncio.wait_for(dash_task, 5)
266
+ except (TimeoutError, asyncio.CancelledError):
267
+ dash_task.cancel()