Skip to main content
Glama
kaggle-extend-api

kaggle-extend-api

README.md
# kaggle-extend-api

Interactive Kaggle sessions for AI agents: named accounts, meaningful session/job
handles, live job logs, notebook/file operations, and automatic OAuth renewal.
Python 3.11+, official `kagglesdk`, MCP SDK 1.x or 2.x. Version **0.3.0**.

## Install and connect Codex

From the release ZIP, extract all files and run `install.cmd` on Windows or
`sh install.sh` on Linux. The installer creates a per-user Python environment
and adds the MCP server to Codex. See `INSTALL.md` at the top of the extracted
bundle (in `packaging/` in the source tree).

For development from a checkout:

```powershell
pip install -e .
codex mcp add kaggle -- E:/path/to/project/.venv/Scripts/python.exe -m kaggle_extend_api.cli mcp
```

Or configure any MCP client:

```json
{"mcpServers":{"kaggle":{"command":"E:/path/to/project/.venv/Scripts/python.exe","args":["-m","kaggle_extend_api.cli","mcp"]}}}
```

The executable must remain at that path. Open a new Codex chat/reload its MCP
connection after updates. The server uses stdio; diagnostic text never belongs
on stdout. It exposes one current interface, without a legacy profile switch.

## Accounts and OAuth

No API key download is required. Sign in once through normal Chrome/default
browser. The loopback OAuth callback verifies and stores the login automatically:

```powershell
kaggle-ext auth login --account research
kaggle-ext auth login --account personal
kaggle-ext auth accounts
kaggle-ext auth use --account research
kaggle-ext auth logout --account personal
```

Account names are local aliases (letters/digits/underscore/hyphen, max 48).
Select the intended Kaggle user on the consent page; an existing alias is bound
to that username and cannot silently become a different identity. Use another
alias to add a different user. Multiple named accounts can be logged in at once.

`default` shares `~/.kaggle/credentials.json` with the official Kaggle CLI.
Other credentials live in `~/.kaggle/extend/accounts/<alias>.json`. The adjacent
`accounts.json` stores only usernames, logout flags and the selected alias.
Set `KAGGLE_EXT_ACCOUNTS_DIR` to relocate named profiles and metadata. Keep
these files outside source control. Logout deletes that account's local OAuth
credentials; **default logout also removes the CLI's shared OAuth login**.
Other accounts, remote compute and remote/browser grants are unchanged. Stop
compute explicitly before logout if you want it released. Already running jobs
may finish; their captured logs remain readable in the current MCP process.

An explicit `account` argument takes priority. Session/job handles embed their
account, so selecting them overrides the active default; contradictory selectors
are rejected. `use` changes the default only for future unqualified operations.
A named account never falls back to another account's environment token.
`default` still supports `KAGGLE_API_TOKEN` and legacy `~/.kaggle/kaggle.json`.
An explicitly logged-out default does not reuse those fallback sources until
OAuth login is restored.

Access tokens refresh **five minutes before expiry** using the refresh grant.
Refresh reloads the latest file under a cross-process lock, preserves rotated
refresh tokens, and atomically writes to that account's own source file. Other
clients then read the renewed token. A public API HTTP 401 triggers one forced
refresh/retry; timeouts, 403s and unknown mutation failures are never retried.
Temporary refresh/network failures retain credentials and do not launch another
login. A still-valid token can be used during a short renewal outage. A missing,
expired or revoked **refresh grant** requires new consent; an expired access token
alone does not.

Within MCP use `kaggle_accounts`:

```text
kaggle_accounts(action="login", account="research")
kaggle_accounts(action="status", account="research")
kaggle_accounts(action="use", account="research")
kaggle_accounts(action="list")
kaggle_accounts(action="logout", account="personal")
```

Missing/revoked initial credentials automatically start a pending OAuth flow;
poll account status, complete consent, then retry the original call. The tool
does not replay code or allocation automatically. Set `KAGGLE_EXT_AUTO_LOGIN=0`
for headless/noninteractive environments. Explicit login accepts
`launch_browser=false` (CLI: `--no-launch-browser`) and returns a link while the
local callback waits. The browser must reach the machine's localhost. Login
expires after five minutes; `--force` can replace an existing grant. MCP refuses
forced credential replacement while that account has running jobs.

OAuth uses the official CLI's `resources.admin:*` default scope. See
[Kaggle authentication](https://github.com/Kaggle/kaggle-cli/blob/main/skills/references/auth.md)
and [the OAuth refresh grant](https://www.kaggle.com/docs/api).

## Agent workflow and target selection

There are **10 MCP tools**:

| Tool | Purpose |
| --- | --- |
| `kaggle_accounts` | List/login/status/use/logout accounts |
| `kaggle_status` | Inspect named sessions/jobs; filter account/session/job |
| `kaggle_notebooks` | Search notebooks in an account |
| `kaggle_quota` | Accelerator quota for an account/session/job owner |
| `kaggle_open` | Discover/connect/create a named session; URL stays internal |
| `kaggle_run` | Submit named code execution once |
| `kaggle_job` | Live logs, trace, job listing and targeted interrupt |
| `kaggle_files` | List/read/write/upload/download/delete |
| `kaggle_notebook` | List/read/append/replace/delete individual cells |
| `kaggle_stop` | Stop selected session, or the session containing a job |

```text
kaggle_open(account="research", slug="owner/notebook", name="train-detector")
kaggle_run(session="<returned session>", name="train-epoch", code="train()", wait=0)
kaggle_job(id="<returned job>", action="logs", offset=0, wait=20)
kaggle_job(id="<returned job>", action="trace", offset=<cursor>, wait=20)
kaggle_files(job="<returned job>", action="read", path="metrics.json")
kaggle_stop(job="<returned job>")
```

Session handles resemble `research/train-detector-a1b2c3`; job IDs resemble
`research/train-detector-a1b2c3/train-epoch-20261112T120000-d4e5f6`.
They include readable names and collision-resistant suffixes. You may also use
an unambiguous session/job name **within the selected account**, e.g.
`kaggle_job(account="research", id="train-epoch")`. Repeated names require the
full handle. Default session names derive from the notebook slug; job names
derive from the Python operation (`run-train`, `assign-model`, `import-torch`),
without copying argument literals into names. Explicit names describe the task.

`kaggle_open(mode="connect")` never creates compute. `auto` reuses the managed
session or account-scoped cached id, then tries SDK-authenticated metadata.
If absence cannot be confirmed, it fails safely; explicitly request
`mode="create"` to allocate. CPU is the default; GPU requires `accelerator`.
No repeated opens silently change options of an existing session. Creation
conflicts do not allocate a second session. Session IDs are cached outside the
repo; after MCP restart reconnect with the slug or numeric `session_id`. Old
unscoped cache entries are ignored to avoid crossing account identities.

Read-only account-wide discovery may be unavailable with SDK authorization;
it never launches a browser or reads cookie databases. Connect by saved session
id or explicitly create instead. **Persistence control, persistence arguments,
cookie extraction and `auth web-*` were removed.** Existing Kaggle notebook
persistence settings are left untouched. A browser is used only for OAuth
login, never for changing notebook settings.

## Live job logs and tracing

`run` executes once in a background thread. `wait=0..20` controls how long a tool
waits, while `timeout` is the separate code execution deadline. Logs arrive from
that execution's Jupyter IOPub messages **during execution**; no remote log file,
download, or file synchronization is involved.

Read `kaggle_job(id, action="logs", offset=<last cursor>, wait=20)`. It returns
when output arrives, execution ends, or the bounded wait elapses. `cursor` is an
absolute character position; pass it on the next call to avoid duplicate text.
`next_offset` means unread text already exists. Printing a log does not mean a
job is finished: inspect `status`. Code exceptions are `execution_status=error`
even if the transport job is `done`.

`action="trace"` adds creation/start/finish times in UTC, kernel ID, Jupyter
request ID and event history (stdout/stderr, errors, execution reply, kernel
state, interruption). Text events include character offsets so trace can be
correlated with log pages. Events from other executions are filtered out.

`action="list"` lists jobs by account/session with `offset`/`limit` pagination.
`action="interrupt"` interrupts the kernel executing that job; interruption is
requested, then confirmed by following the log/status. This can affect other
work sharing the same kernel. `kaggle_stop` stops the entire containing session.
File/notebook reads may run alongside a job; mutations require an idle session.

Logs retain the latest **1,000,000 characters**, event traces the latest **256
events**, and at most **64 jobs per account**. `dropped_chars` reports text that
has fallen out of the rolling log window; completed old jobs may be evicted.
Logs/jobs are in memory for this MCP process: server restart loses that history
and detaches from running code without stopping remote compute. No log files
are secretly synchronized or written. Python/subprocess buffering can delay
messages; use `print(..., flush=True)` / `python -u` for prompt progress.
Output defaults to 6,000 characters/page; rich HTML/base64 images are omitted.
Save useful images/data as remote artifacts and download with `kaggle_files`.

A busy session rejects another execution. Timeout/disconnect leaves uncertain
state because code may still be running; do not resubmit it blindly. Inspect
trace and stop/reconnect deliberately. Signed proxy URLs are omitted from tool
results/errors. Expected errors include `code`, `message`, `next_action`.

## Python API

```python
from kaggle_extend_api import KaggleAgent, login, logout, list_accounts, use_account

login(account="research")
agent = KaggleAgent(account="research")
opened = agent.open("owner/notebook", name="train-detector", mode="connect")
while opened.get("status") == "running":
    opened = agent.job(opened["job"], wait=20)

job = agent.run("print('hello', flush=True)", name="check-runtime", wait=0)
cursor = 0
while True:
    page = agent.job(job["job"], offset=cursor, wait=20)
    print(page["text"], end="")
    cursor = page["cursor"]
    if page["status"] != "running" and cursor >= page["total_chars"]:
        break
print(agent.job(job["job"], action="trace", wait=0))
agent.stop(job=job["job"])
```

All session operations also accept explicit `session` and/or `job` selectors.
Inspect errors before proceeding with dependent operations. Low-level
`KaggleSessionClient(account=...)`, `KernelSession`, and `JupyterTools` remain
available. `JupyterTools.execute(..., on_event=callback)` delivers matching live
execution events. File paths are relative to `/kaggle/working`; list/read are
paged, text reads are limited to 2MB, and upload/download use local paths.

CLI low-level session/raw commands support `--account`:

```powershell
kaggle-ext session quota --account research
kaggle-ext session create owner/test-notebook --account research --accelerator cpu --no-wait
kaggle-ext session logs --session-id 123 --account research
kaggle-ext raw kernels.kernels_api_client.list_kernels --account research --args '{"user":"owner"}'
```

## Verification

```powershell
pip install -e ".[test]"
python -m pytest -q --basetemp .pytest_cache/test_tmp
python scripts/smoke_live.py owner/test-notebook
python scripts/smoke_agent_live.py owner/test-notebook
```

Live smokes are opt-in: use a dedicated test notebook. They allocate CPU,
exercise real execution/files/notebook operations, clean temporary files and
stop their sessions. The agent smoke checks logs **before code completes**,
trace correlation and all 10 tools. Multi-account login/logout/rotation are
covered with isolated synthetic profiles; no second real account is assumed.
See [TEST_REPORT.md](TEST_REPORT.md) for results and limits.

To rebuild the shareable ZIP and its SHA-256 file, run
`python scripts/build_release.py` from the checkout with `uv` on PATH.