Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/python-sdk.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Python SDK
on:
push:
branches: [main]
paths:
- "packages/code-sdk-python/**"
- ".github/workflows/python-sdk.yml"
pull_request:
paths:
- "packages/code-sdk-python/**"
- ".github/workflows/python-sdk.yml"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
test:
name: python-sdk (${{ matrix.os }}, py${{ matrix.python }})
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
python: ["3.10", "3.13"]
runs-on: ${{ matrix.os }}
defaults:
run:
working-directory: packages/code-sdk-python
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: ${{ matrix.python }}
- run: uv sync --locked
- run: uv run ruff check .
- run: uv run ruff format --check .
- run: uv run mypy
- run: uv run pytest -W error
6 changes: 6 additions & 0 deletions packages/code-sdk-python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.venv/
__pycache__/
.pytest_cache/
.mypy_cache/
.ruff_cache/
dist/
21 changes: 21 additions & 0 deletions packages/code-sdk-python/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 MiniMax Code

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
106 changes: 106 additions & 0 deletions packages/code-sdk-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# minimax-code-sdk

Python SDK for driving the local [MiniMax Code](https://agent.minimax.io) agent (`mcode`).

It mirrors the TypeScript SDK [`@minimax-ai/code-sdk`](../code-sdk): every Turn runs
`mcode exec --output-format=stream-json` and continues the Session with `--session`.

## Requirements

- Python 3.10+
- The `mcode` CLI (0.6.3 or newer): `npm install -g @minimax-ai/code`

The CLI is found from `MCodeOptions(bin=...)`, then the `MCODE_BIN` environment variable,
then `PATH`.

## Quick start

```python
import asyncio
from minimax_code import MCode, ThreadOptions


async def main() -> None:
client = MCode()
thread = client.start_thread(ThreadOptions(cwd=".", permission="smart"))

turn = await thread.run("Summarize this repository in one sentence.")
print(turn.final_response, turn.usage)

# Same Session, next Turn.
turn = await thread.run("Now list its top-level directories.")

# Persist thread.id and continue later.
later = client.resume_thread(thread.id)
print((await later.run("What did I ask first?")).final_response)


asyncio.run(main())
```

### Streaming

```python
streamed = await thread.run_streamed("Fix the failing test.")
async for event in streamed:
if event["type"] == "item.updated" and event["item"]["type"] == "agent_message":
print(event["item"].get("contentDelta", ""), end="")
elif event["type"] == "turn.failed":
print("failed:", event.get("error"))
```

Events are the CLI's stream-json events, passed through unchanged (unknown types included).
`turn.failed` is an ordinary event; iteration raises only for process or protocol failures.

### Cancellation

- `streamed.cancel()` sends SIGINT; the stream ends with the CLI's final events.
- Leaving the `async for` early, or cancelling the task running `thread.run()`, stops the CLI
(SIGINT, then SIGKILL after a grace period).
- `RunOptions(timeout_ms=...)` is enforced by the CLI.

### Blocking API

```python
from minimax_code import SyncMCode

with SyncMCode() as client:
thread = client.start_thread()
print(thread.run("hello").final_response)
for event in thread.run_streamed("again"):
print(event["type"])
```

## Options

| Object | Fields |
| --- | --- |
| `MCodeOptions` | `bin`, `data_dir` (`MINIMAX_DATA_DIR`), `env` (replaces `os.environ`), `config_path` |
| `ThreadOptions` | `cwd`, `model` (`provider/model`), `effort`, `permission` (`smart`/`full`/`off`), `mode`, `prompt_mode`, `system_prompt`, `append_system_prompt` |
| `RunOptions` | `files`, `timeout_ms`, `max_steps` |

## Errors

All errors subclass `MCodeError` (with `exit_code`, `stderr`, `session_id`, `result`, `items`):
`MCodeNotFoundError`, `MCodeVersionError`, `MCodeInvocationError`, `MCodeRunError`
(`status`, `category`), `MCodeAbortError`, `MCodeProtocolError`, `ThreadBusyError`.

## Limitations

Each Turn is a separate process, so interactive permission prompts (`permission="ask"`) and
custom in-process tools are not supported yet. A long-lived ACP transport is planned.

## Development

```bash
uv sync
uv run pytest
uv run ruff check . && uv run ruff format --check . && uv run mypy
```

End-to-end tests against a real CLI and model are opt-in:
`MCODE_SDK_E2E=1 MCODE_BIN=/path/to/mcode uv run pytest -m e2e`.

## License

MIT
22 changes: 22 additions & 0 deletions packages/code-sdk-python/examples/basic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Run one Turn, a follow-up Turn, and resume the Session from its id."""

import asyncio
import sys

from minimax_code import MCode, ThreadOptions


async def main() -> None:
client = MCode()
thread = client.start_thread(ThreadOptions(cwd=".", permission="smart"))
turn = await thread.run(sys.argv[1] if len(sys.argv) > 1 else "Say hello in one sentence.")
print(turn.final_response)
print("session:", thread.id, "usage:", turn.usage)

assert thread.id is not None
resumed = client.resume_thread(thread.id)
print((await resumed.run("Repeat your previous answer in five words.")).final_response)


if __name__ == "__main__":
asyncio.run(main())
24 changes: 24 additions & 0 deletions packages/code-sdk-python/examples/streaming.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Print the agent's answer as it streams, and tool calls as they finish."""

import asyncio
import sys

from minimax_code import MCode


async def main() -> None:
thread = MCode().start_thread()
streamed = await thread.run_streamed(sys.argv[1] if len(sys.argv) > 1 else "List files here.")
async for event in streamed:
item = event.get("item")
if item and item["type"] == "agent_message":
print(item.get("contentDelta", ""), end="", flush=True)
elif item and item["type"] == "tool_call" and event["type"] == "item.completed":
print(f"\n[tool] {item.get('toolCall', {}).get('name')}")
elif event["type"] == "turn.failed":
print("\nturn failed:", event.get("error"))
print()


if __name__ == "__main__":
asyncio.run(main())
48 changes: 48 additions & 0 deletions packages/code-sdk-python/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
[build-system]
requires = ["hatchling>=1.24"]
build-backend = "hatchling.build"

[project]
name = "minimax-code-sdk"
version = "0.1.0"
description = "Python SDK for driving the local MiniMax Code (mcode) agent."
readme = "README.md"
license = "MIT"
license-files = ["LICENSE"]
requires-python = ">=3.10"
dependencies = ["typing_extensions>=4.7"]
keywords = ["minimax", "minimax-code", "mcode", "agent", "coding-agent", "sdk"]
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Typing :: Typed",
]

[project.urls]
Homepage = "https://agent.minimax.io"
Repository = "https://github.com/MiniMax-AI/minimax-code"
Issues = "https://github.com/MiniMax-AI/minimax-code/issues"

[dependency-groups]
dev = ["pytest>=8", "pytest-asyncio>=0.24", "ruff>=0.6", "mypy>=1.11"]

[tool.hatch.build.targets.wheel]
packages = ["src/minimax_code"]

[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = ["tests"]
markers = ["e2e: runs a real mcode CLI against a real model (opt-in via MCODE_SDK_E2E=1)"]

[tool.ruff]
line-length = 100
target-version = "py310"

[tool.ruff.lint]
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF"]

[tool.mypy]
strict = true
python_version = "3.10"
files = ["src", "tests"]
66 changes: 66 additions & 0 deletions packages/code-sdk-python/src/minimax_code/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""Python SDK for driving the local MiniMax Code (``mcode``) agent."""

from .client import MCode
from .errors import (
MCODE_EXEC_EXIT_CODES,
MCodeAbortError,
MCodeError,
MCodeInvocationError,
MCodeNotFoundError,
MCodeProtocolError,
MCodeRunError,
MCodeVersionError,
ThreadBusyError,
)
from .sync import SyncMCode, SyncThread
from .thread import StreamedTurn, Thread
from .types import (
AgentMessageItem,
ExecError,
ExecItem,
ExecResult,
MCodeOptions,
ModelIdentity,
ReasoningItem,
RunOptions,
ThreadEvent,
ThreadItem,
ThreadOptions,
ToolCallItem,
Turn,
Usage,
)

__version__ = "0.1.0"

__all__ = [
"MCODE_EXEC_EXIT_CODES",
"AgentMessageItem",
"ExecError",
"ExecItem",
"ExecResult",
"MCode",
"MCodeAbortError",
"MCodeError",
"MCodeInvocationError",
"MCodeNotFoundError",
"MCodeOptions",
"MCodeProtocolError",
"MCodeRunError",
"MCodeVersionError",
"ModelIdentity",
"ReasoningItem",
"RunOptions",
"StreamedTurn",
"SyncMCode",
"SyncThread",
"Thread",
"ThreadBusyError",
"ThreadEvent",
"ThreadItem",
"ThreadOptions",
"ToolCallItem",
"Turn",
"Usage",
"__version__",
]
Loading
Loading