python-repl-mcp 0.2.5__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,318 @@
1
+ """MCP surface: four tools, session routing and result shaping.
2
+
3
+ Pooled OpenCode requires chat identity in the per-call ``_meta`` payload.
4
+ Standalone connections can fall back to a configured or per-process key.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ from collections.abc import AsyncGenerator, Mapping
12
+ from contextlib import asynccontextmanager
13
+ from typing import Annotated, Any, Final, cast
14
+
15
+ from mcp.server.mcpserver import Context, MCPServer
16
+ from mcp.types import CallToolResult, TextContent
17
+ from pydantic import BaseModel, Field
18
+
19
+ from python_repl_mcp import __version__
20
+ from python_repl_mcp.config import (
21
+ DEFAULT_SESSION,
22
+ MAX_SESSION_ID_CHARS,
23
+ Config,
24
+ load_config,
25
+ )
26
+ from python_repl_mcp.errors import MissingSession, ReplError
27
+ from python_repl_mcp.kernel import ExecuteOutcome
28
+ from python_repl_mcp.opencode import valid_session_id
29
+ from python_repl_mcp.protocol import MAX_CODE_CHARS
30
+ from python_repl_mcp.service import ReplService
31
+
32
+ SESSION_META_KEY: Final = "ai.opencode/sessionID"
33
+ DEFAULT_TIMEOUT_SECONDS: Final = 30.0
34
+ MAX_TIMEOUT_SECONDS: Final = 600.0
35
+
36
+
37
+ class ErrorInfo(BaseModel):
38
+ """Compact failure details; never contains code or raw protocol frames."""
39
+
40
+ code: str
41
+ message: str
42
+ type: str | None = None
43
+ traceback: str | None = None
44
+ line: int | None = None
45
+ offset: int | None = None
46
+ context: str | None = None
47
+
48
+
49
+ class ResultModel(BaseModel):
50
+ """Structured tool result shared by execution and lifecycle calls."""
51
+
52
+ ok: bool
53
+ file: str | None = None
54
+ stdout: str = ""
55
+ stderr: str = ""
56
+ result: str | None = None
57
+ result_type: str | None = None
58
+ result_truncated: bool = False
59
+ result_json: Any | None = None
60
+ truncated: bool = False
61
+ capture_complete: bool = True
62
+ fresh_kernel: bool = False
63
+ kernel_id: str | None = None
64
+ workdir: str | None = None
65
+ error: ErrorInfo | None = None
66
+
67
+
68
+ def _service(ctx: Context) -> ReplService:
69
+ return cast(ReplService, ctx.request_context.lifespan_context)
70
+
71
+
72
+ def _valid_session(value: object) -> bool:
73
+ return isinstance(value, str) and 0 < len(value) <= MAX_SESSION_ID_CHARS
74
+
75
+
76
+ def _session_id(ctx: Context) -> str:
77
+ service = _service(ctx)
78
+ meta = ctx.request_context.meta
79
+ if meta is not None:
80
+ values = cast("Mapping[str, object]", meta)
81
+ if SESSION_META_KEY in values:
82
+ value = values[SESSION_META_KEY]
83
+ if not _valid_session(value):
84
+ raise MissingSession(f"invalid {SESSION_META_KEY!r} metadata")
85
+ session_id = cast(str, value)
86
+ if service.pooled and not valid_session_id(session_id):
87
+ raise MissingSession(f"invalid {SESSION_META_KEY!r} metadata")
88
+ return session_id
89
+ if service.pooled:
90
+ raise MissingSession(f"pooled OpenCode requires {SESSION_META_KEY!r} metadata")
91
+ configured = service.session_id
92
+ if configured is not None:
93
+ if not _valid_session(configured): # pragma: no cover - load_config validates it
94
+ raise MissingSession("invalid PYTHON_REPL_MCP_SESSION")
95
+ return configured
96
+ return DEFAULT_SESSION
97
+
98
+
99
+ def _render(model: ResultModel) -> str:
100
+ parts: list[str] = []
101
+ if model.error is not None:
102
+ location = ""
103
+ if model.error.line is not None:
104
+ location = f" (line {model.error.line}"
105
+ if model.error.offset is not None:
106
+ location += f", offset {model.error.offset}"
107
+ location += ")"
108
+ parts.append(f"{model.error.code}: {model.error.message}{location}")
109
+ if model.error.traceback:
110
+ parts.append(model.error.traceback)
111
+ else:
112
+ parts.append("ok" if model.ok else "failed")
113
+ if model.stdout:
114
+ parts.append(f"stdout:\n{model.stdout}")
115
+ if model.stderr:
116
+ parts.append(f"stderr:\n{model.stderr}")
117
+ if model.result is not None:
118
+ parts.append(f"result: {model.result}")
119
+ if model.result_type is not None:
120
+ parts.append(f"result_type: {model.result_type}")
121
+ if model.result_truncated:
122
+ parts.append("[result truncated]")
123
+ if model.file is not None:
124
+ parts.append(f"file: {model.file}")
125
+ if model.workdir is not None:
126
+ parts.append(f"workdir: {model.workdir}")
127
+ if model.kernel_id is not None:
128
+ parts.append(f"kernel: {model.kernel_id}")
129
+ if model.truncated:
130
+ parts.append("[output truncated]")
131
+ if not model.capture_complete:
132
+ parts.append("[capture incomplete]")
133
+ return "\n".join(parts)
134
+
135
+
136
+ def _result(model: ResultModel, *, is_error: bool, include_result_json: bool = False) -> CallToolResult:
137
+ structured = model.model_dump(mode="json", exclude_none=True)
138
+ if include_result_json and "result_json" not in structured:
139
+ # A displayed None carries JSON null; exclude_none must not drop it.
140
+ structured["result_json"] = None
141
+ return CallToolResult(
142
+ content=[TextContent(type="text", text=_render(model))],
143
+ structured_content=structured,
144
+ is_error=is_error,
145
+ )
146
+
147
+
148
+ def _tool_error(exc: ReplError) -> CallToolResult:
149
+ return _result(
150
+ ResultModel(ok=False, error=ErrorInfo(code=exc.code, message=exc.message)),
151
+ is_error=True,
152
+ )
153
+
154
+
155
+ def _execution_result(outcome: ExecuteOutcome) -> CallToolResult:
156
+ error = None
157
+ if outcome.error_code is not None:
158
+ error = ErrorInfo(
159
+ code=outcome.error_code,
160
+ message=outcome.error_message or outcome.error_code,
161
+ type=outcome.error_type,
162
+ traceback=outcome.error_traceback,
163
+ line=outcome.error_line,
164
+ offset=outcome.error_offset,
165
+ context=outcome.error_context,
166
+ )
167
+ result_json = None
168
+ if outcome.result_json is not None:
169
+ try:
170
+ result_json = json.loads(outcome.result_json)
171
+ except ValueError:
172
+ result_json = None
173
+ return _result(
174
+ ResultModel(
175
+ ok=outcome.ok,
176
+ file=outcome.file,
177
+ stdout=outcome.stdout,
178
+ stderr=outcome.stderr,
179
+ result=outcome.result,
180
+ result_type=outcome.result_type,
181
+ result_truncated=outcome.result_truncated,
182
+ result_json=result_json,
183
+ truncated=outcome.truncated,
184
+ capture_complete=outcome.capture_complete,
185
+ fresh_kernel=outcome.fresh_kernel,
186
+ kernel_id=outcome.kernel_id,
187
+ workdir=outcome.workdir,
188
+ error=error,
189
+ ),
190
+ is_error=False,
191
+ include_result_json=outcome.result_json is not None,
192
+ )
193
+
194
+
195
+ def create_server(config: Config | None = None) -> MCPServer:
196
+ """Build the MCP server; ``config`` is a test seam, production loads it lazily."""
197
+
198
+ @asynccontextmanager
199
+ async def lifespan(_server: MCPServer) -> AsyncGenerator[ReplService]:
200
+ service = ReplService(config if config is not None else load_config())
201
+ try:
202
+ yield service
203
+ finally:
204
+ await service.close()
205
+
206
+ server: MCPServer = MCPServer(
207
+ name="python-repl-mcp",
208
+ version=__version__,
209
+ lifespan=lifespan,
210
+ instructions=(
211
+ "Runs complete Python cells in one persistent interpreter per chat. "
212
+ "State survives between calls; use repl_reset for a clean interpreter "
213
+ "and repl_stop to release it."
214
+ ),
215
+ )
216
+
217
+ @server.tool()
218
+ async def repl_execute(
219
+ code: Annotated[
220
+ str,
221
+ Field(
222
+ min_length=1,
223
+ max_length=MAX_CODE_CHARS,
224
+ description=(
225
+ "Complete Python source for one cell. The final expression value is returned; "
226
+ "a lone string literal is a docstring and has no result."
227
+ ),
228
+ ),
229
+ ],
230
+ ctx: Context,
231
+ timeout_seconds: Annotated[
232
+ float,
233
+ Field(
234
+ default=DEFAULT_TIMEOUT_SECONDS,
235
+ gt=0,
236
+ le=MAX_TIMEOUT_SECONDS,
237
+ allow_inf_nan=False,
238
+ description="Wall-clock limit for this cell, in seconds.",
239
+ ),
240
+ ] = DEFAULT_TIMEOUT_SECONDS,
241
+ ) -> Annotated[CallToolResult, ResultModel]:
242
+ """Run one Python cell; returns the final expression value when present."""
243
+ try:
244
+ session_id = _session_id(ctx)
245
+ outcome = await _service(ctx).execute(session_id, code, timeout_seconds)
246
+ except ReplError as exc:
247
+ return _tool_error(exc)
248
+ return _execution_result(outcome)
249
+
250
+ @server.tool()
251
+ async def repl_run_file(
252
+ file_path: Annotated[
253
+ str,
254
+ Field(
255
+ min_length=1,
256
+ max_length=4_096,
257
+ description="Python file to run; relative paths resolve against the chat's bound working directory.",
258
+ ),
259
+ ],
260
+ ctx: Context,
261
+ args: Annotated[
262
+ list[str],
263
+ Field(
264
+ max_length=64,
265
+ description="Arguments exposed to the script as sys.argv[1:].",
266
+ ),
267
+ ] = [], # noqa: B006 - the SDK only reads this default
268
+ timeout_seconds: Annotated[
269
+ float,
270
+ Field(
271
+ default=DEFAULT_TIMEOUT_SECONDS,
272
+ gt=0,
273
+ le=MAX_TIMEOUT_SECONDS,
274
+ allow_inf_nan=False,
275
+ description="Wall-clock limit for this script, in seconds.",
276
+ ),
277
+ ] = DEFAULT_TIMEOUT_SECONDS,
278
+ ) -> Annotated[CallToolResult, ResultModel]:
279
+ """Run a Python file in this chat's persistent namespace; no trailing expression value is reported."""
280
+ try:
281
+ session_id = _session_id(ctx)
282
+ outcome = await _service(ctx).run_file(session_id, file_path, args, timeout_seconds)
283
+ except ReplError as exc:
284
+ return _tool_error(exc)
285
+ return _execution_result(outcome)
286
+
287
+ @server.tool()
288
+ async def repl_reset(ctx: Context) -> Annotated[CallToolResult, ResultModel]:
289
+ """Replace this chat's interpreter with a clean one that is ready before returning."""
290
+ try:
291
+ session_id = _session_id(ctx)
292
+ await _service(ctx).reset(session_id)
293
+ except ReplError as exc:
294
+ return _tool_error(exc)
295
+ return _result(ResultModel(ok=True), is_error=False)
296
+
297
+ @server.tool()
298
+ async def repl_stop(ctx: Context) -> Annotated[CallToolResult, ResultModel]:
299
+ """End this chat's interpreter without starting a replacement."""
300
+ try:
301
+ session_id = _session_id(ctx)
302
+ await _service(ctx).stop(session_id)
303
+ except ReplError as exc:
304
+ return _tool_error(exc)
305
+ return _result(ResultModel(ok=True), is_error=False)
306
+
307
+ return server
308
+
309
+
310
+ server = create_server()
311
+
312
+
313
+ def main() -> None:
314
+ asyncio.run(server.run_stdio_async())
315
+
316
+
317
+ if __name__ == "__main__":
318
+ main()