🪐 Jupyter Kernel Client through HTTP and WebSocket
Jupyter Kernel Client allows you to connect to live Jupyter Kernels through HTTP and WebSocket.
A
Kernelis the process responsible to execute the notebook code.
Jupyter Kernel Client also provides a easy to use interactive Konsole (console for Kernels aka REPL, Read-Evaluate-Print-Loop).
To install the library, run the following command.
pip install jupyter_kernel_client
Usage
Check you have a Jupyter Server with ipykernel running somewhere. You can install those packages with the following command.
pip install jupyter-server ipykernel
- Start a Jupyter Server.
# make jupyter-server
jupyter server --port 8888 --ServerApp.port_retries 0 --IdentityProvider.token MY_TOKEN
- Launch a IPython REPL in a terminal with
ipython(orjupyter console). Execute the following snippet (update the server_url and token if needed).
import os
from platform import node
from jupyter_kernel_client import KernelClient
with KernelClient(server_url="http://localhost:8888", token="MY_TOKEN") as kernel:
code = """import os
from platform import node
print(f"Hey {os.environ.get('USER', 'John Smith')} from {node()}.")
"""
reply = kernel.execute(code)
print(reply)
assert reply["execution_count"] == 1
assert reply["outputs"] == [
{
"output_type": "stream",
"name": "stdout",
"text": f"Hey {os.environ.get('USER', 'John Smith')} from {node()}.\n",
}
]
assert reply["status"] == "ok"
Check the response.
{"execution_count": 1, "outputs": [{"output_type": "stream", "name": "stdout", "text": "Hey echarles from eric.\n"}], "status": "ok"}
Instead of using the kernel client as context manager, you can call the start() and stop() methods.
from jupyter_kernel_client import KernelClient
kernel = KernelClient(server_url="http://localhost:8888", token="MY_TOKEN")
kernel.start()
reply = kernel.execute(code)
print(reply)
kernel.stop()
Connect to an existing Kernel
First start JupyterLab, open a Notebook with a Kernel and take not of the Kernel ID.
TODO: Document how to get the
Kernel ID.
make jupyterlab
You can now connect to the existing Kernel and run code (do not invoke stop).
from jupyter_kernel_client import KernelClient
kernel = KernelClient(server_url="http://localhost:8888", kernel_id="83ef59b7-9c78-40bd-8cc2-4447635e7d0b", token="MY_TOKEN")
kernel.start()
reply = kernel.execute("x=1")
print(reply)
Connect to a Google Colab Kernel
Google Colab exposes a Jupyter-compatible kernel behind an authenticating proxy.
Use ColabKernelClient to connect to it. You obtain the server_url,
kernel_id, and proxy_token from Colab's runtime assignment API.
Option A: connect to an existing Colab kernel
from jupyter_kernel_client import ColabKernelClient
kernel = ColabKernelClient(
server_url="https://<colab-host>",
kernel_id="<kernel_id>",
proxy_token="<proxy_token>",
)
kernel.start()
reply = kernel.execute("x = 1")
print(reply)
# Do not shut down the Colab kernel; disconnect only.
kernel.stop(shutdown_kernel=False)
Option B: create a new kernel on the assigned Colab runtime
If you omit kernel_id, the client creates a new kernel when start() is called.
This uses the standard Jupyter POST /api/kernels endpoint on your assigned
Colab runtime proxy.
from jupyter_kernel_client import ColabKernelClient
kernel = ColabKernelClient(
server_url="https://<colab-host>",
proxy_token="<proxy_token>",
)
kernel.start() # Creates a new kernel on the assigned runtime.
print("kernel_id:", kernel.id)
reply = kernel.execute("x = 1 + 1; print(x)")
print(reply)
# You likely own this kernel if you created it from this client.
kernel.stop(shutdown_kernel=True)
ColabKernelClient forwards the proxy token both as the
X-Colab-Runtime-Proxy-Token header and the colab-runtime-proxy-token
WebSocket query parameter, which the Colab proxy requires for authentication.
How to obtain the Colab connection info
The three values (server_url, kernel_id, proxy_token) are the pieces of the
WebSocket URL that Colab's own frontend uses to reach your assigned runtime:
wss://<host>/api/kernels/<kernel_id>/channels?session_id=<...>&colab-runtime-proxy-token=<proxy_token>&colab-client-agent=web
For example:
wss://<colab-host>/api/kernels/<kernel_id>/channels?session_id=<session_id>&colab-runtime-proxy-token=<proxy_token>&colab-client-agent=web
They are tied to your Colab session and are short-lived — they change whenever the runtime is reassigned or reconnected, so re-fetch them after reconnecting.
The easiest way to read them is through your browser's developer tools:
- Open your notebook on colab.research.google.com and connect to a runtime (Runtime → Connect, or run any cell).
- Open DevTools (
F12) → Network tab and select the WS filter (or typekernelsin the filter box). - Run a cell to trigger kernel traffic.
- Click the
.../api/kernels/<kernel_id>/channels?...request and read off:server_url— the scheme + host before/api/kernels(change thewss://scheme tohttps://). Colab assigns a per-session host such ashttps://<colab-host>.prod.colab.dev; there is usually no/tun/m/...path segment.kernel_id— the UUID segment right after/api/kernels/.proxy_token— thecolab-runtime-proxy-tokenquery parameter (this is the same value as theX-Colab-Runtime-Proxy-Tokenrequest header). Ignore thesession_idandcolab-client-agentquery parameters.
The programmatic "runtime assignment API" is the internal endpoint the Colab frontend calls (authenticated with your Google session); it is not an officially published public API, so the DevTools method above is the practical way to obtain the values.
Can I provision a Colab runtime "from zero" with a credential?
Not for consumer Colab. There is no official public API or Python SDK, and no API key, that lets you create or assign a colab.research.google.com runtime from a standalone process. Colab's own FAQ disallows bypassing the notebook UI to drive runtimes programmatically. So even with a credential in an environment variable, you cannot start a consumer Colab runtime from scratch.
The supported workflow is therefore two-step:
- Obtain runtime assignment info (
server_url,proxy_token, and optionallykernel_id) from an active Colab browser session (see the DevTools steps above). - Use
ColabKernelClientto either connect to an existing kernel (Option A) or create a new kernel on that already-assigned runtime (Option B).
For a true "from zero" flow, use Colab Enterprise instead.
Colab Enterprise on Google
Cloud does let you provision runtimes programmatically (via the Agent Platform
API, gcloud, Terraform, or the google-cloud-aiplatform Python client),
authenticated with Google Cloud credentials (a service account through
GOOGLE_APPLICATION_CREDENTIALS / Application Default Credentials — not a Colab
API key). Note that Colab Enterprise runtimes are designed to be driven through
the Colab Enterprise notebook UI, so a raw public Jupyter-kernel WebSocket
endpoint for this client is not a documented interface. Colab Enterprise
provisioning is out of scope for jupyter-kernel-client.
Browser bridge: get the connection info from an authenticated session
Manually copying server_url / kernel_id / proxy_token out of DevTools is
tedious. The browser bridge automates the handoff using the same pattern as
Google's own colab-mcp: a short-lived local WebSocket server receives the
runtime details directly from your already-authenticated Colab browser tab.
Google credentials never leave the browser — the bridge only exchanges a
one-time local token.
from jupyter_kernel_client import request_colab_connection
# Opens a Colab page, then waits for the browser to post the runtime details
# back to a localhost WebSocket protected by a generated token.
info = request_colab_connection(timeout=60)
with info.to_kernel_client() as kernel:
print(kernel.execute("print(1 + 1)"))
How it works:
-
A localhost WebSocket server starts on a random port with a generated token (
secrets.token_urlsafe) and anOriginallowlist restricted to the Colab domains. -
A Colab page is opened with the token and port in the URL fragment (
#bridgeToken=<token>&bridgePort=<port>). -
The authenticated Colab tab connects back to
ws://localhost:<port>/?access_token=<token>(or with anAuthorization: Bearer <token>header) and sends a JSON payload:{ "server_url": "https://<colab-host>", "proxy_token": "<proxy_token>", "kernel_id": "<kernel_id>" }
Aliases such as
serverUrl,proxyToken/colab-runtime-proxy-token, andkernelIdare also accepted;kernel_idis optional (omit it to create a new kernel via Option B).
The browser side must run a cooperating page, extension or userscript that reads
bridgeToken/bridgePortfrom the launch URL and posts the payload. This library implements the local half of the handshake; it does not add an unofficial Colab API.
Reusing the bridge for other services
request_colab_connection is a thin preset over a fully generic, configurable
primitive. BrowserBridgeServer (async) and request_payload (sync) can bridge
any browser-authenticated service — configure the host, port, token, allowed
origins, subprotocols, launch URL and auth parameter as needed:
from jupyter_kernel_client import request_payload
payload = request_payload(
launch_url="https://my-service.example/bridge#token={token}&port={port}",
allowed_origins=["https://my-service.example"],
timeout=60,
)
Async usage (e.g. inside an existing event loop such as an MCP server):
from jupyter_kernel_client import ColabBridge
async with ColabBridge(open_browser=True) as bridge:
info = await bridge.receive_connection(timeout=60)
kernel = info.to_kernel_client()
This is why the bridge lives in jupyter-kernel-client: code-sandboxes
(ColabSandbox(use_browser_bridge=True)) and jupyter-mcp-server reuse the same
implementation. Install the optional dependency with
pip install 'jupyter-kernel-client[bridge]'.
Jupyter Konsole aka Console for Kernels
This package can be used to open a Jupyter Console to a Jupyter Kernel 🐣.
- Install the optional dependencies.
pip install jupyter-kernel-client[konsole]
- Start a Jupyter Server.
# make jupyter-server
jupyter server --port 8888 --ServerApp.port_retries 0 --IdentityProvider.token MY_TOKEN
- Start the konsole and execute code.
# make jupyter-konsole
jupyter konsole --url http://localhost:8888 --token MY_TOKEN
[KonsoleApp] KernelHttpManager created a new kernel:...
Jupyter Konsole...
In [1]: 1+1
2
Uninstall
To remove the library, execute the following command.
pip uninstall jupyter_kernel_client
Contributing
Development install
# Clone the repo to your local environment
# Change directory to the jupyter_kernel_client directory
# Install package in development mode, this will automatically enable the server extension.
pip install -e ".[konsole,test,lint,typing]"
Running Tests
Install dependencies.
pip install -e ".[test]"
Run the python tests.
pytest
Development uninstall
pip uninstall jupyter_kernel_client
Packaging the library
See RELEASE
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file jupyter_kernel_client-0.13.0-py3-none-any.whl.
File metadata
- Download URL: jupyter_kernel_client-0.13.0-py3-none-any.whl
- Upload date:
- Size: 56.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/6.2.0 CPython/3.13.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
46a2c2a23acc1d11ce5a1fd53ff1239507fa656e72e8ed3b06d1872d714f3433
|
|
| MD5 |
84975ec3be954de78d8dcd34f0194665
|
|
| BLAKE2b-256 |
813815a4f164b3de4f6bfb12b1f85a3bd728ce0af4b1c0ae3664ea8f8cd9b768
|