Python implementation of the Cap'n Web protocol
Project description
Cap'n Web Python Implementation
Python implementation of the Cap'n Web protocol, delivering both server and client with support for HTTP batch and WebSocket transports.
Features
- Capability-based security: Unforgeable object references with explicit disposal
- Expression evaluation: Full support for wire expressions including remap (
.map()operations) - Multiple transports: HTTP batch and WebSocket with pluggable transport abstraction
- Type-safe: Full type hints with pyright/mypy compatibility
- Async/await: Built on Python's asyncio
- Error handling: Structured error model with security-conscious stack trace redaction
- Reference counting: Automatic resource management with proper refcounting
- Interoperable: Compatible with TypeScript and Rust implementations
Installation
pip install capnweb
# or
uv add capnweb
or, from this repository:
uv sync
Quick Start
Server
import asyncio
from typing import Any
from capnweb.server import Server, ServerConfig
from capnweb.types import RpcTarget
from capnweb.error import RpcError
class Calculator(RpcTarget):
async def call(self, method: str, args: list[Any]) -> Any:
match method:
case "add":
return args[0] + args[1]
case "subtract":
return args[0] - args[1]
case _:
raise RpcError.not_found(f"Method {method} not found")
async def get_property(self, property: str) -> Any:
raise RpcError.not_found("Property access not implemented")
async def main() -> None:
config = ServerConfig(host="127.0.0.1", port=8080)
server = Server(config)
# Register the main capability
server.register_capability(0, Calculator())
await server.start()
print("Calculator server listening on http://127.0.0.1:8080/rpc/batch")
# Keep running
try:
await asyncio.Event().wait()
except KeyboardInterrupt:
await server.stop()
if __name__ == "__main__":
asyncio.run(main())
Client
import asyncio
from capnweb.client import Client, ClientConfig
async def main() -> None:
config = ClientConfig(url="http://localhost:8080/rpc/batch")
# Use async context manager for automatic cleanup
async with Client(config) as client:
# Make RPC calls
result = await client.call(0, "add", [5, 3])
print(f"5 + 3 = {result}") # Output: 5 + 3 = 8
result = await client.call(0, "subtract", [10, 4])
print(f"10 - 4 = {result}") # Output: 10 - 4 = 6
if __name__ == "__main__":
asyncio.run(main())
Development
Setup
# Clone and install with uv
git clone https://github.com/abilian/py-capnweb.git
cd py-capnweb
uv sync
Testing
make test
# or
pytest
pytest tests/test_wire.py -v
# etc.
Linting & Type Checking
# Run linter
ruff check
# Run type checker
pyrefly check src
# Run both
make check
Project Structure
src/capnweb/
├── __init__.py # Public API exports
├── ids.py # ID types (ImportId, ExportId, IdAllocator)
├── error.py # Error types (RpcError, ErrorCode)
├── wire.py # Wire protocol messages and expressions
├── tables.py # Import/Export tables with refcounting
├── types.py # Core types (RpcTarget, Transport protocol)
├── evaluator.py # Expression evaluator with remap support
├── transports.py # Transport implementations (HTTP, WebSocket)
├── server.py # Server with configurable security
├── client.py # Client with automatic resource management
└── __main__.py # CLI entry point (if applicable)
tests/
├── test_ids.py # ID allocation tests
├── test_wire.py # Wire protocol tests
├── test_wire_protocol.py # Advanced protocol features
├── test_tables.py # Import/export table tests
├── test_error.py # Error handling tests
├── test_evaluator.py # Expression evaluation tests
├── test_remap_evaluation.py # Remap (.map) tests
├── test_transports.py # Transport abstraction tests
├── test_improvements.py # Recent enhancements tests
├── test_integration.py # End-to-end integration tests
└── test_bidirectional.py # Peer-to-peer tests
examples/
├── calculator/ # Simple RPC calculator
├── batch-pipelining/ # Batching demonstration
└── peer_to_peer/ # Bidirectional RPC example
Protocol Compliance
This implementation follows the official Cap'n Web protocol specification and supports:
✅ Implemented Features
- Wire Protocol: All core message types (push, pull, resolve, reject, release, abort)
- Wire Expressions: Error, import, export, promise, pipeline, date, remap
- Release with refcount: Proper reference counting for resource management
- Remap expressions: Full
.map()operation support with captures and instructions - Escaped literal arrays:
[[...]]format to prevent special form confusion - Transport abstraction: HTTP batch and WebSocket transports
- Security: Configurable stack trace redaction
- Error handling: Structured error model with custom error data
🚧 Planned Features
- Promise pipelining: Chaining calls without waiting for intermediate results
- WebTransport support: H3-based transport for modern applications
- IL plan execution: Complex multi-step operations
- Recorder macros: Ergonomic client-side API generation
Interoperability
Designed to be fully compatible with:
- TypeScript reference implementation
- Rust implementation (in development)
License
Dual-licensed under MIT or Apache-2.0, at your option.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file py_capnweb-0.2.1.tar.gz.
File metadata
- Download URL: py_capnweb-0.2.1.tar.gz
- Upload date:
- Size: 21.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0rc1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2ea93a8059dcb3c27eecbd117cf55190e65724301f01ea13c0f0603de97d2bd3
|
|
| MD5 |
d0f07f205af9f377156c4ad35fbcb70c
|
|
| BLAKE2b-256 |
f1a9448c572e728d26af6c8d4e4f00ae53e746b81c2353bad636fed96d1fc259
|
File details
Details for the file py_capnweb-0.2.1-py3-none-any.whl.
File metadata
- Download URL: py_capnweb-0.2.1-py3-none-any.whl
- Upload date:
- Size: 26.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0rc1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
976a45962aceb39435184288b228049b2bad31e5fa04776b78ee7839cb9f590e
|
|
| MD5 |
13e4e6988a2acdc8bc08ec10ae1f86b2
|
|
| BLAKE2b-256 |
380d22e9b45ddf0eafba54324c3fe3e1134d3ecf86247a17f061fd6650225a7b
|