Metadata-Version: 2.4
Name: stdiobus
Version: 1.0.0
Summary: Python SDK for stdio_bus - AI agent transport layer
Author-email: Raman Marozau <raman@worktif.com>
Maintainer-email: Raman Marozau <raman@worktif.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work.
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to the Licensor for inclusion in the Work by the copyright
              owner or by an individual or Legal Entity authorized to submit on
              behalf of the copyright owner.
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
        
           8. Limitation of Liability. In no event and under no theory of liability,
              whether in contract, strict liability, or tort (including negligence
              or otherwise) arising in any way out of the use or inability to use
              the Work, even if advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2024-2026 stdio-bus contributors
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/stdio-bus/stdio-bus
Project-URL: Documentation, https://github.com/stdio-bus/stdio-bus/tree/main/sdk/python#readme
Project-URL: Repository, https://github.com/stdio-bus/stdio-bus.git
Project-URL: Issues, https://github.com/stdio-bus/stdio-bus/issues
Project-URL: Changelog, https://github.com/stdio-bus/stdio-bus/blob/main/sdk/python/CHANGELOG.md
Keywords: stdio-bus,stdiobus,acp,mcp,agent,ai,llm,transport,json-rpc,ndjson,agent-client-protocol,model-context-protocol
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Networking
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Provides-Extra: native
Requires-Dist: cffi>=1.15; extra == "native"
Provides-Extra: all
Requires-Dist: stdiobus[dev,native]; extra == "all"
Dynamic: license-file

# stdiobus

Python SDK for stdio_bus - the AI agent transport layer.

[![PyPI](https://img.shields.io/pypi/v/stdiobus)](https://pypi.org/project/stdiobus/)
[![CI](https://github.com/stdiobus/python/actions/workflows/ci.yml/badge.svg)](https://github.com/stdiobus/python/actions/workflows/ci.yml)

## Features

- **Cross-platform** - Works on Windows, macOS, Linux via Docker backend
- **Native backend** - Direct FFI to C kernel on Linux/macOS (cffi)
- **Async/Sync API** - Both `AsyncStdioBus` and `StdioBus` classes
- **Type hints** - Full typing support for IDE autocompletion
- **Context managers** - Clean resource management with `with`/`async with`

## Installation

```bash
pip install stdiobus
```

Requirements:
- Python 3.10+
- [Docker Desktop](https://www.docker.com/products/docker-desktop) (for Docker backend)

### Native Backend (Optional)

For better performance on Linux/macOS, build the native extension:

```bash
# Build libstdio_bus.a first
git clone https://github.com/stdiobus/stdio-bus.git
cd stdio-bus
make lib

# Build Python extension
cd sdk/python
pip install cffi
python -m stdiobus._native.build_ffi
```

## Quick Start

### Synchronous API

```python
from stdiobus import StdioBus

with StdioBus(config_path='./config.json') as bus:
    result = bus.request('tools/list', {})
    print('Tools:', result)
```

### Async API

```python
import asyncio
from stdiobus import AsyncStdioBus

async def main():
    async with AsyncStdioBus(config_path='./config.json') as bus:
        result = await bus.request('tools/list', {})
        print('Tools:', result)

asyncio.run(main())
```

## Configuration

Create a `config.json` file:

```json
{
  "pools": [
    {
      "id": "mcp-worker",
      "command": "node",
      "args": ["./worker.js"],
      "instances": 4
    }
  ]
}
```

## API Reference

### StdioBus / AsyncStdioBus

```python
bus = StdioBus(
    config_path='./config.json',  # Required
    backend='auto',               # 'auto', 'native', or 'docker'
    timeout_ms=30000,             # Default request timeout
    docker=DockerOptions(         # Docker backend options
        image='stdiobus/stdiobus:node20',
        pull_policy='if-missing',
    ),
)
```

### Methods

| Method | Description |
|--------|-------------|
| `start()` | Start the bus and spawn workers |
| `stop(timeout_sec=30)` | Stop the bus gracefully |
| `request(method, params, timeout_ms=None)` | Send request and wait for response |
| `notify(method, params)` | Send notification (no response) |
| `send(message)` | Send raw JSON-RPC message |
| `on_message(handler)` | Register message handler |
| `get_state()` | Get current bus state |
| `get_stats()` | Get runtime statistics |
| `is_running()` | Check if bus is running |
| `destroy()` | Release all resources |

### States

```python
from stdiobus import BusState

BusState.CREATED   # 0 - Created but not started
BusState.STARTING  # 1 - Workers being spawned
BusState.RUNNING   # 2 - Running and accepting messages
BusState.STOPPING  # 3 - Graceful shutdown in progress
BusState.STOPPED   # 4 - Fully stopped
```

### Errors

```python
from stdiobus import (
    StdioBusError,        # Base exception
    InvalidArgumentError, # Invalid parameter
    InvalidStateError,    # Operation not valid in current state
    TimeoutError,         # Request timeout
    TransportError,       # Transport-level failure
    PolicyDeniedError,    # Operation denied by policy
)
```

## Docker Backend

The Docker backend runs stdio_bus in a container and communicates via TCP.

```python
from stdiobus import StdioBus
from stdiobus.types import DockerOptions

bus = StdioBus(
    config_path='./config.json',
    backend='docker',
    docker=DockerOptions(
        image='stdiobus/stdiobus:node20',
        pull_policy='if-missing',  # never, if-missing, always
        startup_timeout_sec=15.0,
        extra_args=['-v', '/path/to/worker.js:/worker.js:ro'],
        env={'DEBUG': '1'},
    ),
)
```

## License

Apache-2.0
