Skip to main content

A toolkit for building, managing, and extending Jupyter agent workflows, including kernel and notebook utilities.

Project description

Agent Jupyter Toolkit

A Python toolkit for building agent tools that interact with Jupyter kernels and the Jupyter protocol. This package provides high-level wrappers and abstractions around jupyter_client, jupyter_ydoc, and pycrdt, making it easy to manage kernels, execute code, and build agent-driven workflows for automation, orchestration, and integration with Model Context Protocol (MCP) servers.

Features

Kernel

  • Async-first kernel sessions with pluggable transports:
    • Local transport — direct ZMQ communication with local kernel processes
    • Server transport — HTTP REST + WebSocket to remote Jupyter servers
  • Code execution with real-time streaming output callbacks
  • Kernel introspection — tab-completion, object inspection, code-completeness checks, and execution history retrieval
  • Kernel control — interrupt running cells, restart kernels, query kernel metadata (language, version, protocol)
  • Variable management — inspect and set kernel variables safely (base64-encoded payloads)
  • Extensible hooks — pre/post execution and output hooks for instrumentation

Notebook

  • Multiple notebook transports:
    • Local file transport — filesystem-backed notebooks with thread-safe read/write
    • Contents API transport — Jupyter Server-managed notebooks via REST
    • Collaboration transport — real-time multi-client editing via Yjs/CRDT (pycrdt + jupyter_ydoc)
  • Cell operations — append, insert, delete, set source, update outputs (full replace and delta)
  • In-memory notebook buffer for staged edits with explicit commit
  • Local notebook autosave with optional debounced writes
  • Change observers — register callbacks for cell mutations, saves, and awareness events

Use Cases

  • Build agent tools that execute code in Jupyter kernels
  • Integrate Jupyter kernel execution into MCP servers or other orchestration systems
  • Automate notebook and code execution for data science, ML, and automation pipelines
  • Build collaborative notebook editing experiences with CRDT-based conflict resolution

Installation

Install from PyPI

# Using pip
pip install agent-jupyter-toolkit

# Install optional DataFrame serialization support
pip install agent-jupyter-toolkit[dataframe]

# Or using uv
uv pip install agent-jupyter-toolkit

Install the dataframe extra only if you want pandas/Arrow-backed DataFrame serialization and inspection helpers. Core kernel and notebook features do not require it.

Development (monorepo)

git clone https://github.com/Cyb3rWard0g/agent-jupyter-toolkit.git
cd agent-jupyter-toolkit
uv sync --all-packages

This installs both agent-jupyter-toolkit and mcp-jupyter-notebook in editable mode into the .venv.

Quickstart

Local kernel execution does not require a Jupyter Server. The library starts a local kernel process for you (via jupyter_client) and connects over ZMQ.

Basic execution

import asyncio
from agent_jupyter_toolkit.kernel import SessionConfig, create_session

async def main() -> None:
    async with create_session(SessionConfig(mode="local", kernel_name="python3")) as session:
        result = await session.execute(
            "import os\n"
            "from platform import node\n"
            "user = os.environ.get('USER', 'friend')\n"
            "print(f'Hello {user} from {node()}')\n"
        )
    print("status:", result.status)
    print("stdout:", result.stdout.strip())

asyncio.run(main())

Introspection and control

async with create_session() as session:
    # Tab-completion
    result = await session.complete("import os; os.path.jo", cursor_pos=21)
    print(result.matches)  # ["join"]

    # Object inspection
    info = await session.inspect("len", cursor_pos=3)
    print(info.data.get("text/plain", ""))

    # Code-completeness check
    check = await session.is_complete("for i in range(10):")
    print(check.status)  # "incomplete"
    print(check.indent)  # "    "

    # Execution history
    hist = await session.history(n=5)
    for entry in hist.history:
        print(f"[{entry.line_number}] {entry.input}")

    # Kernel metadata
    kinfo = await session.kernel_info()
    print(f"{kinfo.language_info['name']} {kinfo.language_info['version']}")

    # Interrupt a long-running cell
    import asyncio
    task = asyncio.create_task(session.execute("import time; time.sleep(999)"))
    await asyncio.sleep(1)
    await session.interrupt()

For server-backed and notebook scenarios, see the quickstarts/ directory.

API Overview

Kernel Session

Method Description
execute(code, *, timeout, output_callback, ...) Execute code with optional streaming callbacks
interrupt() Send SIGINT to cancel running execution
complete(code, cursor_pos) Tab-completion suggestions
inspect(code, cursor_pos, detail_level) Object documentation/signature
is_complete(code) Syntax completeness check
history(*, output, raw, hist_access_type, n) Execution history retrieval
kernel_info() Kernel metadata (language, version, protocol)
is_alive() Health check
start() / shutdown() Lifecycle management (also via async with)

Notebook Document Transport

Method Description
fetch() Get notebook content as nbformat dict
save(content) Write notebook content
append_code_cell(source, metadata, tags) Append a code cell
insert_code_cell(index, source, metadata, tags) Insert a code cell at index
append_markdown_cell(source, tags) Append a markdown cell
insert_markdown_cell(index, source, tags) Insert a markdown cell at index
set_cell_source(index, source) Update cell source text
update_cell_outputs(index, outputs, execution_count) Replace cell outputs
delete_cell(index) Delete cell at index
on_change(callback) Register mutation observer

Architecture

agent_jupyter_toolkit
├── kernel/
│   ├── session.py          # Session + create_session() factory
│   ├── transport.py        # KernelTransport protocol
│   ├── types.py            # Dataclasses (SessionConfig, ExecutionResult, ...)
│   ├── manager.py          # KernelManager (lifecycle, channels)
│   ├── messages.py         # Wire-protocol message builders
│   ├── variables.py        # VariableManager (inspect/set kernel vars)
│   ├── hooks.py            # Extensible execution hooks
│   ├── mimetypes.py        # MIME-type serialization registry
│   ├── serialization.py    # High-level serialize/deserialize API
│   └── transports/
│       ├── local.py        # LocalTransport (ZMQ)
│       └── server.py       # ServerTransport (HTTP+WS)
├── notebook/
│   ├── session.py          # NotebookSession (kernel + document orchestration)
│   ├── transport.py        # NotebookDocumentTransport protocol
│   ├── factory.py          # make_document_transport() factory
│   ├── buffer.py           # In-memory NotebookBuffer
│   ├── cells.py            # Cell creation helpers (code, markdown)
│   ├── config.py           # Environment-based Config (allowlist, timeout)
│   ├── utils.py            # Path validation, output normalization
│   └── transports/
│       ├── local_file.py   # LocalFileDocumentTransport (+ autosave)
│       ├── contents.py     # ContentsApiDocumentTransport
│       └── collab/         # CollabYjsDocumentTransport (Yjs/CRDT)
└── utils/                  # High-level helpers (factories, execution, packages)

Dependencies

Package Purpose
jupyter-client Kernel protocol, ZMQ channels, kernel management
jupyter-ydoc YNotebook schema for collaborative editing
pycrdt CRDT types (Doc, Array, Map, Text, Awareness)
nbformat Notebook file format handling
aiohttp Async HTTP/WS for server transport
pandas + pyarrow Optional dataframe extra for DataFrame variable inspection

Contributing

See CONTRIBUTING.md for dev setup, testing, and the release process.


Contributions and feedback are welcome!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agent_jupyter_toolkit-0.7.0.tar.gz (95.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agent_jupyter_toolkit-0.7.0-py3-none-any.whl (108.2 kB view details)

Uploaded Python 3

File details

Details for the file agent_jupyter_toolkit-0.7.0.tar.gz.

File metadata

  • Download URL: agent_jupyter_toolkit-0.7.0.tar.gz
  • Upload date:
  • Size: 95.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for agent_jupyter_toolkit-0.7.0.tar.gz
Algorithm Hash digest
SHA256 95c32ef39d5fd6a16ddec6b2d0286729315bcbfcf5a2f71760717258bb41bbdd
MD5 226f53b896580c38b86fee9cc9f5d53b
BLAKE2b-256 8c44067da5bbb52a3e45af98ed1e089fbcb8e92244e9204a11dafb1a6dc5de28

See more details on using hashes here.

Provenance

The following attestation bundles were made for agent_jupyter_toolkit-0.7.0.tar.gz:

Publisher: release.yml on Cyb3rWard0g/agent-jupyter-toolkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file agent_jupyter_toolkit-0.7.0-py3-none-any.whl.

File metadata

File hashes

Hashes for agent_jupyter_toolkit-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dc58f0b3b50eec72c9d28b99adab3844347982bbc3292614e3aa4201fb1d4234
MD5 c6821353be8c6f07cbfeeaea65cea4e3
BLAKE2b-256 f525b9c01cbd645b0df1ab5fb8227742c68f5952e0c5b40c8bc288d295910c5a

See more details on using hashes here.

Provenance

The following attestation bundles were made for agent_jupyter_toolkit-0.7.0-py3-none-any.whl:

Publisher: release.yml on Cyb3rWard0g/agent-jupyter-toolkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page