Skip to main content

Kover

Build status Line coverage snapshot: 90.9% License Python 3.12 or newer PyPI version Typed package

Async MongoDB driver for Python with first-class Pydantic support.
Save, validate, find, update, and delete data with typed models or dictionaries.

For example, define a User model, save a user to the database, and read it back as a User object with validated fields and editor autocomplete.

Use it for async applications such as a FastAPI backend storing users, products, or messages. It requires Python 3.12+ and Pydantic v2.

Where does Kover fit?

Your Python application (for example, a FastAPI backend)
    → Kover (validates models and sends database requests)
    → MongoDB (stores your data)
  • A MongoDB driver: connects your application to MongoDB and runs database operations asynchronously with await. No PyMongo or Motor dependency.
  • Pydantic integration: define the shape of your data with Python classes, validate it, and read database results back as model instances. Plain dictionaries work too.
  • Optional database-side validation: generate MongoDB validation rules from your models so the database can reject invalid documents too.

Kover is a Python library, not a database or a web framework. You still need a running MongoDB server, locally or hosted. It has its own API; it is not a drop-in replacement for PyMongo or Motor.

Want to see it in an API? See the complete FastAPI CRUD application.

Contents

Capabilities and requirements

Kover talks directly to MongoDB using asyncio streams and MongoDB's OP_MSG / OP_COMPRESSED wire protocol, without thread-pool wrappers.

  • Native asynchronous clients, per-server connection pools, and lazy cursors.
  • Live discovery and monitoring (SDAM) for standalone servers, replica sets, and sharded deployments.
  • All five read preference modes, ordered tag sets, max staleness, and latency windows.
  • Pydantic Document models and strict MongoDB $jsonSchema generation.
  • CRUD, aggregation, indexes, database/user administration, and GridFS.
  • Logical sessions and explicit multi-document transactions.
  • SCRAM-SHA-256 / SCRAM-SHA-1 authentication, TLS, and negotiated compression.

Requires Python 3.12+ and a reachable MongoDB deployment. Transactions need a replica set or sharded cluster; server-level bulkWrite needs MongoDB 8.0+. Check MongoDB's version requirements for other commands you use.

Runtime dependencies:

Dependency Minimum version
elune 0.5.0
dnspython 2.7.0
pydantic 2.14.3

Kover uses Elune for BSON serialization.

Installation

Install Kover using pip:

pip install kover

Or using uv:

uv add kover
# Optional Snappy and Zstandard compression:
uv add "kover[snappy,zstd]"

Quick start

With MongoDB running at 127.0.0.1:27017, save this as main.py and run python main.py. This example defines a user, saves it, and reads it back:

import asyncio

from pydantic import Field

from kover import Document, from_uri


class User(Document):
    name: str
    age: int = Field(ge=0)


async def main() -> None:
    async with await from_uri("mongodb://127.0.0.1:27017/") as client:
        # .get_database and .get_collection are also exists
        users = client.demo.users

        # Validate the data with Pydantic, then save it to MongoDB.
        user = User(name="Maksim", age=21)
        user_id = await users.insert_one(user)

        # Read it back as a User object rather than a dictionary.
        user = await users.find_one({"_id": user_id}, cls=User)
        if user is not None:
            print(user.name, user.age)  # Maksim 21


if __name__ == "__main__":
    asyncio.run(main())

User(name="Maksim", age=-1) raises a Pydantic validation error before any database request. cls=User also validates documents when reading them back. To enforce rules inside MongoDB itself, see MongoDB schema validation.

You can also pass dictionaries to insert_one() and omit cls when querying to receive dictionaries instead. Each run of this example inserts a new user.

from_uri() and make_client() are module-level factory functions returning a Kover client. They are not methods on the Kover class. Factories perform initial server selection and start SDAM monitoring; application connections are opened lazily in per-server pools.

The remaining asynchronous snippets belong inside an async function. Unless a snippet creates its own client, it assumes an open client and reuses models and collection handles introduced earlier. Close clients with async with or await client.close() when finished.

Connections and routing

Explicit configuration

from kover import AuthCredentials, make_client

credentials = AuthCredentials.from_environ()
client = await make_client(
    host="127.0.0.1",
    port=27017,
    credentials=credentials,
    tls=False,
    compression=["zlib"],
    max_pool_size=50,
)
async with client:
    await client.admin.ping()

AuthCredentials.from_environ() reads MONGO_USER, MONGO_PASSWORD, and optional MONGO_AUTH_DB (default admin). It returns None if neither credential is set and raises CredentialsException if only one is provided. URI credentials use authSource, then the URI database, then admin. Percent-encode reserved characters in URI usernames and passwords.

URI configuration supports TLS and compressor negotiation, for example mongodb://user:pass@host/demo?authSource=admin&tls=true&compressors=zlib. Do not hardcode production secrets. Authentication selects SCRAM-SHA-256 or SCRAM-SHA-1 from the mechanisms advertised by hello.

Discovery and timeouts

URI seeds are probed concurrently; discovery follows replica set members advertised by hello. Use hostnames reachable as advertised in the replica set configuration, not just reachable seed aliases.

URI option make_client() argument Default
replicaSet replica_set No expected set name
directConnection direct_connection False
serverSelectionTimeoutMS server_selection_timeout 30 seconds
connectTimeoutMS connect_timeout 10 seconds
localThresholdMS local_threshold 0.015 seconds
heartbeatFrequencyMS heartbeat_frequency 10 seconds; minimum 500 ms
serverMonitoringMode server_monitoring_mode "auto" ("poll" or "stream")
maxPoolSize max_pool_size 100 connections per server

URI durations in this table use milliseconds; Python arguments use seconds. connect_timeout limits connection setup, including the handshake and authentication. connect_timeout=None (connectTimeoutMS=0) disables the per-connection setup limit for the application pool; monitors use a 10-second base timeout. Server selection and explicit operation deadlines still apply.

server_selection_timeout limits selection, not command execution. Neither setting is a socket timeout for commands on established connections. client.command() and Database.command() accept an absolute deadline measured by the event-loop clock.

Read preferences

from kover import ReadPreference, from_uri

client = await from_uri(
    "mongodb://seed1:27017,seed2:27017/shop?replicaSet=rs0"
    "&readPreference=secondaryPreferred"
    "&readPreferenceTags=region:east"
    "&readPreferenceTags="
    "&maxStalenessSeconds=120"
    "&localThresholdMS=15",
)
async with client:
    orders = client.shop.orders
    cursor = orders.find({}).read_preference(ReadPreference("nearest"))
    documents = await cursor.to_list()
    reply = await client.command(
        {"count": "orders"},
        database="shop",
        read_preference=ReadPreference("primary"),
    )

Modes are primary (default), primaryPreferred, secondary, secondaryPreferred, and nearest. Ordered tag sets are tried after staleness filtering; {} is a catch-all. Max staleness is -1 (disabled) or an integer of at least 90 seconds. primary rejects nonempty tags and enabled staleness. Tags/staleness do not constrain a preferred mode's primary fallback.

Eligible reads use the effective read preference; writes, unknown/admin commands, and aggregations containing $out / $merge use primary routing. Configure cursor overrides before execution. getMore and killCursors retain server affinity, not socket affinity. Transactions require primary reads and pin a server address, never a connection.

directConnection=true requires one non-SRV seed and keeps operations on it, even if it is a secondary. Writes are not redirected; direct mode does not make secondary transactions valid.

SDAM and server monitoring

Kover starts a background monitor for each seed during initial server selection and follows replica-set membership changes reported by hello. Heartbeats use dedicated connections, so they don't compete with application operations for pool capacity. When a heartbeat fails, the server is marked Unknown and monitored for recovery. Topology changes wake waiting selectors, so a later operation can use a new primary without recreating the client.

The default mode, "auto", prefers streaming hello when the server reports topologyVersion and uses polling in detected FaaS environments. Use "poll" to force polling or "stream" to prefer streaming explicitly:

from kover import make_client


client = await make_client(
    host="db1",
    heartbeat_frequency=5.0,
    server_monitoring_mode="stream",
)
async with client:
    await client.admin.ping()

The equivalent URI options are:

mongodb://db1:27017/?heartbeatFrequencyMS=5000&serverMonitoringMode=stream

"stream" falls back to polling if a server doesn't advertise topologyVersion. Closing the client stops monitoring before closing the application pools. See the SDAM guide for timeout and pool retirement details.

What SDAM doesn't do: Kover does not retry or replay failed commands. A command can still fail during an election, and a transaction or cursor pinned to an address does not move to another server. Load-balanced mode and custom TLS certificate options are not supported.

Typed documents and BSON

Document extends Pydantic's BaseModel with extra="forbid", use_enum_values=True, and serialize_by_alias=True. MongoDB's _id is a regular model field named object_id, with alias _id and default None. model_dump() uses field aliases and omits _id when its value is None.

from uuid import UUID, uuid4

from pydantic import Field

from kover import Document


class User(Document):
    username: str = Field(min_length=3, max_length=32)
    age: int = Field(ge=18)
    external_id: UUID = Field(default_factory=uuid4, alias="externalId")

Native UUIDs require an explicit BSON representation. Use this client for the User schema and CRUD examples below:

from elune import CodecOptions, UuidRepresentation

from kover import from_uri

client = await from_uri(
    "mongodb://127.0.0.1:27017/",
    codec_options=CodecOptions(  # or via url parameter
        uuid_representation=UuidRepresentation.STANDARD,
    ),
)
users = client.demo.users

make_client() accepts the same codec_options= argument. STANDARD encodes UUIDs as binary subtype 4 and decodes them back to UUID. The default UNSPECIFIED representation rejects native UUID encoding. Keep this client open for the following examples and close it when done.

API Purpose
doc.model_dump() Python-mode dump using field aliases, including _id when set
doc.model_dump(exclude={"object_id"}) Dump without _id; exclusion uses the Python field name
Model.model_validate(payload) Validate a MongoDB document, including its _id
doc.object_id / doc.object_id = value Read or assign the document ID
Model.model_mongodb_schema() Generate a {"$jsonSchema": ...} validator
from elune import ObjectId

user = User(username="alice", age=27)
assert user.object_id is None
assert "_id" not in user.model_dump()

identifier = ObjectId()
stored = User.model_validate({"_id": identifier, **user.model_dump()})
assert stored.object_id == identifier
assert stored.model_dump()["_id"] == identifier

Insert operations do not assign generated IDs back to the input model; assign user.object_id = await users.insert_one(user) if needed. Field names are not automatically converted to camelCase: declare aliases explicitly, as with externalId above. See documents and serialization for details.

Use Python-mode dumps for BSON, not model_dump(mode="json"). Elune's native Pydantic integration preserves BSON instances in Python mode.

Decimal values

Schema generation is not value conversion. A decimal.Decimal annotation produces a decimal schema, but model_dump() retains the Python Decimal; it needs a codec or explicit conversion for BSON encoding.

For domain models using Decimal, prefer the DecimalCodec example in the Elune README over manual conversion or model serializers. Define that codec in your application and register it with CodecOptions(type_registry=TypeRegistry([DecimalCodec()])) (CodecOptions and TypeRegistry are imported from elune.codec_options). Pass these options as codec_options= to from_uri() or make_client(); if you also use UUIDs, include their representation in the same options. The codec converts Decimal to BSON Decimal128 on writes and back to Decimal on reads, including values in nested documents. Values must still fit the precision and range of Decimal128. DecimalCodec is an example to define, not a built-in class to import.

Alternatively, use elune.Decimal128 directly for stored values:

from decimal import Decimal

from elune import Decimal128

from kover import Document


class Product(Document):
    price: Decimal128


product = Product(price=Decimal128(Decimal("19.99")))
payload = product.model_dump()

MongoDB schema validation

from kover import ValidationLevel

users = await client.demo.users.create_if_not_exists()
await users.set_validator(
    User.model_mongodb_schema(),
    level=ValidationLevel.STRICT,
)
user = User(username="alice", age=27)
alice_id = await users.insert_one(user)

The generator resolves references, normalizes JSON Schema, maps BSON types, and checks MongoDB compatibility without mutating the input schemas. Unsupported constraints raise SchemaGenerationException; there is no permissive mode that silently removes validation rules.

The root _id is required and has bsonType: "objectId", without a null branch. None is only an application-side placeholder for an unset ID and is excluded from dumps. Nested Document models also declare _id, but it is optional in their schemas; plain Pydantic models do not inherit this field.

Examples of unsupported constraints include recursive/external references, email/IP format, discriminators, constrained binary lengths, UUID versions, datetime bounds/timezone constraints, and decimal digit/scale limits. Custom Python validators are not translated into server-side rules. Defaults are applied by Pydantic, not MongoDB; default annotations are omitted from the server validator. MongoDB cannot enforce binary subtypes or UUID contents through these schemas.

CRUD and cursors

from kover import Delete, Update

await users.insert_many(
    [
        User(username="charlie", age=31),
        User(username="dana", age=24),
    ]
)
user: User | None = await users.find_one({"username": "charlie"}, cls=User)

cursor = (
    users.find({"age": {"$gte": 21}}, cls=User)
    .sort({"age": -1})
    .limit(50)
    .batch_size(25)
)
async with cursor:
    async for item in cursor:
        print(item.object_id, item.username)

all_users: list[User] = await users.find({}, cls=User).to_list()
await users.update(Update({"username": "charlie"}, {"$set": {"age": 32}}))
deleted = await users.delete(Delete({"username": "dana"}, limit=1))

Without cls=, queries return dictionaries. insert_one() returns an ID; insert_many() returns a list of IDs. update(*updates) and delete(*deletes) accept operation models as positional arguments. Use update operators such as $set / $inc; deletion uses limit=1 for one match or limit=0 for all.

Cursors are lazy and support sort, skip, limit, batch_size, projection, hint, comment, and collation. A projection used with cls=Model must retain the fields required to validate that model. A cursor cannot be read concurrently across tasks. Use async with cursor: when iteration may stop early to clean up the server cursor. to_list() consumes remaining results; first() raises StopAsyncIteration if empty. Close the cursor if you only consume its first item.

group_by_age = [{"$group": {"_id": "$age", "count": {"$sum": 1}}}]
stats = await users.aggregate(group_by_age).to_list()

adults = [{"$match": {"age": {"$gte": 18}}}]
plan = await users.aggregate(adults, explain=True).command_result()

Aggregation returns a lazy cursor. For commands returning a document rather than a cursor, such as aggregation explain, use command_result(). Collection helpers also cover index management, collection options, and validators.

Bulk writes

BulkWriteBuilder targets one or more database.collection namespaces using MongoDB 8.0+'s server-level bulkWrite command. Execution and result fetching are lazy; result cursors can require getMore round trips.

from kover import BulkWriteBuilder, Delete, Update

builder = BulkWriteBuilder(ordered=True, errors_only=False)
builder.add_insert([{"sku": "A-1", "quantity": 5}], ns="demo.inventory")
builder.add_update(
    Update({"sku": "A-1"}, {"$set": {"quantity": 10}}),
    ns="demo.inventory",
)
builder.add_delete(Delete({"sku": "obsolete"}, limit=1), ns="demo.inventory")
results = await client.bulk_write(builder.build()).to_list()

Sessions and transactions

Sessions and transactions are not context managers. Start transactions synchronously; await commit/abort and explicitly end sessions.

orders = await client.demo.orders.create_if_not_exists()
session = await client.start_session()
try:
    session.start_transaction()
    await orders.insert_one({"status": "created"}, session=session)
    await orders.insert_one({"status": "queued"}, session=session)
    await session.commit_transaction()
finally:
    try:
        await session.close()
    finally:
        await client.end_sessions([session])
  • Pass the same session to every participating operation; it must belong to the same client.
  • Reads require an effective ReadPreference("primary"). Override transaction read cursors if the client default is non-primary.
  • start_transaction(options=...) stores options locally but does not apply them to commands.
  • Empty transactions commit/abort locally without sending a transaction command.
  • session.close() aborts an unfinished transaction and clears its server pin; it does not replace end_sessions().
  • There is no automatic transaction retry wrapper. Inspect OperationFailure.is_transient_transaction_error and .is_unknown_commit_result for application-controlled retries.
  • An unknown commit result retains the transaction number and server pin for explicit commit retry. The cleanup example above does not implement retries.

See Transactions before implementing production retry logic.

GridFS

GridFS stores files as chunks, allowing files larger than MongoDB's 16 MiB document limit. Uploads and downloads can both stream without assembling a complete file in memory.

from kover import GridFS

fs = await GridFS(client.get_database("files")).indexed()
async with fs.open_upload_stream("hello.txt") as upload:
    await upload.write(b"Hello from ")
    await upload.write(b"GridFS!")

file_doc, download = await fs.open_download_stream(
    upload.file_id, chunk_size=64 * 1024,
)
async with download:
    async for chunk in download:
        print(chunk)

await fs.put(source) accepts an async iterable of bytes, pathlib.Path, binary or text file objects, and in-memory bytes or str. Local files are read in bounded blocks in a worker thread. The driver writes bounded batches and only publishes the file document after the last batch. Use small input blocks when producing an async source to keep its own memory use bounded.

An upload stream publishes on successful exit from async with or close(). Call await upload.abort() to discard it. Source errors and exceptions in the upload context also abort the upload. Failed MongoDB writes can leave orphaned chunks, as specified by GridFS.

open_download_stream(chunk_size=...) sets the output block size in bytes. The last block may be shorter. Without it, the stream yields the chunks as stored in MongoDB. Downloads check stored chunk order and sizes. SHA-1 is stored in metadata by default and checked at the end of a complete download when present. Leaving the download context early closes the cursor without checking the full hash. For small files, get_by_file_id() and get_by_filename() still return the complete data as a BytesIO buffer.

Errors

  • OperationFailure: MongoDB command/write failure, with .code, .message, .code_name, .details, .err_info, and .error_labels. Server error codes map to subclasses such as DuplicateKey.
  • ServerSelectionError: no suitable server before the selection deadline, with per-server diagnostics.
  • PoolTimeoutError: checkout, connection setup, or selection-lock deadline exceeded. PoolClosedError / PoolPausedError describe unavailable pools.
  • NetworkError / ProtocolError: failed socket exchange or invalid server wire reply. Initial connection setup may also propagate OSError.
  • CredentialsException: incomplete environment credentials.
  • SchemaGenerationException: unsupported schema or constraint. Invalid model data raises Pydantic ValidationError.
  • GridFSFileNotFound / IncorrectGridFSData: missing file, unsupported upload payload, or invalid download chunk. A checksum mismatch raises RuntimeError.
  • ValueError / TypeError: invalid configuration, session ownership, or operation use. BSON encoding errors are local errors, not MongoDB command failures.

For raw operations use await client.command(document, database="demo") or await client.demo.command(document). There is no client.request() API.

Development

uv sync --dev
uv run pytest tests/unit tests/functional -q
KOVER_RUN_INTEGRATION=0 uv run pytest tests -q
uv run ruff check kover tests examples
uv run pyright kover tests examples

Unit tests include local TCP protocol tests but do not require MongoDB. Integration tests are opt-in:

KOVER_RUN_INTEGRATION=1 \
  MONGO_HOST=127.0.0.1 \
  MONGO_PORT=27017 \
  uv run pytest tests/integration -v

Optional credentials use MONGO_USER, MONGO_PASSWORD, and MONGO_AUTH_DB. The current test suite does not consume MONGODB_URI. Use a deployment supporting the tested features, including transactions and MongoDB 8.0+ bulk writes. To run against a sharded deployment, point MONGO_HOST and MONGO_PORT at a mongos router on a disposable cluster.

Test coverage

The badge is a snapshot of 90.9% line coverage for kover at e2c16b3, measured with the unit and functional suites and the GridFS integration tests. With MongoDB running, reproduce the measurement with:

KOVER_RUN_INTEGRATION=1 uv run --with coverage python -m coverage run \
  --source=kover -m pytest tests/unit tests/functional \
  tests/integration/test_gridfs.py -q
uv run --with coverage python -m coverage report --precision=1

Documentation and examples

Bug reports and contributions are welcome via GitHub Issues and pull requests. Please follow the Code of Conduct.

License

Kover is licensed under the Apache License 2.0. Copyright (c) 2024–present megawattka.

The Code of Conduct is separately licensed under Creative Commons Attribution 4.0 International.

Metadata

Release files for kover 3.4.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kover 3.4.4
File Size Uploaded Provenance Actions
kover-3.4.4.tar.gz 127.1 kB Without provenance Details for kover-3.4.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kover 3.4.4
File Interpreter ABI Platform Actions
kover-3.4.4-py3-none-any.whl Python 3 none any Details for kover-3.4.4-py3-none-any.whl

Total release size: 298.6 kB

Release files / kover-3.4.4.tar.gz

Download URL kover-3.4.4.tar.gz
Size 127.1 kB
Tags Source
SHA-256 checksum
How to use checksums
3ac2e213bfd816a728dd11a3a02574d8fd1ba707466116ecf16c156b9d940efc
BLAKE2b-256 checksum
How to use checksums
686b001f5d6c2624eb4129ae0468fcc14e69293d2af735edce82f0135564153d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.19

Release files / kover-3.4.4-py3-none-any.whl

Download URL kover-3.4.4-py3-none-any.whl
Size 171.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
375a766fcfa4c1547e305a867d5fa7ea0dc66834810d7323ee95341431e03870
BLAKE2b-256 checksum
How to use checksums
c321f4cc50f8092e3c4aa269047dccd0dd9b443ccdcaaf40783794b15429e400
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.19

Security for kover 3.4.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page