mcp-terminal-client-dev 0.1.92__tar.gz

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,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-terminal-client-dev
3
+ Version: 0.1.92
4
+ Summary: Async Python client for the mcp-terminal server. Hides all networking behind typed per-command methods.
5
+ Author-email: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.12
8
+ Requires-Dist: mcp-proxy-adapter<9,>=8.10.28
@@ -0,0 +1,115 @@
1
+ # mcp-terminal-client
2
+
3
+ Async Python client for the mcp-terminal server. Hides all networking behind typed per-command methods.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install mcp-terminal-client
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Basic Connection
14
+
15
+ ```python
16
+ from mcp_terminal_client import TerminalAsyncClient
17
+
18
+ # Connect with explicit parameters
19
+ client = TerminalAsyncClient(
20
+ protocol="https",
21
+ host="127.0.0.1",
22
+ port=3011,
23
+ cert="path/to/client.crt",
24
+ key="path/to/client.key",
25
+ ca="path/to/ca.crt",
26
+ check_hostname=False
27
+ )
28
+
29
+ # Or load from server config file
30
+ client = TerminalAsyncClient.from_server_config_path("/path/to/term_server.json")
31
+ ```
32
+
33
+ ### Async Context Manager
34
+
35
+ ```python
36
+ async with TerminalAsyncClient(...) as client:
37
+ # Use the client
38
+ sessions = await client.terminal_sessions(project_id="my-project")
39
+ ```
40
+
41
+ ### Running Commands
42
+
43
+ ```python
44
+ # Create a session
45
+ result = await client.terminal_session_create(
46
+ project_id="my-project",
47
+ session_id="my-session"
48
+ )
49
+
50
+ # Run a command
51
+ run_result = await client.terminal_run(
52
+ project_id="my-project",
53
+ session_id="my-session",
54
+ execution_kind="shell",
55
+ command="echo 'Hello, World!'"
56
+ )
57
+
58
+ # Wait for it to complete
59
+ status = await client.wait_for_command(
60
+ seq=run_result["seq"],
61
+ project_id="my-project",
62
+ session_id="my-session"
63
+ )
64
+
65
+ # Read the output
66
+ output = await client.read_output_text(
67
+ seq=run_result["seq"],
68
+ stream="stdout",
69
+ project_id="my-project",
70
+ session_id="my-session"
71
+ )
72
+
73
+ print(output)
74
+ ```
75
+
76
+ ### Convenience Helpers
77
+
78
+ The client provides convenience helpers for common workflows:
79
+
80
+ - `run_and_wait()` — submit and wait for a command to complete in one call
81
+ - `wait_for_command()` — poll a command until completion
82
+ - `wait_for_bootstrap()` — wait for a session to bootstrap
83
+ - `read_output_text()` — read accumulated output as text
84
+
85
+ ## Available Methods
86
+
87
+ All terminal server commands are available as typed async methods:
88
+
89
+ - `health()` — Server health check
90
+ - `echo(message)` — Echo test
91
+ - `help(command_name=None)` — Get command help
92
+ - `info(page=None, page_size=None)` — Server info
93
+ - `terminal_sessions(project_id, limit=None)` — List sessions
94
+ - `terminal_session_create(project_id, session_id, ...)` — Create a session
95
+ - `terminal_get_session_bootstrap(project_id, session_id)` — Get bootstrap status
96
+ - `terminal_run(project_id, session_id, ...)` — Run a command
97
+ - `terminal_attach(project_id, session_id, ...)` — Attach to interactive shell
98
+ - `terminal_send(shell_id, data)` — Send data to shell
99
+ - `terminal_read_shell(shell_id, offset=None, max_bytes=None)` — Read shell output
100
+ - `terminal_resize(shell_id, cols, rows)` — Resize terminal
101
+ - `terminal_detach(shell_id)` — Detach from shell
102
+ - `terminal_host_exec(...)` — Run on host
103
+ - `terminal_list(project_id, session_id, limit=None)` — List runs
104
+ - `terminal_list_watch(rescan=None)` — Watch for changes
105
+ - `terminal_registry_refresh()` — Refresh registry
106
+ - `terminal_get(project_id, session_id, seq)` — Get a run
107
+ - `terminal_read(seq, stream, ...)` — Read run output
108
+ - `terminal_search_commands(project_id, session_id, pattern, limit=None)` — Search commands
109
+ - `terminal_search_output(project_id, session_id, seq, stream, pattern, max_matches=None)` — Search output
110
+ - `terminal_tail(seq, stream, ...)` — Tail run output
111
+ - `terminal_stat(seq, ...)` — Get run stats
112
+ - `terminal_delete(project_id, session_id, force=None)` — Delete a session
113
+ - `terminal_get_status(seq, ...)` — Get command status
114
+ - `terminal_kill(project_id, session_id, seq)` — Kill a command
115
+ - `terminal_purge_sessions(dry_run=None, kill_docker=None, remove_runtime=None)` — Clean up sessions
@@ -0,0 +1,31 @@
1
+ """mcp-terminal-client: Async Python client for the mcp-terminal server.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from mcp_terminal_client.client import TerminalAsyncClient
10
+ from mcp_terminal_client.config import (
11
+ jsonrpc_kwargs_from_server_config,
12
+ load_server_config,
13
+ )
14
+ from mcp_terminal_client.exceptions import (
15
+ BootstrapFailedError,
16
+ CommandFailedError,
17
+ JobTimeoutError,
18
+ TerminalClientError,
19
+ )
20
+ from mcp_terminal_client.version import __version__
21
+
22
+ __all__ = [
23
+ "__version__",
24
+ "TerminalAsyncClient",
25
+ "TerminalClientError",
26
+ "CommandFailedError",
27
+ "JobTimeoutError",
28
+ "BootstrapFailedError",
29
+ "load_server_config",
30
+ "jsonrpc_kwargs_from_server_config",
31
+ ]
@@ -0,0 +1,833 @@
1
+ """Async client for mcp-terminal server.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+ from types import TracebackType
13
+ from typing import Any, Literal, Self
14
+
15
+ from mcp_proxy_adapter.client.jsonrpc_client.exceptions import ClientRemoteResponseError
16
+
17
+ try:
18
+ from mcp_proxy_adapter.client.jsonrpc_client.client import JsonRpcClient
19
+ except ImportError: # pragma: no cover - compatibility with older layouts
20
+ from mcp_proxy_adapter.client.jsonrpc_client import JsonRpcClient
21
+
22
+ from mcp_terminal_client.config import (
23
+ jsonrpc_kwargs_from_server_config,
24
+ load_server_config,
25
+ )
26
+ from mcp_terminal_client.exceptions import (
27
+ BootstrapFailedError,
28
+ CommandFailedError,
29
+ JobTimeoutError,
30
+ )
31
+
32
+ __all__ = ["TerminalAsyncClient"]
33
+
34
+
35
+ class TerminalAsyncClient:
36
+ """Async client for mcp-terminal server.
37
+
38
+ Provides typed methods for all server commands and convenience helpers
39
+ for common workflows like run_and_wait and wait_for_command.
40
+ """
41
+
42
+ __slots__ = ("_rpc",)
43
+
44
+ def __init__(
45
+ self,
46
+ *,
47
+ protocol: str = "https",
48
+ host: str = "127.0.0.1",
49
+ port: int = 3011,
50
+ token_header: str | None = None,
51
+ token: str | None = None,
52
+ cert: str | None = None,
53
+ key: str | None = None,
54
+ ca: str | None = None,
55
+ check_hostname: bool = False,
56
+ timeout: float | None = None,
57
+ ) -> None:
58
+ """Initialize TerminalAsyncClient with connection parameters.
59
+
60
+ Args:
61
+ protocol: Transport protocol (http, https, mtls). Default: https
62
+ host: Server hostname. Default: 127.0.0.1
63
+ port: Server port. Default: 3011
64
+ token_header: Header name for authentication token
65
+ token: Authentication token value
66
+ cert: Path to client certificate file
67
+ key: Path to client private key file
68
+ ca: Path to CA certificate file
69
+ check_hostname: Whether to verify hostname in SSL connections. Default: False
70
+ timeout: HTTP request timeout in seconds
71
+ """
72
+ self._rpc = JsonRpcClient(
73
+ protocol=protocol,
74
+ host=host,
75
+ port=port,
76
+ token_header=token_header,
77
+ token=token,
78
+ cert=cert,
79
+ key=key,
80
+ ca=ca,
81
+ check_hostname=check_hostname,
82
+ timeout=timeout,
83
+ )
84
+
85
+ @classmethod
86
+ def from_jsonrpc_kwargs(cls, **kwargs: Any) -> TerminalAsyncClient:
87
+ """Construct from JsonRpcClient keyword arguments."""
88
+ return cls(**kwargs)
89
+
90
+ @classmethod
91
+ def from_server_config(
92
+ cls,
93
+ config: Mapping[str, Any],
94
+ **overrides: Any,
95
+ ) -> TerminalAsyncClient:
96
+ """Construct from a server configuration dict.
97
+
98
+ Args:
99
+ config: Server config dict (e.g., from term_server.json)
100
+ **overrides: Optional keyword arguments to override config values
101
+
102
+ Returns:
103
+ TerminalAsyncClient instance
104
+ """
105
+ kwargs = jsonrpc_kwargs_from_server_config(config)
106
+ kwargs.update(overrides)
107
+ return cls(**kwargs)
108
+
109
+ @classmethod
110
+ def from_server_config_path(
111
+ cls,
112
+ path: str | Path,
113
+ **overrides: Any,
114
+ ) -> TerminalAsyncClient:
115
+ """Load config from a file and construct a client.
116
+
117
+ Args:
118
+ path: Path to config file (e.g., term_server.json)
119
+ **overrides: Optional keyword arguments to override config values
120
+
121
+ Returns:
122
+ TerminalAsyncClient instance
123
+ """
124
+ config = load_server_config(path)
125
+ return cls.from_server_config(config, **overrides)
126
+
127
+ @property
128
+ def rpc(self) -> JsonRpcClient:
129
+ """Underlying JsonRpcClient (escape hatch for direct access)."""
130
+ return self._rpc
131
+
132
+ async def call(self, command_name: str, **params: Any) -> Any:
133
+ """Execute a command via JSON-RPC.
134
+
135
+ Drops params with None values and unwraps the adapter envelope.
136
+
137
+ Args:
138
+ command_name: Command name
139
+ **params: Command parameters (keyword arguments)
140
+
141
+ Returns:
142
+ Command result data, or the raw result if no "data" key in envelope
143
+
144
+ Raises:
145
+ CommandFailedError: If the command response contains an error
146
+ """
147
+ # Drop None values from params
148
+ filtered = {k: v for k, v in params.items() if v is not None}
149
+
150
+ # Normalize remote command errors while preserving transport failures.
151
+ try:
152
+ response = await self._rpc.execute_command(command_name, filtered)
153
+ except ClientRemoteResponseError as exc:
154
+ raise CommandFailedError(
155
+ command=command_name,
156
+ code=exc.details.get("code"),
157
+ message=str(exc),
158
+ data=exc.details.get("data"),
159
+ ) from exc
160
+ except RuntimeError as exc:
161
+ # Older JsonRpcClient versions raise RuntimeError on JSON-RPC errors.
162
+ raise CommandFailedError(
163
+ command=command_name,
164
+ code=None,
165
+ message=str(exc),
166
+ data=None,
167
+ ) from exc
168
+
169
+ # Unwrap envelope: check for error or success=False
170
+ if isinstance(response, dict):
171
+ err = response.get("error")
172
+ if response.get("success") is False or err is not None:
173
+ code: Any = None
174
+ message: str | None = None
175
+ err_data: Any = None
176
+ if isinstance(err, dict): # adapter builtins may use JSON-RPC error object form
177
+ code = err.get("code")
178
+ message = err.get("message")
179
+ err_data = err.get("data")
180
+ elif err is not None: # mcp-terminal form: error is the string code
181
+ code = err
182
+ message = (
183
+ message
184
+ or response.get("message")
185
+ or (str(code) if code is not None else "command failed")
186
+ )
187
+ raise CommandFailedError(
188
+ command=command_name,
189
+ code=code,
190
+ message=message,
191
+ data=err_data if err_data is not None else response.get("data"),
192
+ )
193
+ # If there's a "data" key, return it; otherwise return the whole response
194
+ if "data" in response:
195
+ return response["data"]
196
+
197
+ return response
198
+
199
+ # =========================================================================
200
+ # Built-in adapter commands
201
+ # =========================================================================
202
+
203
+ async def health(self) -> dict[str, Any]:
204
+ """Server health check."""
205
+ return await self.call("health") # type: ignore[return-value]
206
+
207
+ async def echo(self, message: str) -> dict[str, Any]:
208
+ """Echo test message."""
209
+ return await self.call("echo", message=message) # type: ignore[return-value]
210
+
211
+ async def help(self, command_name: str | None = None) -> dict[str, Any]:
212
+ """Get command help."""
213
+ kwargs = {}
214
+ if command_name is not None:
215
+ kwargs["cmdname"] = command_name
216
+ return await self.call("help", **kwargs) # type: ignore[return-value]
217
+
218
+ # =========================================================================
219
+ # Terminal server commands
220
+ # =========================================================================
221
+
222
+ async def info(
223
+ self,
224
+ *,
225
+ page: int | None = None,
226
+ page_size: int | None = None,
227
+ ) -> dict[str, Any]:
228
+ """Get server info."""
229
+ return await self.call("info", page=page, page_size=page_size) # type: ignore[return-value]
230
+
231
+ async def terminal_sessions(
232
+ self,
233
+ project_id: str,
234
+ *,
235
+ limit: int | None = None,
236
+ ) -> dict[str, Any]:
237
+ """List terminal sessions for a project."""
238
+ return await self.call("terminal_sessions", project_id=project_id, limit=limit) # type: ignore[return-value]
239
+
240
+ async def terminal_session_create(
241
+ self,
242
+ project_id: str,
243
+ session_id: str,
244
+ *,
245
+ bootstrap_python_env: bool | None = None,
246
+ bootstrap_timeout_seconds: int | None = None,
247
+ image_profile: (
248
+ Literal["python_dev_3_14", "node_dev_20", "base_tools", "cuda_dev_12_4"] | None
249
+ ) = None,
250
+ workspace_write: bool | None = None,
251
+ use_venv: bool | None = None,
252
+ pid_namespace: Literal["container", "host"] | None = None,
253
+ memory_limit: str | None = None,
254
+ cpu_limit: float | None = None,
255
+ pids_limit: int | None = None,
256
+ binds: list[dict[str, str]] | None = None,
257
+ ) -> dict[str, Any]:
258
+ """Create a terminal session."""
259
+ return await self.call( # type: ignore[return-value]
260
+ "terminal_session_create",
261
+ project_id=project_id,
262
+ session_id=session_id,
263
+ bootstrap_python_env=bootstrap_python_env,
264
+ bootstrap_timeout_seconds=bootstrap_timeout_seconds,
265
+ image_profile=image_profile,
266
+ workspace_write=workspace_write,
267
+ use_venv=use_venv,
268
+ pid_namespace=pid_namespace,
269
+ memory_limit=memory_limit,
270
+ cpu_limit=cpu_limit,
271
+ pids_limit=pids_limit,
272
+ binds=binds,
273
+ )
274
+
275
+ async def terminal_get_session_bootstrap(
276
+ self,
277
+ project_id: str,
278
+ session_id: str,
279
+ ) -> dict[str, Any]:
280
+ """Get session bootstrap status with its state available at the top level."""
281
+ payload = await self.call(
282
+ "terminal_get_session_bootstrap",
283
+ project_id=project_id,
284
+ session_id=session_id,
285
+ )
286
+ if not isinstance(payload, dict):
287
+ return payload # type: ignore[return-value]
288
+ runtime_image = payload.get("runtime_image")
289
+ if "status" not in payload and isinstance(runtime_image, dict):
290
+ status = runtime_image.get("status")
291
+ if status is not None:
292
+ return {**payload, "status": status}
293
+ return payload
294
+
295
+ async def terminal_run(
296
+ self,
297
+ project_id: str,
298
+ session_id: str,
299
+ *,
300
+ execution_kind: Literal["shell", "argv"],
301
+ command: str | None = None,
302
+ argv: list[str] | None = None,
303
+ cwd: str | None = None,
304
+ mode: Literal["read_only", "workspace_write", "scratch_write"] | None = None,
305
+ network: Literal["none", "package_registry", "service"] | None = None,
306
+ image_profile: (
307
+ Literal["python_dev_3_14", "node_dev_20", "base_tools", "cuda_dev_12_4"] | None
308
+ ) = None,
309
+ timeout_seconds: int | None = None,
310
+ keep_container: bool | None = None,
311
+ use_venv: bool | None = None,
312
+ memory_limit: str | None = None,
313
+ cpu_limit: float | None = None,
314
+ pids_limit: int | None = None,
315
+ binds: list[dict[str, str]] | None = None,
316
+ ) -> dict[str, Any]:
317
+ """Run a command in a terminal session."""
318
+ return await self.call( # type: ignore[return-value]
319
+ "terminal_run",
320
+ project_id=project_id,
321
+ session_id=session_id,
322
+ execution_kind=execution_kind,
323
+ command=command,
324
+ argv=argv,
325
+ cwd=cwd,
326
+ mode=mode,
327
+ network=network,
328
+ image_profile=image_profile,
329
+ timeout_seconds=timeout_seconds,
330
+ keep_container=keep_container,
331
+ use_venv=use_venv,
332
+ memory_limit=memory_limit,
333
+ cpu_limit=cpu_limit,
334
+ pids_limit=pids_limit,
335
+ binds=binds,
336
+ )
337
+
338
+ async def terminal_attach(
339
+ self,
340
+ project_id: str,
341
+ session_id: str,
342
+ *,
343
+ command: Literal["bash", "sh", "python", "ipython"] | None = None,
344
+ cols: int | None = None,
345
+ rows: int | None = None,
346
+ ) -> dict[str, Any]:
347
+ """Attach to an interactive shell."""
348
+ return await self.call( # type: ignore[return-value]
349
+ "terminal_attach",
350
+ project_id=project_id,
351
+ session_id=session_id,
352
+ command=command,
353
+ cols=cols,
354
+ rows=rows,
355
+ )
356
+
357
+ async def terminal_send(self, shell_id: str, data: str) -> dict[str, Any]:
358
+ """Send data to a shell."""
359
+ return await self.call("terminal_send", shell_id=shell_id, data=data) # type: ignore[return-value]
360
+
361
+ async def terminal_read_shell(
362
+ self,
363
+ shell_id: str,
364
+ *,
365
+ offset: int | None = None,
366
+ max_bytes: int | None = None,
367
+ ) -> dict[str, Any]:
368
+ """Read shell output."""
369
+ return await self.call( # type: ignore[return-value]
370
+ "terminal_read_shell",
371
+ shell_id=shell_id,
372
+ offset=offset,
373
+ max_bytes=max_bytes,
374
+ )
375
+
376
+ async def terminal_resize(self, shell_id: str, cols: int, rows: int) -> dict[str, Any]:
377
+ """Resize terminal."""
378
+ return await self.call( # type: ignore[return-value]
379
+ "terminal_resize",
380
+ shell_id=shell_id,
381
+ cols=cols,
382
+ rows=rows,
383
+ )
384
+
385
+ async def terminal_detach(self, shell_id: str) -> dict[str, Any]:
386
+ """Detach from a shell."""
387
+ return await self.call("terminal_detach", shell_id=shell_id) # type: ignore[return-value]
388
+
389
+ async def terminal_host_exec(
390
+ self,
391
+ *,
392
+ execution_kind: Literal["shell", "argv"],
393
+ command: str | None = None,
394
+ argv: list[str] | None = None,
395
+ project_id: str | None = None,
396
+ session_id: str | None = None,
397
+ target_user: str | None = None,
398
+ cwd: str | None = None,
399
+ timeout_seconds: int | None = None,
400
+ use_venv: bool | None = None,
401
+ ) -> dict[str, Any]:
402
+ """Run a command on the host."""
403
+ return await self.call( # type: ignore[return-value]
404
+ "terminal_host_exec",
405
+ execution_kind=execution_kind,
406
+ command=command,
407
+ argv=argv,
408
+ project_id=project_id,
409
+ session_id=session_id,
410
+ target_user=target_user,
411
+ cwd=cwd,
412
+ timeout_seconds=timeout_seconds,
413
+ use_venv=use_venv,
414
+ )
415
+
416
+ async def terminal_list(
417
+ self,
418
+ project_id: str,
419
+ session_id: str,
420
+ *,
421
+ limit: int | None = None,
422
+ ) -> dict[str, Any]:
423
+ """List terminal runs."""
424
+ return await self.call( # type: ignore[return-value]
425
+ "terminal_list",
426
+ project_id=project_id,
427
+ session_id=session_id,
428
+ limit=limit,
429
+ )
430
+
431
+ async def terminal_list_watch(self, *, rescan: bool | None = None) -> dict[str, Any]:
432
+ """Watch for terminal changes."""
433
+ return await self.call("terminal_list_watch", rescan=rescan) # type: ignore[return-value]
434
+
435
+ async def terminal_registry_refresh(self) -> dict[str, Any]:
436
+ """Refresh the terminal registry."""
437
+ return await self.call("terminal_registry_refresh") # type: ignore[return-value]
438
+
439
+ async def terminal_get(self, project_id: str, session_id: str, seq: int) -> dict[str, Any]:
440
+ """Get a terminal run."""
441
+ return await self.call( # type: ignore[return-value]
442
+ "terminal_get",
443
+ project_id=project_id,
444
+ session_id=session_id,
445
+ seq=seq,
446
+ )
447
+
448
+ async def terminal_read(
449
+ self,
450
+ seq: int,
451
+ stream: Literal["stdout", "stderr"],
452
+ *,
453
+ project_id: str | None = None,
454
+ session_id: str | None = None,
455
+ host_run_id: str | None = None,
456
+ offset: int | None = None,
457
+ max_bytes: int | None = None,
458
+ ) -> dict[str, Any]:
459
+ """Read terminal output."""
460
+ return await self.call( # type: ignore[return-value]
461
+ "terminal_read",
462
+ seq=seq,
463
+ stream=stream,
464
+ project_id=project_id,
465
+ session_id=session_id,
466
+ host_run_id=host_run_id,
467
+ offset=offset,
468
+ max_bytes=max_bytes,
469
+ )
470
+
471
+ async def terminal_search_commands(
472
+ self,
473
+ project_id: str,
474
+ session_id: str,
475
+ pattern: str,
476
+ *,
477
+ limit: int | None = None,
478
+ ) -> dict[str, Any]:
479
+ """Search terminal commands."""
480
+ return await self.call( # type: ignore[return-value]
481
+ "terminal_search_commands",
482
+ project_id=project_id,
483
+ session_id=session_id,
484
+ pattern=pattern,
485
+ limit=limit,
486
+ )
487
+
488
+ async def terminal_search_output(
489
+ self,
490
+ project_id: str,
491
+ session_id: str,
492
+ seq: int,
493
+ stream: Literal["stdout", "stderr"],
494
+ pattern: str,
495
+ *,
496
+ max_matches: int | None = None,
497
+ ) -> dict[str, Any]:
498
+ """Search terminal output."""
499
+ return await self.call( # type: ignore[return-value]
500
+ "terminal_search_output",
501
+ project_id=project_id,
502
+ session_id=session_id,
503
+ seq=seq,
504
+ stream=stream,
505
+ pattern=pattern,
506
+ max_matches=max_matches,
507
+ )
508
+
509
+ async def terminal_tail(
510
+ self,
511
+ seq: int,
512
+ stream: Literal["stdout", "stderr"],
513
+ *,
514
+ project_id: str | None = None,
515
+ session_id: str | None = None,
516
+ host_run_id: str | None = None,
517
+ lines: int | None = None,
518
+ ) -> dict[str, Any]:
519
+ """Tail terminal output."""
520
+ return await self.call( # type: ignore[return-value]
521
+ "terminal_tail",
522
+ seq=seq,
523
+ stream=stream,
524
+ project_id=project_id,
525
+ session_id=session_id,
526
+ host_run_id=host_run_id,
527
+ lines=lines,
528
+ )
529
+
530
+ async def terminal_stat(
531
+ self,
532
+ seq: int,
533
+ *,
534
+ project_id: str | None = None,
535
+ session_id: str | None = None,
536
+ host_run_id: str | None = None,
537
+ ) -> dict[str, Any]:
538
+ """Get terminal run stats."""
539
+ return await self.call( # type: ignore[return-value]
540
+ "terminal_stat",
541
+ seq=seq,
542
+ project_id=project_id,
543
+ session_id=session_id,
544
+ host_run_id=host_run_id,
545
+ )
546
+
547
+ async def terminal_delete(
548
+ self,
549
+ project_id: str,
550
+ session_id: str,
551
+ *,
552
+ force: bool | None = None,
553
+ ) -> dict[str, Any]:
554
+ """Delete a terminal session."""
555
+ return await self.call( # type: ignore[return-value]
556
+ "terminal_delete",
557
+ project_id=project_id,
558
+ session_id=session_id,
559
+ force=force,
560
+ )
561
+
562
+ async def terminal_get_status(
563
+ self,
564
+ seq: int,
565
+ *,
566
+ project_id: str | None = None,
567
+ session_id: str | None = None,
568
+ host_run_id: str | None = None,
569
+ ) -> dict[str, Any]:
570
+ """Get terminal run status."""
571
+ return await self.call( # type: ignore[return-value]
572
+ "terminal_get_status",
573
+ seq=seq,
574
+ project_id=project_id,
575
+ session_id=session_id,
576
+ host_run_id=host_run_id,
577
+ )
578
+
579
+ async def terminal_kill(self, project_id: str, session_id: str, seq: int) -> dict[str, Any]:
580
+ """Kill a terminal run."""
581
+ return await self.call( # type: ignore[return-value]
582
+ "terminal_kill",
583
+ project_id=project_id,
584
+ session_id=session_id,
585
+ seq=seq,
586
+ )
587
+
588
+ async def terminal_jobs_health(self) -> dict[str, Any]:
589
+ """Return process-local terminal_run job counters (accepted/started/pending/running/completed/failed)."""
590
+ return await self.call("terminal_jobs_health") # type: ignore[return-value]
591
+
592
+ async def terminal_purge_sessions(
593
+ self,
594
+ *,
595
+ dry_run: bool | None = None,
596
+ kill_docker: bool | None = None,
597
+ remove_runtime: bool | None = None,
598
+ ) -> dict[str, Any]:
599
+ """Purge terminal sessions."""
600
+ return await self.call( # type: ignore[return-value]
601
+ "terminal_purge_sessions",
602
+ dry_run=dry_run,
603
+ kill_docker=kill_docker,
604
+ remove_runtime=remove_runtime,
605
+ )
606
+
607
+ # =========================================================================
608
+ # Convenience helpers
609
+ # =========================================================================
610
+
611
+ async def wait_for_command(
612
+ self,
613
+ seq: int,
614
+ *,
615
+ project_id: str | None = None,
616
+ session_id: str | None = None,
617
+ host_run_id: str | None = None,
618
+ poll_interval: float = 1.0,
619
+ timeout: float = 600.0,
620
+ ) -> dict[str, Any]:
621
+ """Wait for a command to complete.
622
+
623
+ Polls terminal_get_status until queue_status or terminal_status indicates
624
+ a terminal state (not "pending" or "running").
625
+
626
+ Args:
627
+ seq: Command sequence number
628
+ project_id: Project ID
629
+ session_id: Session ID
630
+ host_run_id: Host run ID (for host_exec commands)
631
+ poll_interval: Polling interval in seconds. Default: 1.0
632
+ timeout: Maximum time to wait in seconds. Default: 600.0
633
+
634
+ Returns:
635
+ Final status payload
636
+
637
+ Raises:
638
+ JobTimeoutError: If timeout is exceeded
639
+ """
640
+ elapsed = 0.0
641
+ while elapsed < timeout:
642
+ status = await self.terminal_get_status(
643
+ seq,
644
+ project_id=project_id,
645
+ session_id=session_id,
646
+ host_run_id=host_run_id,
647
+ )
648
+
649
+ # Check queue_status if present
650
+ queue_status = status.get("queue_status")
651
+ if queue_status and queue_status not in ("pending", "running", "queued", "started"):
652
+ return status
653
+
654
+ # Check terminal_status if present
655
+ terminal_status = status.get("terminal_status")
656
+ if terminal_status and terminal_status not in (
657
+ "pending",
658
+ "running",
659
+ "queued",
660
+ "started",
661
+ ):
662
+ return status
663
+
664
+ await asyncio.sleep(poll_interval)
665
+ elapsed += poll_interval
666
+
667
+ raise JobTimeoutError(f"Timed out after {timeout}s waiting for command seq={seq}")
668
+
669
+ async def run_and_wait(
670
+ self,
671
+ project_id: str,
672
+ session_id: str,
673
+ *,
674
+ poll_interval: float = 1.0,
675
+ wait_timeout: float = 600.0,
676
+ **terminal_run_kwargs: Any,
677
+ ) -> dict[str, Any]:
678
+ """Submit a command and wait for it to complete.
679
+
680
+ Combines terminal_run and wait_for_command.
681
+
682
+ Args:
683
+ project_id: Project ID
684
+ session_id: Session ID
685
+ poll_interval: Polling interval. Default: 1.0
686
+ wait_timeout: Maximum wait time. Default: 600.0
687
+ **terminal_run_kwargs: Keyword arguments for terminal_run
688
+
689
+ Returns:
690
+ Dict with keys "submit" (run response) and "status" (final status)
691
+ """
692
+ submit = await self.terminal_run(
693
+ project_id=project_id,
694
+ session_id=session_id,
695
+ **terminal_run_kwargs,
696
+ )
697
+
698
+ seq = submit.get("seq")
699
+ if seq is None:
700
+ raise CommandFailedError(
701
+ command="terminal_run",
702
+ code=None,
703
+ message="terminal_run response missing seq",
704
+ data=submit,
705
+ )
706
+
707
+ status = await self.wait_for_command(
708
+ seq,
709
+ project_id=project_id,
710
+ session_id=session_id,
711
+ poll_interval=poll_interval,
712
+ timeout=wait_timeout,
713
+ )
714
+
715
+ return {
716
+ "submit": submit,
717
+ "status": status,
718
+ }
719
+
720
+ async def wait_for_bootstrap(
721
+ self,
722
+ project_id: str,
723
+ session_id: str,
724
+ *,
725
+ poll_interval: float = 2.0,
726
+ timeout: float = 1800.0,
727
+ ) -> dict[str, Any]:
728
+ """Wait for a session to complete bootstrap.
729
+
730
+ Polls terminal_get_session_bootstrap until runtime_image.status is not "pending".
731
+
732
+ Args:
733
+ project_id: Project ID
734
+ session_id: Session ID
735
+ poll_interval: Polling interval in seconds. Default: 2.0
736
+ timeout: Maximum time to wait in seconds. Default: 1800.0
737
+
738
+ Returns:
739
+ Bootstrap payload
740
+
741
+ Raises:
742
+ BootstrapFailedError: If bootstrap status is "failed"
743
+ JobTimeoutError: If timeout is exceeded
744
+ """
745
+ elapsed = 0.0
746
+ while elapsed < timeout:
747
+ payload = await self.terminal_get_session_bootstrap(
748
+ project_id=project_id,
749
+ session_id=session_id,
750
+ )
751
+
752
+ runtime_image = payload.get("runtime_image", {})
753
+ status = runtime_image.get("status")
754
+
755
+ if status == "failed":
756
+ raise BootstrapFailedError(f"Session bootstrap failed: {payload}")
757
+
758
+ if status and status != "pending":
759
+ return payload
760
+
761
+ await asyncio.sleep(poll_interval)
762
+ elapsed += poll_interval
763
+
764
+ raise JobTimeoutError(
765
+ f"Timed out after {timeout}s waiting for bootstrap of {project_id}/{session_id}"
766
+ )
767
+
768
+ async def read_output_text(
769
+ self,
770
+ seq: int,
771
+ stream: Literal["stdout", "stderr"],
772
+ *,
773
+ project_id: str | None = None,
774
+ session_id: str | None = None,
775
+ host_run_id: str | None = None,
776
+ chunk_bytes: int = 65536,
777
+ ) -> str:
778
+ """Read all output from a terminal run as text.
779
+
780
+ Loops terminal_read advancing offset until bytes_read < chunk_bytes.
781
+
782
+ Args:
783
+ seq: Command sequence number
784
+ stream: Output stream (stdout or stderr)
785
+ project_id: Project ID
786
+ session_id: Session ID
787
+ host_run_id: Host run ID (for host_exec commands)
788
+ chunk_bytes: Chunk size for each read. Default: 65536
789
+
790
+ Returns:
791
+ Full output text concatenated from all chunks
792
+ """
793
+ offset = 0
794
+ chunks: list[str] = []
795
+
796
+ while True:
797
+ result = await self.terminal_read(
798
+ seq,
799
+ stream,
800
+ project_id=project_id,
801
+ session_id=session_id,
802
+ host_run_id=host_run_id,
803
+ offset=offset,
804
+ max_bytes=chunk_bytes,
805
+ )
806
+
807
+ text = result.get("text", "")
808
+ chunks.append(text)
809
+
810
+ bytes_read = result.get("bytes_read", 0)
811
+ if bytes_read < chunk_bytes:
812
+ break
813
+
814
+ offset += bytes_read
815
+
816
+ return "".join(chunks)
817
+
818
+ async def close(self) -> None:
819
+ """Close the underlying JSON-RPC transport."""
820
+ await self._rpc.close()
821
+
822
+ async def __aenter__(self) -> Self:
823
+ """Enter async context manager."""
824
+ return self
825
+
826
+ async def __aexit__(
827
+ self,
828
+ exc_type: type[BaseException] | None,
829
+ exc: BaseException | None,
830
+ tb: TracebackType | None,
831
+ ) -> None:
832
+ """Exit async context manager and close the client."""
833
+ await self.close()
@@ -0,0 +1,138 @@
1
+ """Configuration loading and mapping for mcp-terminal-client.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Any, Mapping
12
+
13
+ __all__ = ["load_server_config", "jsonrpc_kwargs_from_server_config"]
14
+
15
+
16
+ def _expand_path(value: Any) -> str | None:
17
+ """Expand a non-empty filesystem path value to an absolute string."""
18
+ if value is None or value == "":
19
+ return None
20
+ return str(Path(str(value)).expanduser().resolve())
21
+
22
+
23
+ def _ssl_paths_from_section(ssl_section: Any) -> dict[str, str]:
24
+ """Extract and normalize TLS path fields from a config SSL section."""
25
+ if not isinstance(ssl_section, dict):
26
+ return {}
27
+ out: dict[str, str] = {}
28
+ for key in ("cert", "key", "ca", "cert_path", "key_path", "ca_path"):
29
+ raw = ssl_section.get(key)
30
+ expanded = _expand_path(raw) if raw else None
31
+ if expanded:
32
+ out[key] = expanded
33
+ # Normalize aliases to cert/key/ca for downstream comparison / JsonRpcClient
34
+ if "cert" not in out and out.get("cert_path"):
35
+ out["cert"] = out["cert_path"]
36
+ if "key" not in out and out.get("key_path"):
37
+ out["key"] = out["key_path"]
38
+ if "ca" not in out and out.get("ca_path"):
39
+ out["ca"] = out["ca_path"]
40
+ return out
41
+
42
+
43
+ def load_server_config(path: str | Path) -> dict[str, Any]:
44
+ """Load server config.json into a dict."""
45
+ p = Path(path).expanduser()
46
+ with p.open("r", encoding="utf-8") as f:
47
+ data: Any = json.load(f)
48
+ if not isinstance(data, dict):
49
+ raise ValueError("Server config must be a JSON object")
50
+ return dict(data)
51
+
52
+
53
+ def jsonrpc_kwargs_from_server_config(
54
+ config: Mapping[str, Any],
55
+ *,
56
+ prefer_client_ssl: bool = True,
57
+ ) -> dict[str, Any]:
58
+ """Turn term_server config into keyword args for JsonRpcClient.
59
+
60
+ Maps server config structure (host, port, protocol in config["server"],
61
+ TLS paths in config["client"]["ssl"] or config["server"]["ssl"]) to
62
+ JsonRpcClient constructor kwargs.
63
+
64
+ Args:
65
+ config: Server configuration dict (e.g., from term_server.json)
66
+ prefer_client_ssl: When True (default), prefer client.ssl paths over server.ssl
67
+
68
+ Returns:
69
+ Dict with keys: protocol, host, port, token_header, token, cert, key, ca, check_hostname
70
+ """
71
+ # Network settings from config["server"]
72
+ server = config.get("server", {})
73
+ if not isinstance(server, dict):
74
+ server = {}
75
+
76
+ host = server.get("host", "127.0.0.1")
77
+ # Map 0.0.0.0 and :: to 127.0.0.1
78
+ if host in ("0.0.0.0", "::", "[::]"):
79
+ host = "127.0.0.1"
80
+
81
+ port = int(server.get("port", 3011))
82
+ protocol = server.get("protocol", "https")
83
+
84
+ # TLS paths: prefer client.ssl, fall back to server.ssl
85
+ ssl_paths: dict[str, str] = {}
86
+ if prefer_client_ssl:
87
+ client = config.get("client", {})
88
+ if isinstance(client, dict):
89
+ client_ssl = client.get("ssl", {})
90
+ if isinstance(client_ssl, dict):
91
+ ssl_paths = _ssl_paths_from_section(client_ssl)
92
+
93
+ # If client_ssl is empty or prefer_client_ssl is False, try server.ssl
94
+ if not ssl_paths:
95
+ server_ssl = server.get("ssl", {})
96
+ if isinstance(server_ssl, dict):
97
+ ssl_paths = _ssl_paths_from_section(server_ssl)
98
+
99
+ # Extract individual cert/key/ca from paths
100
+ cert = ssl_paths.get("cert")
101
+ key = ssl_paths.get("key")
102
+ ca = ssl_paths.get("ca")
103
+
104
+ # Check hostname: default False unless explicitly set to True
105
+ check_hostname = False
106
+ ssl_section = config.get("client", {}).get("ssl", {}) if prefer_client_ssl else None
107
+ if not ssl_section:
108
+ ssl_section = config.get("server", {}).get("ssl", {})
109
+ if isinstance(ssl_section, dict):
110
+ check_hostname_raw = ssl_section.get("check_hostname")
111
+ if check_hostname_raw is True:
112
+ check_hostname = True
113
+
114
+ # Auth token: only map if use_token is true and token is present
115
+ token_header: str | None = None
116
+ token: str | None = None
117
+ auth = config.get("auth", {})
118
+ if isinstance(auth, dict) and auth.get("use_token"):
119
+ tokens = auth.get("tokens", {})
120
+ if isinstance(tokens, dict):
121
+ # Take the first token value if any exist
122
+ for key_name, token_value in tokens.items():
123
+ if token_value:
124
+ token = str(token_value)
125
+ token_header = "X-API-Key"
126
+ break
127
+
128
+ return {
129
+ "protocol": str(protocol),
130
+ "host": str(host),
131
+ "port": int(port),
132
+ "token_header": token_header,
133
+ "token": token,
134
+ "cert": cert,
135
+ "key": key,
136
+ "ca": ca,
137
+ "check_hostname": check_hostname,
138
+ }
@@ -0,0 +1,62 @@
1
+ """Exceptions for mcp-terminal-client.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Optional
10
+
11
+ __all__ = [
12
+ "TerminalClientError",
13
+ "CommandFailedError",
14
+ "JobTimeoutError",
15
+ "BootstrapFailedError",
16
+ ]
17
+
18
+
19
+ class TerminalClientError(Exception):
20
+ """Base exception for mcp-terminal-client errors."""
21
+
22
+ pass
23
+
24
+
25
+ class CommandFailedError(TerminalClientError):
26
+ """A command execution failed with an error response."""
27
+
28
+ def __init__(
29
+ self,
30
+ *,
31
+ command: str,
32
+ code: Any,
33
+ message: str,
34
+ data: Any,
35
+ ) -> None:
36
+ """Initialize with command details and error information.
37
+
38
+ Args:
39
+ command: The command that failed
40
+ code: The error code from the server
41
+ message: The error message from the server
42
+ data: Additional error data from the server
43
+ """
44
+ super().__init__(
45
+ f"Command '{command}' failed with code {code}: {message}"
46
+ )
47
+ self.command = command
48
+ self.code = code
49
+ self.message = message
50
+ self.data = data
51
+
52
+
53
+ class JobTimeoutError(TerminalClientError):
54
+ """Polling exceeded timeout while waiting for a job to complete."""
55
+
56
+ pass
57
+
58
+
59
+ class BootstrapFailedError(TerminalClientError):
60
+ """Session bootstrap failed."""
61
+
62
+ pass
@@ -0,0 +1,41 @@
1
+ """Version information for mcp-terminal-client.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from pathlib import Path
11
+ from importlib.metadata import version, PackageNotFoundError
12
+
13
+ __all__ = ["__version__"]
14
+
15
+
16
+ def _get_version() -> str:
17
+ """Get version from importlib.metadata or parse from pyproject.toml."""
18
+ pyproject_path = Path(__file__).resolve().parents[1] / "pyproject.toml"
19
+ if pyproject_path.exists():
20
+ match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject_path.read_text(), re.M)
21
+ if match:
22
+ return match.group(1)
23
+ try:
24
+ return version("mcp-terminal-client")
25
+ except PackageNotFoundError:
26
+ try:
27
+ return version("mcp-terminal-client-dev")
28
+ except PackageNotFoundError:
29
+ pass
30
+ # Fallback: parse version from pyproject.toml
31
+ pyproject_path = Path(__file__).resolve().parents[1] / "pyproject.toml"
32
+ if pyproject_path.exists():
33
+ with open(pyproject_path, "r", encoding="utf-8") as f:
34
+ content = f.read()
35
+ match = re.search(r'version\s*=\s*"([^"]+)"', content)
36
+ if match:
37
+ return match.group(1)
38
+ return "0.0.0"
39
+
40
+
41
+ __version__ = _get_version()
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-terminal-client-dev
3
+ Version: 0.1.92
4
+ Summary: Async Python client for the mcp-terminal server. Hides all networking behind typed per-command methods.
5
+ Author-email: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.12
8
+ Requires-Dist: mcp-proxy-adapter<9,>=8.10.28
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ mcp_terminal_client/__init__.py
4
+ mcp_terminal_client/client.py
5
+ mcp_terminal_client/config.py
6
+ mcp_terminal_client/exceptions.py
7
+ mcp_terminal_client/py.typed
8
+ mcp_terminal_client/version.py
9
+ mcp_terminal_client_dev.egg-info/PKG-INFO
10
+ mcp_terminal_client_dev.egg-info/SOURCES.txt
11
+ mcp_terminal_client_dev.egg-info/dependency_links.txt
12
+ mcp_terminal_client_dev.egg-info/requires.txt
13
+ mcp_terminal_client_dev.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ mcp-proxy-adapter<9,>=8.10.28
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mcp-terminal-client-dev"
7
+ version = "0.1.92"
8
+ description = "Async Python client for the mcp-terminal server. Hides all networking behind typed per-command methods."
9
+ requires-python = ">=3.12"
10
+ license = {text = "MIT"}
11
+ authors = [
12
+ {name = "Vasiliy Zdanovskiy", email = "vasilyvz@gmail.com"}
13
+ ]
14
+ dependencies = [
15
+ "mcp-proxy-adapter>=8.10.28,<9"
16
+ ]
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["."]
20
+ include = ["mcp_terminal_client*"]
21
+
22
+ [tool.setuptools.package-data]
23
+ mcp_terminal_client = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+