clikernel 0.2.20__tar.gz → 0.2.21__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.
- {clikernel-0.2.20 → clikernel-0.2.21}/CHANGELOG.md +10 -0
- {clikernel-0.2.20/clikernel.egg-info → clikernel-0.2.21}/PKG-INFO +9 -8
- {clikernel-0.2.20 → clikernel-0.2.21}/README.md +6 -4
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel/__init__.py +4 -5
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel/_modidx.py +12 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel/core.py +31 -17
- clikernel-0.2.21/clikernel/mcp.py +359 -0
- clikernel-0.2.21/clikernel/skill.py +20 -0
- {clikernel-0.2.20 → clikernel-0.2.21/clikernel.egg-info}/PKG-INFO +9 -8
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel.egg-info/SOURCES.txt +1 -3
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel.egg-info/requires.txt +2 -3
- {clikernel-0.2.20 → clikernel-0.2.21}/pyproject.toml +2 -3
- clikernel-0.2.20/clikernel/mcp.py +0 -145
- clikernel-0.2.20/clikernel/skill.py +0 -24
- clikernel-0.2.20/clikernel/stream.py +0 -125
- clikernel-0.2.20/tests/test_stream.py +0 -47
- {clikernel-0.2.20 → clikernel-0.2.21}/LICENSE +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/MANIFEST.in +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel/cli.py +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel/login.py +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel/rules.py +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel.egg-info/dependency_links.txt +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel.egg-info/entry_points.txt +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/clikernel.egg-info/top_level.txt +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/setup.cfg +0 -0
- {clikernel-0.2.20 → clikernel-0.2.21}/tests/test_rules.py +0 -0
|
@@ -2,6 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
<!-- do not remove -->
|
|
4
4
|
|
|
5
|
+
## 0.2.21
|
|
6
|
+
|
|
7
|
+
### New Features
|
|
8
|
+
|
|
9
|
+
- Route subagents to per-(host, agent) gateway sessions with lazy kernel creation and idle session reaping ([#68](https://github.com/AnswerDotAI/clikernel/issues/68))
|
|
10
|
+
- Switch from rustygate to jupygate, remove stream module, and harden `CLIKERNEL_HOST` and remote host routing ([#66](https://github.com/AnswerDotAI/clikernel/issues/66))
|
|
11
|
+
- Add --maxout UTF-8 reply capping in Router with temp-file overflow and %cont paging ([#65](https://github.com/AnswerDotAI/clikernel/issues/65))
|
|
12
|
+
- Add Antigravity support to clikernel-hook, injecting per-conversation agent and cwd, and drop cwd when forwarding to remote hosts ([#64](https://github.com/AnswerDotAI/clikernel/issues/64))
|
|
13
|
+
|
|
14
|
+
|
|
5
15
|
## 0.2.20
|
|
6
16
|
|
|
7
17
|
### New Features
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: clikernel
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.21
|
|
4
4
|
Summary: Serve persistent Jupyter kernels to LLMs as concise text, over MCP or a plain stream protocol
|
|
5
5
|
Author: clikernel contributors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -12,10 +12,9 @@ Requires-Python: >=3.11
|
|
|
12
12
|
Description-Content-Type: text/markdown
|
|
13
13
|
License-File: LICENSE
|
|
14
14
|
Requires-Dist: fastcore>=2.2.2
|
|
15
|
-
Requires-Dist: jupyasyncclient>=0.2.
|
|
16
|
-
Requires-Dist: jupywire>=0.1.9
|
|
15
|
+
Requires-Dist: jupyasyncclient>=0.2.32
|
|
17
16
|
Requires-Dist: mcpmini>=0.0.5
|
|
18
|
-
Requires-Dist:
|
|
17
|
+
Requires-Dist: jupygate>=0.1.0
|
|
19
18
|
Requires-Dist: ipymini>=0.1.28
|
|
20
19
|
Requires-Dist: httpx
|
|
21
20
|
Requires-Dist: ipython
|
|
@@ -30,7 +29,7 @@ Dynamic: license-file
|
|
|
30
29
|
|
|
31
30
|
`clikernel` gives LLM agents persistent kernel sessions over MCP or a plain stream protocol. Imports, variables, and results remain available between calls. Agents can create kernels or attach to existing ones, including a user’s live solveit kernel.
|
|
32
31
|
|
|
33
|
-
[
|
|
32
|
+
[jupygate](https://github.com/AnswerDotAI/jupygate) hosts the kernels. Clikernel routes requests to local or named remote gateways and supplies startup code to Python kernels.
|
|
34
33
|
|
|
35
34
|
New kernels close with their creating conversation by default. Attaching to an existing kernel does not claim ownership. Use `autoclose=false` on a persistent gateway to keep a new kernel for later conversations. See [core](https://AnswerDotAI.github.io/clikernel/core.html) for configuration and lifecycle details.
|
|
36
35
|
|
|
@@ -40,10 +39,10 @@ New kernels close with their creating conversation by default. Attaching to an e
|
|
|
40
39
|
pip install clikernel
|
|
41
40
|
```
|
|
42
41
|
|
|
43
|
-
This installs
|
|
42
|
+
This installs jupygate and ipymini. No service setup is required for a conversation-local kernel: clikernel starts a private gateway if it cannot find one. To retain kernels across conversations, run a resident gateway, for example through launchd or systemd:
|
|
44
43
|
|
|
45
44
|
``` sh
|
|
46
|
-
|
|
45
|
+
jupygate --port 8787
|
|
47
46
|
```
|
|
48
47
|
|
|
49
48
|
## Use with an MCP host
|
|
@@ -61,12 +60,14 @@ create(kernel="py")
|
|
|
61
60
|
exec(code="6*7")
|
|
62
61
|
```
|
|
63
62
|
|
|
64
|
-
|
|
63
|
+
`create` accepts any kernelspec the gateway finds. In the main conversation, `exec` never creates or switches kernels. See [MCP](https://AnswerDotAI.github.io/clikernel/mcp.html) for named gateways and other tools.
|
|
65
64
|
|
|
66
65
|
In Claude Code, subagents share the current kernel unless `clikernel-hook` is registered as a `PreToolUse` hook. With the hook, each subagent’s first `exec` creates a kernel of its own. See [Subagent kernels](https://AnswerDotAI.github.io/clikernel/mcp.html#subagent-kernels) for the settings entry.
|
|
67
66
|
|
|
68
67
|
The router checks each `exec` cell against built-in rules for mistakes agents often make with this toolkit. Most rules add a note to the reply, and `--quiet` leaves the notes out. Two rules always block the cell: shell access through `subprocess`, [`os.system`](https://docs.python.org/3/library/os.html#os.system) or [`os.popen`](https://docs.python.org/3/library/os.html#os.popen), and changes to `sys.path`.
|
|
69
68
|
|
|
69
|
+
The router caps text replies to `--maxout` UTF-8 bytes (default 40,000; pass `0` to disable). When a reply exceeds that limit, the router saves the full output to a temporary file, returns the first chunk with the file path and remaining size, and serves subsequent chunks when you run `exec(code="%cont")` (or `exec(code="%cont <id>")` when several calls overflow in parallel).
|
|
70
|
+
|
|
70
71
|
## Configuration
|
|
71
72
|
|
|
72
73
|
Two optional files in `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
`clikernel` gives LLM agents persistent kernel sessions over MCP or a plain stream protocol. Imports, variables, and results remain available between calls. Agents can create kernels or attach to existing ones, including a user’s live solveit kernel.
|
|
7
7
|
|
|
8
|
-
[
|
|
8
|
+
[jupygate](https://github.com/AnswerDotAI/jupygate) hosts the kernels. Clikernel routes requests to local or named remote gateways and supplies startup code to Python kernels.
|
|
9
9
|
|
|
10
10
|
New kernels close with their creating conversation by default. Attaching to an existing kernel does not claim ownership. Use `autoclose=false` on a persistent gateway to keep a new kernel for later conversations. See [core](https://AnswerDotAI.github.io/clikernel/core.html) for configuration and lifecycle details.
|
|
11
11
|
|
|
@@ -15,10 +15,10 @@ New kernels close with their creating conversation by default. Attaching to an e
|
|
|
15
15
|
pip install clikernel
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
This installs
|
|
18
|
+
This installs jupygate and ipymini. No service setup is required for a conversation-local kernel: clikernel starts a private gateway if it cannot find one. To retain kernels across conversations, run a resident gateway, for example through launchd or systemd:
|
|
19
19
|
|
|
20
20
|
``` sh
|
|
21
|
-
|
|
21
|
+
jupygate --port 8787
|
|
22
22
|
```
|
|
23
23
|
|
|
24
24
|
## Use with an MCP host
|
|
@@ -36,12 +36,14 @@ create(kernel="py")
|
|
|
36
36
|
exec(code="6*7")
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
`create` accepts any kernelspec the gateway finds. In the main conversation, `exec` never creates or switches kernels. See [MCP](https://AnswerDotAI.github.io/clikernel/mcp.html) for named gateways and other tools.
|
|
40
40
|
|
|
41
41
|
In Claude Code, subagents share the current kernel unless `clikernel-hook` is registered as a `PreToolUse` hook. With the hook, each subagent’s first `exec` creates a kernel of its own. See [Subagent kernels](https://AnswerDotAI.github.io/clikernel/mcp.html#subagent-kernels) for the settings entry.
|
|
42
42
|
|
|
43
43
|
The router checks each `exec` cell against built-in rules for mistakes agents often make with this toolkit. Most rules add a note to the reply, and `--quiet` leaves the notes out. Two rules always block the cell: shell access through `subprocess`, [`os.system`](https://docs.python.org/3/library/os.html#os.system) or [`os.popen`](https://docs.python.org/3/library/os.html#os.popen), and changes to `sys.path`.
|
|
44
44
|
|
|
45
|
+
The router caps text replies to `--maxout` UTF-8 bytes (default 40,000; pass `0` to disable). When a reply exceeds that limit, the router saves the full output to a temporary file, returns the first chunk with the file path and remaining size, and serves subsequent chunks when you run `exec(code="%cont")` (or `exec(code="%cont <id>")` when several calls overflow in parallel).
|
|
46
|
+
|
|
45
47
|
## Configuration
|
|
46
48
|
|
|
47
49
|
Two optional files in `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
|
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
Modules:
|
|
4
4
|
|
|
5
5
|
- `clikernel.cli`: The stream-protocol frontend: the service on stdin/stdout for token-reading clients
|
|
6
|
-
- `clikernel.core`: Gateway naming, startup delivery, and MCP sessions on
|
|
7
|
-
- `clikernel.mcp`: Route stdio MCP requests to
|
|
8
|
-
- `clikernel.skill`: Use `clikernel` MCP as the default persistent Python workspace for file/notebook reads and edits, exploration, library checks, data reshaping and debugging. Imports and variables carry across calls. Read before writing, running or debugging Python with `clikernel` connected.
|
|
9
|
-
- `clikernel.stream`: Streaming JSON-lines worker protocol: nbformat-shaped output events, and a supervisor for select-based UIs."""
|
|
6
|
+
- `clikernel.core`: Gateway naming, startup delivery, and MCP sessions on jupygate gateways
|
|
7
|
+
- `clikernel.mcp`: Route stdio MCP requests to jupygate gateways
|
|
8
|
+
- `clikernel.skill`: Use `clikernel` MCP as the default persistent Python workspace for file/notebook reads and edits, exploration, library checks, data reshaping and debugging. Imports and variables carry across calls. Read before writing, running or debugging Python with `clikernel` connected."""
|
|
10
9
|
|
|
11
|
-
__version__ = "0.2.
|
|
10
|
+
__version__ = "0.2.21"
|
|
@@ -34,11 +34,23 @@ d = { 'settings': { 'branch': 'main',
|
|
|
34
34
|
'clikernel.login': {'clikernel.login.main': ('login.html#main', 'clikernel/login.py')},
|
|
35
35
|
'clikernel.mcp': { 'clikernel.mcp.Router': ('mcp.html#router', 'clikernel/mcp.py'),
|
|
36
36
|
'clikernel.mcp.Router.__init__': ('mcp.html#router.__init__', 'clikernel/mcp.py'),
|
|
37
|
+
'clikernel.mcp.Router._cap_text': ('mcp.html#router._cap_text', 'clikernel/mcp.py'),
|
|
38
|
+
'clikernel.mcp.Router._cont': ('mcp.html#router._cont', 'clikernel/mcp.py'),
|
|
39
|
+
'clikernel.mcp.Router._ensure_agent_kernel': ('mcp.html#router._ensure_agent_kernel', 'clikernel/mcp.py'),
|
|
40
|
+
'clikernel.mcp.Router._parent_kernel': ('mcp.html#router._parent_kernel', 'clikernel/mcp.py'),
|
|
41
|
+
'clikernel.mcp.Router._reap_loop': ('mcp.html#router._reap_loop', 'clikernel/mcp.py'),
|
|
42
|
+
'clikernel.mcp.Router._send': ('mcp.html#router._send', 'clikernel/mcp.py'),
|
|
37
43
|
'clikernel.mcp.Router.aclose': ('mcp.html#router.aclose', 'clikernel/mcp.py'),
|
|
38
44
|
'clikernel.mcp.Router.dispatch': ('mcp.html#router.dispatch', 'clikernel/mcp.py'),
|
|
39
45
|
'clikernel.mcp.Router.session': ('mcp.html#router.session', 'clikernel/mcp.py'),
|
|
40
46
|
'clikernel.mcp.Router.tools': ('mcp.html#router.tools', 'clikernel/mcp.py'),
|
|
41
47
|
'clikernel.mcp._cap_images': ('mcp.html#_cap_images', 'clikernel/mcp.py'),
|
|
48
|
+
'clikernel.mcp._cut_utf8': ('mcp.html#_cut_utf8', 'clikernel/mcp.py'),
|
|
49
|
+
'clikernel.mcp._full_body': ('mcp.html#_full_body', 'clikernel/mcp.py'),
|
|
50
|
+
'clikernel.mcp._hook_response': ('mcp.html#_hook_response', 'clikernel/mcp.py'),
|
|
51
|
+
'clikernel.mcp._is_no_current': ('mcp.html#_is_no_current', 'clikernel/mcp.py'),
|
|
52
|
+
'clikernel.mcp._page': ('mcp.html#_page', 'clikernel/mcp.py'),
|
|
53
|
+
'clikernel.mcp._stack': ('mcp.html#_stack', 'clikernel/mcp.py'),
|
|
42
54
|
'clikernel.mcp.agent_input': ('mcp.html#agent_input', 'clikernel/mcp.py'),
|
|
43
55
|
'clikernel.mcp.hook': ('mcp.html#hook', 'clikernel/mcp.py'),
|
|
44
56
|
'clikernel.mcp.main': ('mcp.html#main', 'clikernel/mcp.py')}}}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"""Gateway naming, startup delivery, and MCP sessions on
|
|
1
|
+
"""Gateway naming, startup delivery, and MCP sessions on jupygate gateways
|
|
2
2
|
|
|
3
|
-
[
|
|
3
|
+
[Jupygate](https://github.com/AnswerDotAI/jupygate) hosts kernels and serves MCP requests at `POST /mcp`. Clikernel runs alongside it for the duration of a conversation. It routes the LLM client's stdio MCP requests to gateways.
|
|
4
4
|
|
|
5
5
|
This module connects to those gateways. `gateways.toml` gives them names. `session_defaults` supplies kernel startup code and, for a local gateway, the conversation's working directory and environment. It sends `startup.py` as source, so it can run on another machine.
|
|
6
6
|
|
|
7
7
|
`Gateway` represents one MCP session on one gateway. `default_gateway` connects to the local gateway or starts a child process if it cannot connect. The caller must stop any returned child. The MCP router does this when the conversation ends.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Jupygate tracks the session's current kernel and which kernels it created. Ending a session stops its autoclose kernels. It leaves other kernels running. Stopping an owned gateway process stops all kernels in that process.
|
|
10
10
|
|
|
11
11
|
Docs: https://AnswerDotAI.github.io/clikernel/core.html.md"""
|
|
12
12
|
|
|
@@ -17,10 +17,11 @@ __all__ = ['DEFAULT_URL', 'cfg_dir', 'gateways', 'resolve', 'startup_src', 'sess
|
|
|
17
17
|
|
|
18
18
|
# %% ../nbs/00_core.ipynb #2b3b7f4a
|
|
19
19
|
import os, inspect, tomllib, httpx
|
|
20
|
+
from contextlib import suppress
|
|
20
21
|
from fastcore.utils import *
|
|
21
22
|
from fastcore.xdg import xdg_config_home
|
|
22
23
|
from mcpmini.core import HTTPTransport, jreq
|
|
23
|
-
from
|
|
24
|
+
from jupyasyncclient import start_gateway
|
|
24
25
|
from . import __version__
|
|
25
26
|
|
|
26
27
|
# %% ../nbs/00_core.ipynb #596419b8
|
|
@@ -37,7 +38,8 @@ def gateways(cfgdir=None):
|
|
|
37
38
|
|
|
38
39
|
def resolve(host='', cfgdir=None):
|
|
39
40
|
"Resolve an empty host, URL, or configured gateway name to `(url, token, verify)`."
|
|
40
|
-
|
|
41
|
+
host = host or os.environ.get('CLIKERNEL_HOST') or ''
|
|
42
|
+
if not host: return DEFAULT_URL, os.environ.get('CLIKERNEL_TOKEN'), True
|
|
41
43
|
if '://' in host: return host, os.environ.get('CLIKERNEL_TOKEN'), True
|
|
42
44
|
cfgdir = Path(cfgdir) if cfgdir else cfg_dir()
|
|
43
45
|
g = gateways(cfgdir).get(host)
|
|
@@ -78,7 +80,7 @@ def startup_src(cfgdir=None):
|
|
|
78
80
|
return '\n'.join(parts)
|
|
79
81
|
|
|
80
82
|
def session_defaults(cfgdir=None, quiet=False, local=True):
|
|
81
|
-
"Return startup and quiet settings for
|
|
83
|
+
"Return startup and quiet settings for jupygate initialization. Local sessions also include cwd and env; named hosts, the Claude Code session id."
|
|
82
84
|
d = dict(startup=startup_src(cfgdir), quiet=quiet)
|
|
83
85
|
if local: d.update(cwd=os.getcwd(), env=dict(os.environ))
|
|
84
86
|
elif sid := os.environ.get('CLAUDE_CODE_SESSION_ID'): d['env'] = dict(CLAUDE_CODE_SESSION_ID=sid)
|
|
@@ -86,7 +88,7 @@ def session_defaults(cfgdir=None, quiet=False, local=True):
|
|
|
86
88
|
|
|
87
89
|
# %% ../nbs/00_core.ipynb #10ed59fc
|
|
88
90
|
class Gateway:
|
|
89
|
-
"Open an MCP session on
|
|
91
|
+
"Open an MCP session on jupygate, call its tools, and end the session with DELETE."
|
|
90
92
|
def __init__(
|
|
91
93
|
self,
|
|
92
94
|
url, # The gateway base URL, e.g. 'http://127.0.0.1:8787'
|
|
@@ -105,13 +107,19 @@ class Gateway:
|
|
|
105
107
|
return r['result']
|
|
106
108
|
|
|
107
109
|
async def initialize(self, defaults=None):
|
|
108
|
-
"Open the MCP session with `defaults` in the `
|
|
110
|
+
"Open the MCP session with `defaults` in the `jupygate` extension. Return self."
|
|
109
111
|
await self.tr.start()
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
112
|
+
try:
|
|
113
|
+
self.info = await self.rpc('initialize', protocolVersion='2025-11-25', capabilities={},
|
|
114
|
+
clientInfo=dict(name='clikernel', version=__version__), jupygate=defaults or {})
|
|
115
|
+
if defaults and not self.info.get('jupygate'):
|
|
116
|
+
raise RuntimeError(f'gateway at {self.url} did not acknowledge jupygate session defaults; upgrade the gateway')
|
|
117
|
+
self.tr.proto = self.info['protocolVersion']
|
|
118
|
+
await self.tr.send(jreq('notifications/initialized'))
|
|
119
|
+
return self
|
|
120
|
+
except BaseException:
|
|
121
|
+
with suppress(Exception): await self.aclose()
|
|
122
|
+
raise
|
|
115
123
|
|
|
116
124
|
# %% ../nbs/00_core.ipynb #2dd701f9
|
|
117
125
|
@patch
|
|
@@ -138,11 +146,17 @@ async def aclose(self:Gateway):
|
|
|
138
146
|
async def default_gateway(
|
|
139
147
|
cfgdir=None, # Config dir for `session_defaults` (the standard one if None)
|
|
140
148
|
quiet=False, # Keep startup output out of replies?
|
|
149
|
+
url=DEFAULT_URL, # Local gateway URL to try before spawning a child (ignored when `CLIKERNEL_HOST` is set)
|
|
141
150
|
):
|
|
142
151
|
"Return an initialized `Gateway` and its new child process, or None if it reused a gateway. The caller must stop any child."
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
152
|
+
if host := os.environ.get('CLIKERNEL_HOST'):
|
|
153
|
+
u, token, verify = resolve(host, cfgdir)
|
|
154
|
+
return await Gateway(u, token, verify).initialize(session_defaults(cfgdir, quiet, local=False)), None
|
|
155
|
+
d = session_defaults(cfgdir, quiet, local=True)
|
|
156
|
+
try: return await Gateway(url, os.environ.get('CLIKERNEL_TOKEN'), True).initialize(d), None
|
|
146
157
|
except httpx.ConnectError:
|
|
147
158
|
child = start_gateway()
|
|
148
|
-
return await Gateway(child.url).initialize(d), child
|
|
159
|
+
try: return await Gateway(child.url).initialize(d), child
|
|
160
|
+
except BaseException:
|
|
161
|
+
child.stop()
|
|
162
|
+
raise
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""Route stdio MCP requests to jupygate gateways
|
|
2
|
+
|
|
3
|
+
Claude Code starts `clikernel-mcp` for each conversation. Its `Router` accepts MCP messages over stdio and sends tool calls to jupygate gateways. Jupygate implements the tools. The router gets their schemas from the local gateway and adds `host` to `list_kernels`, `use_kernel`, and `create`.
|
|
4
|
+
|
|
5
|
+
Each `(host, agent)` pair has its own gateway session, with `JUPYGATE_AGENT` passed in subagent `initialize` defaults. Calls without an explicit `host` go to their caller's current host; a subagent starts on the main conversation's current host. On a subagent's first `exec` with no current kernel, the router lazily creates a kernel matching the main session's current kernel implementation. Idle subagent sessions close with `DELETE /mcp` after 30 minutes. The router removes `host` and `agent` before forwarding a call while preserving JSON-RPC request ids and routing cancellations to the caller's session.
|
|
6
|
+
|
|
7
|
+
Before forwarding `exec`, the router intercepts `%cont` to page through truncated replies and checks all other cells against `clikernel.rules`. Most rules add a note to the reply. Two rules block the cell, which then never reaches a gateway. Replies over `maxout` UTF-8 bytes are saved to a temporary file and returned in chunks.
|
|
8
|
+
|
|
9
|
+
`main` closes its gateway sessions on EOF, SIGTERM, or an exception. Closing a session sends an HTTP DELETE. The gateway then stops the kernels that session created with autoclose. If the router started a child gateway, it stops that process too, and removes any temporary output directory.
|
|
10
|
+
|
|
11
|
+
Docs: https://AnswerDotAI.github.io/clikernel/mcp.html.md"""
|
|
12
|
+
|
|
13
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_mcp.ipynb.
|
|
14
|
+
|
|
15
|
+
# %% auto #0
|
|
16
|
+
__all__ = ['HOST_PARAM', 'HOSTED', 'MAXOUT', 'AGENT_IDLE', 'AGENT_KERNEL', 'Router', 'main', 'agent_input', 'hook']
|
|
17
|
+
|
|
18
|
+
# %% ../nbs/01_mcp.ipynb #28c42902
|
|
19
|
+
import asyncio, httpx, json, re, signal, tempfile, time
|
|
20
|
+
from contextlib import suppress
|
|
21
|
+
from fastcore.utils import *
|
|
22
|
+
from fastcore.script import call_parse, store_true
|
|
23
|
+
from mcpmini.core import serve_stdio, jresp, jerr
|
|
24
|
+
from .core import DEFAULT_URL, Gateway, default_gateway, resolve, session_defaults
|
|
25
|
+
from .rules import scan
|
|
26
|
+
from . import __version__
|
|
27
|
+
|
|
28
|
+
# %% ../nbs/01_mcp.ipynb #76e2d782
|
|
29
|
+
HOST_PARAM = {'type': 'string', 'description': 'Gateway to target: a gateways.toml name, or empty for the default local gateway'}
|
|
30
|
+
HOSTED = ('list_kernels', 'use_kernel', 'create')
|
|
31
|
+
MAXOUT = 40_000
|
|
32
|
+
AGENT_IDLE = 1800
|
|
33
|
+
AGENT_KERNEL = "New kernel for this subagent: names from any other kernel, the parent's included, aren't defined here."
|
|
34
|
+
_CONT_RE = re.compile(r'^%cont(?:\s+(\S+))?$')
|
|
35
|
+
|
|
36
|
+
class Router:
|
|
37
|
+
"Route stdio MCP to jupygate with one backend session per `(host, agent)` and a current host for each caller."
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
cfgdir=None, # Config dir for `session_defaults` and `gateways.toml` (the standard one if None)
|
|
41
|
+
quiet=False, # Keep startup output and rule notes out of replies?
|
|
42
|
+
maxout=MAXOUT, # Max UTF-8 bytes per text reply (0 or None disables capping)
|
|
43
|
+
url=DEFAULT_URL, # Local gateway URL to try before spawning a child (ignored when `CLIKERNEL_HOST` is set)
|
|
44
|
+
agent_idle=AGENT_IDLE, # Seconds before closing an idle subagent session (0 or None disables)
|
|
45
|
+
):
|
|
46
|
+
self.cfgdir,self.quiet,self.maxout,self.url,self.agent_idle = cfgdir,quiet,maxout,url,agent_idle
|
|
47
|
+
self.sessions,self.cur,self.inflight,self.child = {},{},{},None
|
|
48
|
+
self._tmpdir,self._out_seq,self._conts,self._last = None,0,{},{}
|
|
49
|
+
self._init_locks,self._agent_locks,self._agent_gen,self._last_used,self._reaper = {},{},{},{},None
|
|
50
|
+
|
|
51
|
+
async def session(self, host='', agent=None):
|
|
52
|
+
"Return the session for `(host, agent)`, initializing it on first use. Empty `host` selects the default local gateway."
|
|
53
|
+
key = (host, agent)
|
|
54
|
+
if key not in self.sessions:
|
|
55
|
+
async with self._init_locks.setdefault(key, asyncio.Lock()):
|
|
56
|
+
if key not in self.sessions:
|
|
57
|
+
if not host and agent is not None: await self.session('')
|
|
58
|
+
d = session_defaults(self.cfgdir, self.quiet, local=not host and not os.environ.get('CLIKERNEL_HOST'))
|
|
59
|
+
if agent is not None: d.setdefault('env', {})['JUPYGATE_AGENT'] = agent
|
|
60
|
+
if host: url, token, verify = resolve(host, self.cfgdir)
|
|
61
|
+
elif self.child: url, token, verify = self.child.url, None, True
|
|
62
|
+
elif ch := os.environ.get('CLIKERNEL_HOST'): url, token, verify = resolve(ch, self.cfgdir)
|
|
63
|
+
elif agent is None:
|
|
64
|
+
self.sessions[key], self.child = await default_gateway(self.cfgdir, self.quiet, url=self.url)
|
|
65
|
+
return self.sessions[key]
|
|
66
|
+
else: url, token, verify = self.url, os.environ.get('CLIKERNEL_TOKEN'), True
|
|
67
|
+
self.sessions[key] = await Gateway(url, token, verify).initialize(d)
|
|
68
|
+
if agent is not None:
|
|
69
|
+
self._last_used[key] = time.monotonic()
|
|
70
|
+
if self.agent_idle and (self._reaper is None or self._reaper.done()):
|
|
71
|
+
self._reaper = asyncio.create_task(self._reap_loop())
|
|
72
|
+
return self.sessions[key]
|
|
73
|
+
|
|
74
|
+
async def _reap_loop(self):
|
|
75
|
+
while any(a is not None for _, a in self.sessions):
|
|
76
|
+
await asyncio.sleep(max(0.05, min(60.0, self.agent_idle / 2)))
|
|
77
|
+
now, active = time.monotonic(), set(self.inflight.values())
|
|
78
|
+
stale = [k for k, s in list(self.sessions.items())
|
|
79
|
+
if k[1] is not None and s not in active and now - self._last_used.get(k, now) >= self.agent_idle]
|
|
80
|
+
for k in stale:
|
|
81
|
+
s = self.sessions.pop(k, None)
|
|
82
|
+
for m in (self._last_used, self._init_locks, self._agent_locks, self._agent_gen): m.pop(k, None)
|
|
83
|
+
if s:
|
|
84
|
+
with suppress(Exception): await s.aclose()
|
|
85
|
+
|
|
86
|
+
# %% ../nbs/01_mcp.ipynb #79da6a3e
|
|
87
|
+
@patch
|
|
88
|
+
async def tools(self:Router):
|
|
89
|
+
"Return the local gateway's tools with `host` added to `list_kernels`, `use_kernel`, and `create`, and `create.kernel` unconstrained for remote hosts."
|
|
90
|
+
ts = await (await self.session()).tools()
|
|
91
|
+
for t in ts:
|
|
92
|
+
props = t['inputSchema'].setdefault('properties', {})
|
|
93
|
+
if t['name'] in HOSTED: props['host'] = dict(HOST_PARAM)
|
|
94
|
+
if t['name'] == 'create' and 'kernel' in props: props['kernel'].pop('enum', None)
|
|
95
|
+
return ts
|
|
96
|
+
|
|
97
|
+
# %% ../nbs/01_mcp.ipynb #6da913bf
|
|
98
|
+
def _cap_images(content, budget=5 << 20):
|
|
99
|
+
"`content`, with each image that would take the total base64 image data past `budget` bytes replaced by a line of text."
|
|
100
|
+
left,res = budget,[]
|
|
101
|
+
for b in content:
|
|
102
|
+
if b['type'] == 'image':
|
|
103
|
+
if (n := len(b['data'])) > left: b = dict(type='text', text=f"[{b['mimeType']} image of {n:,} bytes omitted: images in one reply are limited to {budget:,} bytes]")
|
|
104
|
+
else: left -= n
|
|
105
|
+
res.append(b)
|
|
106
|
+
return res
|
|
107
|
+
|
|
108
|
+
# %% ../nbs/01_mcp.ipynb #2d413a54
|
|
109
|
+
def _cut_utf8(b, budget, snap=256):
|
|
110
|
+
"Byte index <= `budget` in UTF-8 bytes `b` on a char boundary, snapping back to a nearby newline."
|
|
111
|
+
end = min(budget, len(b))
|
|
112
|
+
while end > 0 and end < len(b) and (b[end] & 0xC0) == 0x80: end -= 1
|
|
113
|
+
if end == 0 and b:
|
|
114
|
+
end = 1
|
|
115
|
+
while end < len(b) and (b[end] & 0xC0) == 0x80: end += 1
|
|
116
|
+
elif end < len(b):
|
|
117
|
+
nl = b.rfind(b'\n', max(end // 2, end - snap), end)
|
|
118
|
+
if nl >= 0: end = nl + 1
|
|
119
|
+
return end
|
|
120
|
+
|
|
121
|
+
def _page(data, offset, budget, mk_footer, full=False):
|
|
122
|
+
"Return `(text, new_offset)` fitting `data[offset:]` plus footer and `𝍁…𝍁` wrapper within `budget` UTF-8 bytes."
|
|
123
|
+
wrap = 8 if full else 0
|
|
124
|
+
tail = data[offset:]
|
|
125
|
+
if len(tail) + wrap <= budget:
|
|
126
|
+
body = tail.decode('utf-8')
|
|
127
|
+
return (f'𝍁{body}𝍁' if full else body), len(data)
|
|
128
|
+
avail = budget - wrap - len(mk_footer(len(tail)).encode('utf-8'))
|
|
129
|
+
end = _cut_utf8(tail, max(1, avail))
|
|
130
|
+
body = tail[:end].decode('utf-8') + mk_footer(len(tail) - end)
|
|
131
|
+
return (f'𝍁{body}𝍁' if full else body), offset + end
|
|
132
|
+
|
|
133
|
+
# %% ../nbs/01_mcp.ipynb #d3fc7e55
|
|
134
|
+
@patch
|
|
135
|
+
def _cap_text(self:Router, content, agent, note=''):
|
|
136
|
+
"Cap text blocks in `content` (plus optional `note`) to `self.maxout` UTF-8 bytes, saving overflow for `%cont`."
|
|
137
|
+
note_blk = [dict(type='text', text=note)] if note else []
|
|
138
|
+
if not self.maxout: return note_blk + content
|
|
139
|
+
joined = ''.join(b.get('text', '') for b in content if b['type'] == 'text')
|
|
140
|
+
note_bytes = len(note.encode('utf-8')) + 1 if note else 0
|
|
141
|
+
if len(joined.encode('utf-8')) + note_bytes <= self.maxout: return note_blk + content
|
|
142
|
+
full = joined.startswith('𝍁') and joined.endswith('𝍁') and len(joined) >= 2
|
|
143
|
+
data = (joined[1:-1] if full else joined).encode('utf-8')
|
|
144
|
+
if self._tmpdir is None: self._tmpdir = tempfile.TemporaryDirectory(prefix='clikernel-')
|
|
145
|
+
self._out_seq += 1
|
|
146
|
+
oid = str(self._out_seq)
|
|
147
|
+
path = Path(self._tmpdir.name)/f'out_{oid}.txt'
|
|
148
|
+
path.write_bytes(data)
|
|
149
|
+
total = len(data)
|
|
150
|
+
mk_foot = lambda rem: f'\n[truncated: {rem:,} of {total:,} bytes left; full output: {path}; %cont or %cont {oid} for next]'
|
|
151
|
+
chunk, offset = _page(data, 0, self.maxout - note_bytes, mk_foot, full=full)
|
|
152
|
+
if offset < total:
|
|
153
|
+
self._conts.setdefault(agent, {})[oid] = (path, offset, full, total)
|
|
154
|
+
self._last[agent] = oid
|
|
155
|
+
return note_blk + [dict(type='text', text=chunk)] + [b for b in content if b['type'] != 'text']
|
|
156
|
+
|
|
157
|
+
# %% ../nbs/01_mcp.ipynb #39420ce7
|
|
158
|
+
@patch
|
|
159
|
+
def _cont(self:Router, agent, oid=None):
|
|
160
|
+
"Return the next chunk of a truncated reply for `agent`, optionally selecting `oid`."
|
|
161
|
+
aconts = self._conts.get(agent) or {}
|
|
162
|
+
key = oid or self._last.get(agent)
|
|
163
|
+
if not key or key not in aconts:
|
|
164
|
+
msg = f'No pending output with id {oid}.' if oid else 'No pending output to continue.'
|
|
165
|
+
return dict(isError=True, content=[dict(type='text', text=msg)])
|
|
166
|
+
path, offset, full, total = aconts[key]
|
|
167
|
+
data = path.read_bytes()
|
|
168
|
+
mk_foot = lambda rem: f'\n[{rem:,} of {total:,} bytes left; %cont or %cont {key} for next]'
|
|
169
|
+
chunk, new_offset = _page(data, offset, self.maxout, mk_foot, full=full)
|
|
170
|
+
if new_offset >= total:
|
|
171
|
+
aconts.pop(key, None)
|
|
172
|
+
if self._last.get(agent) == key: self._last.pop(agent, None)
|
|
173
|
+
else:
|
|
174
|
+
aconts[key] = (path, new_offset, full, total)
|
|
175
|
+
self._last[agent] = key
|
|
176
|
+
return dict(content=[dict(type='text', text=chunk)])
|
|
177
|
+
|
|
178
|
+
# %% ../nbs/01_mcp.ipynb #1cb7fe77
|
|
179
|
+
def _full_body(t): return t[1:-1] if len(t) >= 2 and t[0] == '𝍁' and t[-1] == '𝍁' else None
|
|
180
|
+
|
|
181
|
+
def _stack(blocks):
|
|
182
|
+
"Combine MCP reply blocks in order, keeping `𝍁…𝍁` around the combined text if any text block is marked full."
|
|
183
|
+
out = [dict(b) for b in blocks]
|
|
184
|
+
for b in out[:-1]:
|
|
185
|
+
if (t := b.get('text')) and not t.endswith('\n'): b['text'] = t + '\n'
|
|
186
|
+
if any((t := b.get('text')) is not None and _full_body(t.rstrip('\n')) is not None for b in out):
|
|
187
|
+
parts, rest = [], []
|
|
188
|
+
for b in out:
|
|
189
|
+
if (t := b.get('text')) is None: rest.append(b)
|
|
190
|
+
else:
|
|
191
|
+
body = t.rstrip('\n')
|
|
192
|
+
inner = _full_body(body)
|
|
193
|
+
parts.append((body if inner is None else inner) + t[len(body):])
|
|
194
|
+
return [dict(type='text', text='𝍁' + ''.join(parts) + '𝍁'), *rest]
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
def _is_no_current(res):
|
|
198
|
+
r = res.get('result') if res else None
|
|
199
|
+
return bool(r and r.get('isError') and 'no current kernel' in ''.join(b.get('text', '') for b in r.get('content', [])))
|
|
200
|
+
|
|
201
|
+
@patch
|
|
202
|
+
async def _send(self:Router, h, agent, msg):
|
|
203
|
+
key, rid = (h, agent), msg['id']
|
|
204
|
+
s = await self.session(h, agent)
|
|
205
|
+
self.inflight[rid] = s
|
|
206
|
+
if agent is not None: self._last_used[key] = time.monotonic()
|
|
207
|
+
try:
|
|
208
|
+
try: return s, await s.tr.send(msg)
|
|
209
|
+
except httpx.HTTPStatusError as e:
|
|
210
|
+
if e.response.status_code != 404: raise
|
|
211
|
+
self.sessions.pop(key, None)
|
|
212
|
+
s = await self.session(h, agent)
|
|
213
|
+
self.inflight[rid] = s
|
|
214
|
+
return s, await s.tr.send(msg)
|
|
215
|
+
finally:
|
|
216
|
+
if agent is not None and key in self.sessions: self._last_used[key] = time.monotonic()
|
|
217
|
+
|
|
218
|
+
@patch
|
|
219
|
+
async def _parent_kernel(self:Router, h):
|
|
220
|
+
s = self.sessions.get((h, None))
|
|
221
|
+
if not s: return None
|
|
222
|
+
try: r = await s.call('list_kernels')
|
|
223
|
+
except httpx.HTTPStatusError as e:
|
|
224
|
+
if e.response.status_code != 404: raise
|
|
225
|
+
self.sessions.pop((h, None), None)
|
|
226
|
+
return None
|
|
227
|
+
if r.get('isError'): return None
|
|
228
|
+
txt = ''.join(b.get('text', '') for b in r.get('content', []) if b.get('type') == 'text')
|
|
229
|
+
for line in txt.splitlines():
|
|
230
|
+
if line.endswith('<- current') and (m := re.search(r'\bkernel=(\S+)', line)): return m.group(1)
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
@patch
|
|
234
|
+
async def _ensure_agent_kernel(self:Router, h, agent, s, cwd, gen):
|
|
235
|
+
key = (h, agent)
|
|
236
|
+
async with self._agent_locks.setdefault(key, asyncio.Lock()):
|
|
237
|
+
if self._agent_gen.get(key, 0) != gen: return []
|
|
238
|
+
impl = await self._parent_kernel(h)
|
|
239
|
+
if not impl: return None
|
|
240
|
+
kw = dict(kernel=impl)
|
|
241
|
+
if cwd: kw['cwd'] = cwd
|
|
242
|
+
r = await s.call('create', **kw)
|
|
243
|
+
if r.get('isError'): return r
|
|
244
|
+
self._agent_gen[key] = gen + 1
|
|
245
|
+
return [dict(type='text', text=AGENT_KERNEL), *r['content']]
|
|
246
|
+
|
|
247
|
+
# %% ../nbs/01_mcp.ipynb #e1b057dd
|
|
248
|
+
@patch
|
|
249
|
+
async def dispatch(self:Router, msg, requester=None):
|
|
250
|
+
"Answer initialization and ping locally. Forward tool calls to gateways."
|
|
251
|
+
method,id = msg.get('method'), msg.get('id')
|
|
252
|
+
try:
|
|
253
|
+
if method == 'initialize':
|
|
254
|
+
info = (await self.session()).info
|
|
255
|
+
return jresp(id, dict(protocolVersion=msg['params'].get('protocolVersion', '2025-06-18'), capabilities=dict(tools={}),
|
|
256
|
+
serverInfo=dict(name='clikernel', version=__version__), instructions=info.get('instructions')))
|
|
257
|
+
if id is None:
|
|
258
|
+
if method == 'notifications/cancelled' and (s := self.inflight.get(msg['params'].get('requestId'))) is not None:
|
|
259
|
+
await s.tr.send(msg)
|
|
260
|
+
return None
|
|
261
|
+
if method == 'ping': return jresp(id, {})
|
|
262
|
+
if method == 'tools/list': return jresp(id, dict(tools=await self.tools()))
|
|
263
|
+
if method == 'tools/call':
|
|
264
|
+
args = msg['params'].setdefault('arguments', {})
|
|
265
|
+
agent = args.pop('agent', None) or None
|
|
266
|
+
tool = msg['params']['name']
|
|
267
|
+
if tool == 'exec' and (m := _CONT_RE.match(args.get('code', '').strip())): return jresp(id, self._cont(agent, m.group(1)))
|
|
268
|
+
fired = scan(args.get('code', '')) if tool == 'exec' else []
|
|
269
|
+
if blocks := [r.note for r in fired if r.block]:
|
|
270
|
+
return jresp(id, dict(isError=True, content=[dict(type='text', text=' '.join(blocks)+' (If the block seems wrong here, tell your user.)')]))
|
|
271
|
+
has_host = 'host' in args
|
|
272
|
+
host = args.pop('host', '') or ''
|
|
273
|
+
h = host if has_host else self.cur.setdefault(agent, self.cur.get(None, ''))
|
|
274
|
+
if h or os.environ.get('CLIKERNEL_HOST'): args.pop('cwd', None)
|
|
275
|
+
cwd = args.pop('cwd', None) if tool == 'exec' else None
|
|
276
|
+
gen = self._agent_gen.get((h, agent), 0) if agent is not None else 0
|
|
277
|
+
try:
|
|
278
|
+
s, res = await self._send(h, agent, msg)
|
|
279
|
+
if agent is not None and tool == 'exec' and _is_no_current(res):
|
|
280
|
+
opened = await self._ensure_agent_kernel(h, agent, s, cwd, gen)
|
|
281
|
+
if isinstance(opened, dict): res = jresp(id, opened)
|
|
282
|
+
elif opened is not None:
|
|
283
|
+
_, res = await self._send(h, agent, msg)
|
|
284
|
+
if opened and res and 'result' in res and not res['result'].get('isError'):
|
|
285
|
+
res['result']['content'] = _stack(opened + res['result']['content'])
|
|
286
|
+
finally: self.inflight.pop(id, None)
|
|
287
|
+
if res and 'result' in res:
|
|
288
|
+
if has_host and tool in ('use_kernel', 'create') and not res['result'].get('isError'):
|
|
289
|
+
self.cur[agent] = host
|
|
290
|
+
content = _cap_images(res['result']['content'])
|
|
291
|
+
note = ''.join(f'<note>\n{r.note}\n</note>\n' for r in fired) if fired and not self.quiet else ''
|
|
292
|
+
res['result']['content'] = self._cap_text(content, agent, note=note)
|
|
293
|
+
return res
|
|
294
|
+
return jerr(id, -32601, f'method not found: {method}')
|
|
295
|
+
except Exception as e: return None if id is None else jerr(id, -32603, str(e))
|
|
296
|
+
|
|
297
|
+
# %% ../nbs/01_mcp.ipynb #f72f6253
|
|
298
|
+
@patch
|
|
299
|
+
async def aclose(self:Router):
|
|
300
|
+
"Close all sessions and their autoclose kernels, remove any temporary output directory, then stop any owned gateway."
|
|
301
|
+
if self._reaper and not self._reaper.done():
|
|
302
|
+
self._reaper.cancel()
|
|
303
|
+
with suppress(asyncio.CancelledError): await self._reaper
|
|
304
|
+
sessions = list(self.sessions.values())
|
|
305
|
+
self.sessions.clear()
|
|
306
|
+
try: results = await asyncio.gather(*(s.aclose() for s in sessions), return_exceptions=True)
|
|
307
|
+
finally:
|
|
308
|
+
if self.child:
|
|
309
|
+
self.child.stop()
|
|
310
|
+
self.child = None
|
|
311
|
+
if self._tmpdir:
|
|
312
|
+
self._tmpdir.cleanup()
|
|
313
|
+
self._tmpdir = None
|
|
314
|
+
errors = [r for r in results if isinstance(r, BaseException)]
|
|
315
|
+
if errors: raise BaseExceptionGroup('MCP session cleanup failed', errors)
|
|
316
|
+
|
|
317
|
+
# %% ../nbs/01_mcp.ipynb #3b90f0e8
|
|
318
|
+
@call_parse
|
|
319
|
+
def main(
|
|
320
|
+
quiet:store_true=False, # Keep startup output and rule notes out of replies
|
|
321
|
+
cfgdir:str=None, # Directory holding `startup.py` and `gateways.toml`; `~/.config/clikernel/` if unset
|
|
322
|
+
maxout:int=MAXOUT, # Max UTF-8 bytes per text reply (0 disables capping)
|
|
323
|
+
):
|
|
324
|
+
"Run `clikernel-mcp` as a stdio server."
|
|
325
|
+
async def _main():
|
|
326
|
+
router = Router(cfgdir, quiet=quiet, maxout=maxout)
|
|
327
|
+
loop,task = asyncio.get_running_loop(),asyncio.current_task()
|
|
328
|
+
signal.signal(signal.SIGTERM, lambda *_: loop.call_soon_threadsafe(task.cancel))
|
|
329
|
+
try: await serve_stdio(router)
|
|
330
|
+
finally: await router.aclose()
|
|
331
|
+
asyncio.run(_main())
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
# %% ../nbs/01_mcp.ipynb #bc8afe8c
|
|
335
|
+
def agent_input(
|
|
336
|
+
event:dict, # A Claude Code `PreToolUse` hook event
|
|
337
|
+
):
|
|
338
|
+
"`event`'s tool input with `agent` set to the calling subagent's id, or None for a call from the main conversation."
|
|
339
|
+
if aid := event.get('agent_id'): return event['tool_input'] | dict(agent=aid)
|
|
340
|
+
|
|
341
|
+
# %% ../nbs/01_mcp.ipynb #105e6780
|
|
342
|
+
def _hook_response(event:dict):
|
|
343
|
+
if 'toolCall' in event:
|
|
344
|
+
tc = event['toolCall']
|
|
345
|
+
args, cid = tc.get('args') or {}, event.get('conversationId')
|
|
346
|
+
cwd = event.get('cwd') or first(event.get('workspacePaths') or ()) or ''
|
|
347
|
+
extra = {k: v for k, v in dict(agent=cid, cwd=cwd).items() if v}
|
|
348
|
+
if tc.get('name') == 'call_mcp_tool':
|
|
349
|
+
srv = args.get('ServerName') or ''
|
|
350
|
+
if extra and (srv == 'clikernel' or srv.endswith('_clikernel')):
|
|
351
|
+
return dict(decision='allow', overwrite=dict(Arguments=(args.get('Arguments') or {}) | extra))
|
|
352
|
+
elif extra: return dict(decision='allow', overwrite=extra)
|
|
353
|
+
return dict(decision='ask')
|
|
354
|
+
if upd := agent_input(event):
|
|
355
|
+
return dict(hookSpecificOutput=dict(hookEventName='PreToolUse', updatedInput=upd))
|
|
356
|
+
|
|
357
|
+
def hook():
|
|
358
|
+
"Run `clikernel-hook`: read a `PreToolUse` event on stdin and print the hook response giving each caller its own kernel."
|
|
359
|
+
if resp := _hook_response(json.load(sys.stdin)): print(json.dumps(resp))
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# NB: this file is designed for an LLM reader, not a human. Add it to your LLM's context and ask it to explain.
|
|
2
|
+
r"""Use `clikernel` MCP as the default persistent Python workspace for file/notebook reads and edits, exploration, library checks, data reshaping and debugging. Imports and variables carry across calls. Read before writing, running or debugging Python with `clikernel` connected.
|
|
3
|
+
|
|
4
|
+
- prefer: clikernel over one-off scripts (`python -c`, heredocs); pyskills over shell (rgapi `rg` `fd` `ls`; ghapi: GitHub, git); shell: project tests, builds, non-Python tools
|
|
5
|
+
- outlive conversation: `create(kernel="py", autoclose=false)`, tell user its id; reply shows gateway started by this conversation: say so /kernel needs a lasting gateway
|
|
6
|
+
- earlier or user's solveit kernel: `list_kernels` → `use_kernel(id)`
|
|
7
|
+
- `restart`: reruns that kernel's startup; redo interactive setup; `interrupt` keeps state
|
|
8
|
+
- `host=` names: `~/.config/clikernel/gateways.toml`; later `exec` stays on that host
|
|
9
|
+
- replies >`--maxout` bytes: first chunk inline + full-output temp file; `%cont` or `%cont <id>` in `exec` for next chunk; huge: `rg`/`open_doc` on temp file
|
|
10
|
+
|
|
11
|
+
# Python
|
|
12
|
+
|
|
13
|
+
- magics work, `%%bash` too; `%cd` (expands `~`), not `os.chdir`
|
|
14
|
+
- top-level expressions display, not those in blocks (clikernel default; startup can override)
|
|
15
|
+
- outputs reach conversation up to `--maxout`: `len(v)` first
|
|
16
|
+
- imports: once; `NameError` for your name: kernel restarted or attached: redo setup
|
|
17
|
+
- after `nbdev-export` or module edit: `importlib.reload`, re-import held names (`from x import y` keeps old object); `@patch` refreshes; restart only if a held instance's class changed
|
|
18
|
+
- loaded behavior: call it, never `inspect.getsource` /reads disk
|
|
19
|
+
- before env changes, monkeypatching, extra setup: try the plain import or call
|
|
20
|
+
"""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: clikernel
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.21
|
|
4
4
|
Summary: Serve persistent Jupyter kernels to LLMs as concise text, over MCP or a plain stream protocol
|
|
5
5
|
Author: clikernel contributors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -12,10 +12,9 @@ Requires-Python: >=3.11
|
|
|
12
12
|
Description-Content-Type: text/markdown
|
|
13
13
|
License-File: LICENSE
|
|
14
14
|
Requires-Dist: fastcore>=2.2.2
|
|
15
|
-
Requires-Dist: jupyasyncclient>=0.2.
|
|
16
|
-
Requires-Dist: jupywire>=0.1.9
|
|
15
|
+
Requires-Dist: jupyasyncclient>=0.2.32
|
|
17
16
|
Requires-Dist: mcpmini>=0.0.5
|
|
18
|
-
Requires-Dist:
|
|
17
|
+
Requires-Dist: jupygate>=0.1.0
|
|
19
18
|
Requires-Dist: ipymini>=0.1.28
|
|
20
19
|
Requires-Dist: httpx
|
|
21
20
|
Requires-Dist: ipython
|
|
@@ -30,7 +29,7 @@ Dynamic: license-file
|
|
|
30
29
|
|
|
31
30
|
`clikernel` gives LLM agents persistent kernel sessions over MCP or a plain stream protocol. Imports, variables, and results remain available between calls. Agents can create kernels or attach to existing ones, including a user’s live solveit kernel.
|
|
32
31
|
|
|
33
|
-
[
|
|
32
|
+
[jupygate](https://github.com/AnswerDotAI/jupygate) hosts the kernels. Clikernel routes requests to local or named remote gateways and supplies startup code to Python kernels.
|
|
34
33
|
|
|
35
34
|
New kernels close with their creating conversation by default. Attaching to an existing kernel does not claim ownership. Use `autoclose=false` on a persistent gateway to keep a new kernel for later conversations. See [core](https://AnswerDotAI.github.io/clikernel/core.html) for configuration and lifecycle details.
|
|
36
35
|
|
|
@@ -40,10 +39,10 @@ New kernels close with their creating conversation by default. Attaching to an e
|
|
|
40
39
|
pip install clikernel
|
|
41
40
|
```
|
|
42
41
|
|
|
43
|
-
This installs
|
|
42
|
+
This installs jupygate and ipymini. No service setup is required for a conversation-local kernel: clikernel starts a private gateway if it cannot find one. To retain kernels across conversations, run a resident gateway, for example through launchd or systemd:
|
|
44
43
|
|
|
45
44
|
``` sh
|
|
46
|
-
|
|
45
|
+
jupygate --port 8787
|
|
47
46
|
```
|
|
48
47
|
|
|
49
48
|
## Use with an MCP host
|
|
@@ -61,12 +60,14 @@ create(kernel="py")
|
|
|
61
60
|
exec(code="6*7")
|
|
62
61
|
```
|
|
63
62
|
|
|
64
|
-
|
|
63
|
+
`create` accepts any kernelspec the gateway finds. In the main conversation, `exec` never creates or switches kernels. See [MCP](https://AnswerDotAI.github.io/clikernel/mcp.html) for named gateways and other tools.
|
|
65
64
|
|
|
66
65
|
In Claude Code, subagents share the current kernel unless `clikernel-hook` is registered as a `PreToolUse` hook. With the hook, each subagent’s first `exec` creates a kernel of its own. See [Subagent kernels](https://AnswerDotAI.github.io/clikernel/mcp.html#subagent-kernels) for the settings entry.
|
|
67
66
|
|
|
68
67
|
The router checks each `exec` cell against built-in rules for mistakes agents often make with this toolkit. Most rules add a note to the reply, and `--quiet` leaves the notes out. Two rules always block the cell: shell access through `subprocess`, [`os.system`](https://docs.python.org/3/library/os.html#os.system) or [`os.popen`](https://docs.python.org/3/library/os.html#os.popen), and changes to `sys.path`.
|
|
69
68
|
|
|
69
|
+
The router caps text replies to `--maxout` UTF-8 bytes (default 40,000; pass `0` to disable). When a reply exceeds that limit, the router saves the full output to a temporary file, returns the first chunk with the file path and remaining size, and serves subsequent chunks when you run `exec(code="%cont")` (or `exec(code="%cont <id>")` when several calls overflow in parallel).
|
|
70
|
+
|
|
70
71
|
## Configuration
|
|
71
72
|
|
|
72
73
|
Two optional files in `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
|
|
@@ -11,12 +11,10 @@ clikernel/login.py
|
|
|
11
11
|
clikernel/mcp.py
|
|
12
12
|
clikernel/rules.py
|
|
13
13
|
clikernel/skill.py
|
|
14
|
-
clikernel/stream.py
|
|
15
14
|
clikernel.egg-info/PKG-INFO
|
|
16
15
|
clikernel.egg-info/SOURCES.txt
|
|
17
16
|
clikernel.egg-info/dependency_links.txt
|
|
18
17
|
clikernel.egg-info/entry_points.txt
|
|
19
18
|
clikernel.egg-info/requires.txt
|
|
20
19
|
clikernel.egg-info/top_level.txt
|
|
21
|
-
tests/test_rules.py
|
|
22
|
-
tests/test_stream.py
|
|
20
|
+
tests/test_rules.py
|
|
@@ -17,10 +17,9 @@ classifiers = [
|
|
|
17
17
|
|
|
18
18
|
dependencies = [
|
|
19
19
|
"fastcore>=2.2.2",
|
|
20
|
-
"jupyasyncclient>=0.2.
|
|
21
|
-
"jupywire>=0.1.9",
|
|
20
|
+
"jupyasyncclient>=0.2.32",
|
|
22
21
|
"mcpmini>=0.0.5",
|
|
23
|
-
"
|
|
22
|
+
"jupygate>=0.1.0",
|
|
24
23
|
"ipymini>=0.1.28",
|
|
25
24
|
"httpx",
|
|
26
25
|
"ipython",
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
"""Route stdio MCP requests to rustygate gateways
|
|
2
|
-
|
|
3
|
-
Claude Code starts `clikernel-mcp` for each conversation. Its `Router` accepts MCP messages over stdio and sends tool calls to rustygate gateways. Rustygate implements the tools. The router gets their schemas from the local gateway and adds `host` to `list_kernels`, `use_kernel`, and `create`.
|
|
4
|
-
|
|
5
|
-
Each host has a separate gateway session. Calls without an explicit `host` go to their caller's current host. The router keeps one for the main conversation and one for each subagent that `clikernel-hook` names with `agent`; a subagent starts on the main conversation's current host. The router removes `host` before forwarding a call but preserves the JSON-RPC request id. Cancellation notifications also retain their original ids.
|
|
6
|
-
|
|
7
|
-
Before forwarding `exec`, the router checks the cell against `clikernel.rules`. Most rules add a note to the reply. Two rules block the cell, which then never reaches a gateway.
|
|
8
|
-
|
|
9
|
-
`main` closes its gateway sessions on EOF, SIGTERM, or an exception. Closing a session sends an HTTP DELETE. The gateway then stops the kernels that session created with autoclose. If the router started a child gateway, it stops that process too.
|
|
10
|
-
|
|
11
|
-
Docs: https://AnswerDotAI.github.io/clikernel/mcp.html.md"""
|
|
12
|
-
|
|
13
|
-
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_mcp.ipynb.
|
|
14
|
-
|
|
15
|
-
# %% auto #0
|
|
16
|
-
__all__ = ['HOST_PARAM', 'HOSTED', 'Router', 'main', 'agent_input', 'hook']
|
|
17
|
-
|
|
18
|
-
# %% ../nbs/01_mcp.ipynb #28c42902
|
|
19
|
-
import asyncio, httpx, json, signal
|
|
20
|
-
from fastcore.utils import *
|
|
21
|
-
from fastcore.script import call_parse, store_true
|
|
22
|
-
from mcpmini.core import serve_stdio, jresp, jerr
|
|
23
|
-
from .core import Gateway, default_gateway, resolve, session_defaults
|
|
24
|
-
from .rules import scan
|
|
25
|
-
from . import __version__
|
|
26
|
-
|
|
27
|
-
# %% ../nbs/01_mcp.ipynb #76e2d782
|
|
28
|
-
HOST_PARAM = {'type': 'string', 'description': 'Gateway to target: a gateways.toml name, or empty for the default local gateway'}
|
|
29
|
-
HOSTED = ('list_kernels', 'use_kernel', 'create')
|
|
30
|
-
|
|
31
|
-
class Router:
|
|
32
|
-
"Route stdio MCP to rustygate with one session per host and a current host for each caller."
|
|
33
|
-
def __init__(
|
|
34
|
-
self,
|
|
35
|
-
cfgdir=None, # Config dir for `session_defaults` and `gateways.toml` (the standard one if None)
|
|
36
|
-
quiet=False, # Keep startup output and rule notes out of replies?
|
|
37
|
-
):
|
|
38
|
-
self.cfgdir,self.quiet,self.sessions,self.cur,self.inflight,self.child = cfgdir,quiet,{},{},{},None
|
|
39
|
-
|
|
40
|
-
async def session(self, host=''):
|
|
41
|
-
"Return the session for `host`, initializing it on first use. Empty `host` selects the default local gateway."
|
|
42
|
-
if host not in self.sessions:
|
|
43
|
-
if host:
|
|
44
|
-
url, token, verify = resolve(host, self.cfgdir)
|
|
45
|
-
self.sessions[host] = await Gateway(url, token, verify).initialize(session_defaults(self.cfgdir, self.quiet, local=False))
|
|
46
|
-
else: self.sessions[host], self.child = await default_gateway(self.cfgdir, self.quiet)
|
|
47
|
-
return self.sessions[host]
|
|
48
|
-
|
|
49
|
-
# %% ../nbs/01_mcp.ipynb #79da6a3e
|
|
50
|
-
@patch
|
|
51
|
-
async def tools(self:Router):
|
|
52
|
-
"Return the local gateway's tools with `host` added to `list_kernels`, `use_kernel`, and `create`."
|
|
53
|
-
ts = await (await self.session()).tools()
|
|
54
|
-
for t in ts:
|
|
55
|
-
if t['name'] in HOSTED: t['inputSchema'].setdefault('properties', {})['host'] = dict(HOST_PARAM)
|
|
56
|
-
return ts
|
|
57
|
-
|
|
58
|
-
# %% ../nbs/01_mcp.ipynb #6da913bf
|
|
59
|
-
def _cap_images(content, budget=5 << 20):
|
|
60
|
-
"`content`, with each image that would take the total base64 image data past `budget` bytes replaced by a line of text."
|
|
61
|
-
left,res = budget,[]
|
|
62
|
-
for b in content:
|
|
63
|
-
if b['type'] == 'image':
|
|
64
|
-
if (n := len(b['data'])) > left: b = dict(type='text', text=f"[{b['mimeType']} image of {n:,} bytes omitted: images in one reply are limited to {budget:,} bytes]")
|
|
65
|
-
else: left -= n
|
|
66
|
-
res.append(b)
|
|
67
|
-
return res
|
|
68
|
-
|
|
69
|
-
# %% ../nbs/01_mcp.ipynb #e1b057dd
|
|
70
|
-
@patch
|
|
71
|
-
async def dispatch(self:Router, msg, requester=None):
|
|
72
|
-
"Answer initialization and ping locally. Forward tool calls to gateways."
|
|
73
|
-
method,id = msg.get('method'), msg.get('id')
|
|
74
|
-
try:
|
|
75
|
-
if method == 'initialize':
|
|
76
|
-
info = (await self.session()).info
|
|
77
|
-
return jresp(id, dict(protocolVersion=msg['params'].get('protocolVersion', '2025-06-18'), capabilities=dict(tools={}),
|
|
78
|
-
serverInfo=dict(name='clikernel', version=__version__), instructions=info.get('instructions')))
|
|
79
|
-
if id is None:
|
|
80
|
-
if method == 'notifications/cancelled' and (h := self.inflight.get(msg['params'].get('requestId'))) is not None:
|
|
81
|
-
await (await self.session(h)).tr.send(msg)
|
|
82
|
-
return None
|
|
83
|
-
if method == 'ping': return jresp(id, {})
|
|
84
|
-
if method == 'tools/list': return jresp(id, dict(tools=await self.tools()))
|
|
85
|
-
if method == 'tools/call':
|
|
86
|
-
args = msg['params'].setdefault('arguments', {})
|
|
87
|
-
fired = scan(args.get('code', '')) if msg['params']['name'] == 'exec' else []
|
|
88
|
-
if blocks := [r.note for r in fired if r.block]:
|
|
89
|
-
return jresp(id, dict(isError=True, content=[dict(type='text', text=' '.join(blocks)+' (If the block seems wrong here, tell your user.)')]))
|
|
90
|
-
has_host,agent = 'host' in args, args.get('agent')
|
|
91
|
-
host = args.pop('host', '') or ''
|
|
92
|
-
h = host if has_host else self.cur.setdefault(agent, self.cur.get(None, ''))
|
|
93
|
-
s = await self.session(h)
|
|
94
|
-
if has_host and msg['params']['name'] in ('use_kernel', 'create'): self.cur[agent] = host
|
|
95
|
-
self.inflight[id] = h
|
|
96
|
-
try: res = await s.tr.send(msg)
|
|
97
|
-
except httpx.HTTPStatusError as e:
|
|
98
|
-
if e.response.status_code != 404: raise
|
|
99
|
-
del self.sessions[h]
|
|
100
|
-
res = await (await self.session(h)).tr.send(msg)
|
|
101
|
-
finally: self.inflight.pop(id, None)
|
|
102
|
-
if 'result' in res:
|
|
103
|
-
content = res['result']['content'] = _cap_images(res['result']['content'])
|
|
104
|
-
if fired and not self.quiet: content.insert(0, dict(type='text', text=''.join(f'<note>\n{r.note}\n</note>\n' for r in fired)))
|
|
105
|
-
return res
|
|
106
|
-
return jerr(id, -32601, f'method not found: {method}')
|
|
107
|
-
except Exception as e: return None if id is None else jerr(id, -32603, str(e))
|
|
108
|
-
|
|
109
|
-
# %% ../nbs/01_mcp.ipynb #f72f6253
|
|
110
|
-
@patch
|
|
111
|
-
async def aclose(self:Router):
|
|
112
|
-
"Close all sessions and their autoclose kernels, then stop any owned gateway."
|
|
113
|
-
try: results = await asyncio.gather(*(s.aclose() for s in self.sessions.values()), return_exceptions=True)
|
|
114
|
-
finally:
|
|
115
|
-
if self.child: self.child.stop()
|
|
116
|
-
errors = [r for r in results if isinstance(r, BaseException)]
|
|
117
|
-
if errors: raise BaseExceptionGroup('MCP session cleanup failed', errors)
|
|
118
|
-
|
|
119
|
-
# %% ../nbs/01_mcp.ipynb #3b90f0e8
|
|
120
|
-
@call_parse
|
|
121
|
-
def main(
|
|
122
|
-
quiet:store_true=False, # Keep startup output and rule notes out of replies
|
|
123
|
-
cfgdir:str=None, # Directory holding `startup.py` and `gateways.toml`; `~/.config/clikernel/` if unset
|
|
124
|
-
):
|
|
125
|
-
"Run `clikernel-mcp` as a stdio server."
|
|
126
|
-
async def _main():
|
|
127
|
-
router = Router(cfgdir, quiet=quiet)
|
|
128
|
-
loop,task = asyncio.get_running_loop(),asyncio.current_task()
|
|
129
|
-
signal.signal(signal.SIGTERM, lambda *_: loop.call_soon_threadsafe(task.cancel))
|
|
130
|
-
try: await serve_stdio(router)
|
|
131
|
-
finally: await router.aclose()
|
|
132
|
-
asyncio.run(_main())
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
# %% ../nbs/01_mcp.ipynb #bc8afe8c
|
|
136
|
-
def agent_input(
|
|
137
|
-
event:dict, # A Claude Code `PreToolUse` hook event
|
|
138
|
-
):
|
|
139
|
-
"`event`'s tool input with `agent` set to the calling subagent's id, or None for a call from the main conversation."
|
|
140
|
-
if aid := event.get('agent_id'): return event['tool_input'] | dict(agent=aid)
|
|
141
|
-
|
|
142
|
-
# %% ../nbs/01_mcp.ipynb #105e6780
|
|
143
|
-
def hook():
|
|
144
|
-
"Run `clikernel-hook`: read a `PreToolUse` event on stdin, and print the `updatedInput` that gives a subagent its own kernel."
|
|
145
|
-
if upd := agent_input(json.load(sys.stdin)): print(json.dumps(dict(hookSpecificOutput=dict(hookEventName='PreToolUse', updatedInput=upd))))
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
"""Use `clikernel` MCP as the default persistent Python workspace for file/notebook reads and edits, exploration, library checks, data reshaping and debugging. Imports and variables carry across calls. Read before writing, running or debugging Python with `clikernel` connected.
|
|
2
|
-
|
|
3
|
-
Prefer it to one-off scripts (`python -c`, shell heredocs) and installed in-kernel pyskills to shell equivalents: `rgapi` (`rg()`/`fd()`/`ls()`) for search/listing; `ghapi` for GitHub/local git. Shell stays right for project tests/builds and non-Python tools.
|
|
4
|
-
|
|
5
|
-
MCP tool descriptions give parameters/rules; this guide combines calls.
|
|
6
|
-
|
|
7
|
-
`create(kernel="py")` first; read its reply's startup imports and next steps before running anything. Kernels this conversation creates stop at its end. For one that should outlive it, `create(kernel="py", dlgname="work", autoclose=false)` and tell the user its id. It needs a gateway that keeps running; say so if the reply shows a conversation-started gateway.
|
|
8
|
-
|
|
9
|
-
To continue earlier work or use the user's solveit kernel: `list_kernels`, then `use_kernel` with the id. Attach runs no setup, claims no ownership and never stops that live kernel for you.
|
|
10
|
-
|
|
11
|
-
`restart` reruns Python startup only in kernels this conversation created; redo everything else. `interrupt` stops a long `exec`, keeping state. A kernel-gone reply requires `create` or `use_kernel` before executing again.
|
|
12
|
-
|
|
13
|
-
Remote gateways are named in `~/.config/clikernel/gateways.toml`. Same tools/rules: `host=` on `list_kernels`/`use_kernel`/`create`; plain `exec` follows the selected host until the next selection.
|
|
14
|
-
|
|
15
|
-
`create(kernel="luau")`/`create(kernel="bpl")`: same `exec`/autoclose rules, no Python startup/magics. Each creation reply gives language basics. Luau's `exec(code="help()")` gives the full native API; `help("ex.edit_file")` covers one function. BPL needs `basedpl` in the gateway environment for its `bpl` kernelspec.
|
|
16
|
-
|
|
17
|
-
# Python
|
|
18
|
-
- Magics work as written, including `%%bash`. Change directory with `%cd` (expands `~`), not `os.chdir`.
|
|
19
|
-
- clikernel-created Python kernels display every top-level expression, not expressions inside loops/blocks. User startup can override this.
|
|
20
|
-
- All cell output reaches the conversation: `len(v)` first, then choose what to show.
|
|
21
|
-
- Don't repeat imports. A `NameError` for a name you set up means the kernel restarted or is newly attached: redo setup.
|
|
22
|
-
- After `nbdev-export` or imported-module edits, `importlib.reload` and re-import held names: `from x import y` keeps the old object; `@patch` refreshes on reload by writing onto the shared class. Restart only when a class you hold instances of was redefined. Check loaded behavior by calling it, never `inspect.getsource` (reads disk).
|
|
23
|
-
- Try the simple import/API call before environment changes, monkeypatching or extra setup.
|
|
24
|
-
"""
|
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
"""Streaming JSON-lines worker protocol: nbformat-shaped output events, and a supervisor for select-based UIs.
|
|
2
|
-
|
|
3
|
-
A deliberately minimal protocol front over gateway kernels -- MCP's sibling with
|
|
4
|
-
everything stripped (no tool list, no banner, no schemas): one JSON object per
|
|
5
|
-
line in (`{"op":"exec","id":n,"code":...}`, `{"op":"complete","id":n,"code":...,
|
|
6
|
-
"pos":n}`, `{"op":"exit"}`), events out. Each execution's outputs
|
|
7
|
-
(stream/display_data/execute_result/error) arrive as `out` events with the
|
|
8
|
-
nbformat dict intact (mime bundles included), then a `done` event. Interrupt is
|
|
9
|
-
not on the wire: the supervisor sends SIGINT to the worker process, which the
|
|
10
|
-
worker maps to a kernel interrupt. The worker connects to a gateway (URL as
|
|
11
|
-
argv[0], default local; a kernel id as argv[1] attaches instead of creating),
|
|
12
|
-
so the compact protocol exercises the full real stack -- which is its point:
|
|
13
|
-
a self-contained test client, and a reminder to keep the layers flexible.
|
|
14
|
-
"""
|
|
15
|
-
import json,os,select,signal,subprocess,sys,time
|
|
16
|
-
from fastcore.nbio import msg2out
|
|
17
|
-
from jupywire.route import OUTPUT_MSGS
|
|
18
|
-
|
|
19
|
-
def _emit(obj):
|
|
20
|
-
sys.stdout.write(json.dumps(obj) + '\n')
|
|
21
|
-
sys.stdout.flush()
|
|
22
|
-
|
|
23
|
-
async def _do_exec(kc, req):
|
|
24
|
-
rid = req.get('id')
|
|
25
|
-
async for m in kc.run(req['code']):
|
|
26
|
-
if m['msg_type'] in OUTPUT_MSGS: _emit(dict(ev='out', id=rid, output=msg2out(m)))
|
|
27
|
-
_emit({'ev':'done','id':rid})
|
|
28
|
-
|
|
29
|
-
async def _do_complete(kc, req):
|
|
30
|
-
line, pos = req['code'], req.get('pos', len(req['code']))
|
|
31
|
-
matches, start = await kc.complete(line, pos)
|
|
32
|
-
_emit(dict(ev='completions', id=req.get('id'), matches=matches, start=start))
|
|
33
|
-
|
|
34
|
-
async def _amain(url, kernel=None):
|
|
35
|
-
import asyncio
|
|
36
|
-
from jupyasyncclient import JupyAsyncKernelClient
|
|
37
|
-
loop = asyncio.get_running_loop()
|
|
38
|
-
async with await JupyAsyncKernelClient.connect(url, kernel=kernel, cwd=os.getcwd()) as kc:
|
|
39
|
-
loop.add_signal_handler(signal.SIGINT, lambda: asyncio.ensure_future(kc.interrupt_kernel()))
|
|
40
|
-
_emit({'ev':'ready'})
|
|
41
|
-
while True:
|
|
42
|
-
line = await loop.run_in_executor(None, sys.stdin.readline)
|
|
43
|
-
if not line: break
|
|
44
|
-
req = json.loads(line)
|
|
45
|
-
op = req.get('op')
|
|
46
|
-
if op == 'exit': break
|
|
47
|
-
if op == 'exec': await _do_exec(kc, req)
|
|
48
|
-
elif op == 'complete': await _do_complete(kc, req)
|
|
49
|
-
else: _emit(dict(ev='protocol-error', id=req.get('id'), error=f'unknown op {op!r}'))
|
|
50
|
-
|
|
51
|
-
def main():
|
|
52
|
-
import asyncio
|
|
53
|
-
args = sys.argv[1:]
|
|
54
|
-
asyncio.run(_amain(args[0] if args else 'http://127.0.0.1:8787', args[1] if len(args) > 1 else None))
|
|
55
|
-
|
|
56
|
-
class StreamWorker:
|
|
57
|
-
"Drive a `clikernel.stream` worker subprocess: non-blocking `pump` for select loops, SIGINT interrupt."
|
|
58
|
-
def __init__(self, argv=None):
|
|
59
|
-
self.proc = subprocess.Popen(argv or [sys.executable,'-m','clikernel.stream'],
|
|
60
|
-
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0)
|
|
61
|
-
self._buf = b''
|
|
62
|
-
self._next = 1
|
|
63
|
-
self.busy = None # id of the in-flight exec, or None
|
|
64
|
-
self._wait_for('ready')
|
|
65
|
-
|
|
66
|
-
@property
|
|
67
|
-
def fd(self): return self.proc.stdout.fileno()
|
|
68
|
-
|
|
69
|
-
def _send(self, **req):
|
|
70
|
-
self.proc.stdin.write((json.dumps(req) + '\n').encode())
|
|
71
|
-
self.proc.stdin.flush()
|
|
72
|
-
|
|
73
|
-
def pump(self):
|
|
74
|
-
"All events the worker has written so far (never blocks; call when `fd` selects readable)."
|
|
75
|
-
while select.select([self.fd], [], [], 0)[0]:
|
|
76
|
-
data = os.read(self.fd, 1 << 20)
|
|
77
|
-
if not data: break # EOF: the worker died
|
|
78
|
-
self._buf += data
|
|
79
|
-
evs = []
|
|
80
|
-
while b'\n' in self._buf:
|
|
81
|
-
line, self._buf = self._buf.split(b'\n', 1)
|
|
82
|
-
ev = json.loads(line)
|
|
83
|
-
if ev.get('ev') == 'done' and ev.get('id') == self.busy: self.busy = None
|
|
84
|
-
evs.append(ev)
|
|
85
|
-
return evs
|
|
86
|
-
|
|
87
|
-
def _wait_for(self, kind, timeout=30):
|
|
88
|
-
"Block until an event of `kind` arrives, returning it (any earlier events are dropped: idle-time use only)."
|
|
89
|
-
end = time.monotonic() + timeout
|
|
90
|
-
while time.monotonic() < end:
|
|
91
|
-
for ev in self.pump():
|
|
92
|
-
if ev.get('ev') == kind: return ev
|
|
93
|
-
select.select([self.fd], [], [], min(0.05, max(end - time.monotonic(), 0)))
|
|
94
|
-
raise TimeoutError(f'no {kind} event within {timeout}s')
|
|
95
|
-
|
|
96
|
-
def exec(self, code):
|
|
97
|
-
"Send `code` for execution: events arrive via `pump`; returns the request id."
|
|
98
|
-
rid = self._next
|
|
99
|
-
self._next += 1
|
|
100
|
-
self.busy = rid
|
|
101
|
-
self._send(op='exec', id=rid, code=code)
|
|
102
|
-
return rid
|
|
103
|
-
|
|
104
|
-
def complete(self, code, pos, timeout=5):
|
|
105
|
-
"Completion round-trip (idle only): returns (matches, start offset in `code`)."
|
|
106
|
-
rid = self._next
|
|
107
|
-
self._next += 1
|
|
108
|
-
self._send(op='complete', id=rid, code=code, pos=pos)
|
|
109
|
-
ev = self._wait_for('completions', timeout)
|
|
110
|
-
return ev.get('matches', []), ev.get('start', pos)
|
|
111
|
-
|
|
112
|
-
def interrupt(self):
|
|
113
|
-
"SIGINT the worker: the in-flight execution returns with a KeyboardInterrupt error output."
|
|
114
|
-
if self.busy: self.proc.send_signal(signal.SIGINT)
|
|
115
|
-
|
|
116
|
-
def close(self):
|
|
117
|
-
try: self._send(op='exit')
|
|
118
|
-
except Exception: pass
|
|
119
|
-
self.proc.terminate()
|
|
120
|
-
self.proc.wait()
|
|
121
|
-
|
|
122
|
-
def __enter__(self): return self
|
|
123
|
-
def __exit__(self, *args): self.close()
|
|
124
|
-
|
|
125
|
-
if __name__ == '__main__': main()
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
"The stream protocol round trip: a real worker subprocess against a spawned rustygate."
|
|
2
|
-
import select, sys, time
|
|
3
|
-
import pytest
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
@pytest.fixture(scope="module")
|
|
7
|
-
def gateway():
|
|
8
|
-
from rustygate.tools import start_gateway
|
|
9
|
-
g = start_gateway()
|
|
10
|
-
yield g.url
|
|
11
|
-
g.stop()
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def _drain_until(w, pred, timeout=30):
|
|
15
|
-
"Pump until `pred(ev)` matches some event, returning all events seen."
|
|
16
|
-
evs, end = [], time.monotonic() + timeout
|
|
17
|
-
while time.monotonic() < end:
|
|
18
|
-
select.select([w.fd], [], [], 0.05)
|
|
19
|
-
evs += w.pump()
|
|
20
|
-
if any(pred(e) for e in evs): return evs
|
|
21
|
-
raise TimeoutError(f'no matching event within {timeout}s: {evs}')
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def test_stream_round_trip(gateway):
|
|
25
|
-
from clikernel.stream import StreamWorker
|
|
26
|
-
with StreamWorker(argv=[sys.executable, '-m', 'clikernel.stream', gateway]) as w:
|
|
27
|
-
rid = w.exec('print("hi"); 6*7')
|
|
28
|
-
evs = _drain_until(w, lambda e: e.get('ev') == 'done' and e.get('id') == rid)
|
|
29
|
-
outs = [e['output'] for e in evs if e.get('ev') == 'out']
|
|
30
|
-
assert any(o['output_type'] == 'stream' and 'hi' in o['text'] for o in outs)
|
|
31
|
-
assert any(o['output_type'] == 'execute_result' and '42' in o['data']['text/plain'] for o in outs)
|
|
32
|
-
assert w.busy is None
|
|
33
|
-
|
|
34
|
-
w.exec('x = 41 + 1') # state persists across execs
|
|
35
|
-
_drain_until(w, lambda e: e.get('ev') == 'done')
|
|
36
|
-
rid = w.exec('x')
|
|
37
|
-
evs = _drain_until(w, lambda e: e.get('ev') == 'done' and e.get('id') == rid)
|
|
38
|
-
assert any(e.get('ev') == 'out' and '42' in e['output'].get('data', {}).get('text/plain', '') for e in evs)
|
|
39
|
-
|
|
40
|
-
matches, start = w.complete('import o', 8)
|
|
41
|
-
assert 'os' in matches and start == 7
|
|
42
|
-
|
|
43
|
-
rid = w.exec('import time; time.sleep(60)') # interrupt unwedges a long cell
|
|
44
|
-
time.sleep(0.5)
|
|
45
|
-
w.interrupt()
|
|
46
|
-
evs = _drain_until(w, lambda e: e.get('ev') == 'done' and e.get('id') == rid)
|
|
47
|
-
assert any(e.get('ev') == 'out' and e['output'].get('output_type') == 'error' for e in evs)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|