Metadata-Version: 2.4
Name: pysip2
Version: 0.1.0
Summary: Typed SIP2 (3M Standard Interchange Protocol) 2.00 codec and AnyIO TCP server
Keywords: sip2,3m,library,smart-lending,selfcheck,tcp,anyio,msgspec
Author: Jordan Russell
Author-email: Jordan Russell <jordan@artek.nz>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Framework :: Trio
Classifier: Intended Audience :: Developers
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 :: 3.14
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: System :: Networking
Requires-Dist: msgspec>=0.21.1
Requires-Dist: anyio>=4.9,<5
Requires-Python: >=3.10, <3.15
Project-URL: Repository, https://github.com/ftsartek/pysip2
Project-URL: Issues, https://github.com/ftsartek/pysip2/issues
Description-Content-Type: text/markdown

# pysip2

A typed implementation of the 3M™ Standard Interchange Protocol (SIP2 2.00) for
Python, built on [`msgspec`](https://jcristharif.com/msgspec/) and
[`anyio`](https://anyio.readthedocs.io/). It ships:

- a complete set of typed message models for every SIP2 2.00 command and
  response (31 structs),
- a full-frame codec for the SIP2 wire format, including optional
  `AY`/`AZ` sequence/checksum error detection, and
- an AnyIO TCP server that dispatches requests to user-registered, decorated
  handlers and replies with protocol-valid fallbacks for
  recognized-but-unimplemented commands.

The package implements the **ACS (server/librarian) side** of the protocol. It is
agnostic to application concerns: handlers may do anything, including forwarding
requests to a library system. It's recommended to ensure any operations here are
asynchronous or non-blocking, or otherwise wrapped in synchronous handlers.

- Python 3.10–3.14
- Runtime dependencies: `msgspec>=0.21.1`, `anyio>=4.9`

## Installation

Available on [PyPI](https://pypi.org/project/pysip2/):

```bash
uv add pysip2
# or
pip install pysip2
```

To work on the library itself, install from a checkout:

```bash
git clone https://github.com/ftsartek/pysip2
cd pysip2
uv sync --all-groups    # runtime dependencies plus test/lint/type tooling
```

## Minimal server

```python
import anyio
from pysip2 import (
    PATRON_STATUS,
    PatronStatusRequest,
    PatronStatusResponse,
    RequestContext,
    SIP2Server,
)


app = SIP2Server(institution_id="MYLIB")


@app.route(PATRON_STATUS)
async def patron_status(
    req: PatronStatusRequest, ctx: RequestContext[PatronStatusRequest, PatronStatusResponse]
) -> PatronStatusResponse:
    return PatronStatusResponse(
        patron_status=" " * 14,
        language=req.language,
        transaction_date=ctx.now_18(),
        institution_id=req.institution_id,
        patron_identifier=req.patron_identifier,
        personal_name="Alice Example",
        valid_patron="Y",
        screen_message=("Welcome",),
    )


anyio.run(app.serve, "127.0.0.1", 6001)
```

The built-in ACS Status response (`98`) is generated automatically for `99`
(SC Status) unless you register `@app.route(SC_STATUS)`.

## Try it end to end

This library implements the ACS (server) side only, so to exercise a running
server you send it raw SIP2 frames yourself. The codec (`encode_message` /
`decode_message`) builds and parses them, and `app.start()` binds an ephemeral
port and serves in the background — handy for a quick script or a test. The
following is self-contained and runnable:

```python
import anyio
from anyio import connect_tcp

from pysip2 import (
    PATRON_STATUS,
    PatronStatusRequest,
    PatronStatusResponse,
    SIP2Server,
    decode_message,
    encode_message,
)

app = SIP2Server(institution_id="MYLIB")


@app.route(PATRON_STATUS)
async def patron_status(req: PatronStatusRequest, ctx) -> PatronStatusResponse:
    return PatronStatusResponse(
        patron_status=" " * 14,
        language=req.language,
        transaction_date=ctx.now_18(),
        institution_id=req.institution_id,
        patron_identifier=req.patron_identifier,
        personal_name="Alice Example",
        valid_patron="Y",
        screen_message=("Welcome",),
    )


async def main() -> None:
    async with app.start() as port:  # binds 127.0.0.1 on an ephemeral port
        async with await connect_tcp("127.0.0.1", port) as stream:
            request = PatronStatusRequest(
                language="001",
                # YYYYMMDD + ZZZZ (blank = local time) + HHMMSS
                transaction_date="20250825" + "    " + "143000",
                institution_id="MYLIB",
                patron_identifier="21234567890",
                terminal_password="",
                patron_password="",
            )
            await stream.send(encode_message(request))
            reply = decode_message(await stream.receive()).message

    assert isinstance(reply, PatronStatusResponse)
    print(reply.personal_name, reply.valid_patron)  # -> Alice Example Y


anyio.run(main)
```

The snippets in the rest of this README extend the `app` above; import the extra
names (`LOGIN`, `LoginResponse`, `SIP2UnsupportedOperation`, …) from `pysip2` as
you use them.

## Forwarding upstream with an async handler

```python
import httpx  # application dependency, not a pysip2 dependency

from pysip2 import ITEM_INFORMATION, ItemInformationRequest, ItemInformationResponse


@app.route(ITEM_INFORMATION)
async def item_information(req: ItemInformationRequest, ctx):
    async with httpx.AsyncClient() as client:
        r = await client.get(
            "https://catalog.example/api/items", params={"id": req.item_identifier}
        )
        data = r.json()
    return ItemInformationResponse(
        circulation_status="03",
        security_marker="01",
        fee_type="01",
        transaction_date=ctx.now_18(),
        item_identifier=req.item_identifier,
        title_identifier=data["title"],
    )
```

## Sync handlers

Plain (non-`async`) handlers are supported and run in an AnyIO worker thread:

```python
@app.route(LOGIN)
def login(req: LoginRequest, ctx):
    return LoginResponse(ok="1")
```

## Declining

Return the fallback response for the route, or raise `SIP2UnsupportedOperation`:

```python
@app.route(PATRON_STATUS)
def handler(req, ctx):
    raise SIP2UnsupportedOperation("not available")
```

## Login gating and custom status

Set `login_required=True` on the server. The first message must be `93`
(Login); failed or missing login sends `94 ok=0` and closes the connection.

## Error detection

- `error_detection="auto"` (default) accepts checksummed or plain frames and
  replies in the same style.
- `error_detection="required"` responds with a checksummed `96` when a trailer
  is missing or invalid.

A checksum mismatch always yields `96` (Request SC Resend); duplicate
`(sequence, checksum)` requests replay the last response; `97` replays the last
response.

## Supported messages

The ACS Status `BX` field reflects registered routes at the positions defined in
the SIP2 spec.

## Development

```bash
uv sync --all-groups
uv run pytest           # run the test suite
uv run ruff check .     # lint
uv run ruff format .    # format
uv run ty check         # type-check
```

The test suite doubles as a usage reference: `tests/test_roundtrip.py` shows
every message type constructed, and `tests/test_server.py` shows the server
exercised over real TCP.

## License

This implementation is released under the MIT License; see [`LICENSE`](LICENSE).

The MIT License covers this library's own code. The 3M Standard Interchange
Protocol specification itself carries its own 3M notice restricting modification
of the protocol document; that notice applies to the spec, not to this
independent implementation.
