# Cap'n Web Python
A complete Python implementation of the [Cap'n Web protocol](https://github.com/cloudflare/capnweb) - a capability-based RPC system with promise pipelining, structured errors, and multiple transport support.
## What's in the Box
**Core Features:**
- **Capability-based security** - Unforgeable object references with explicit disposal
- **Promise pipelining** - Batch multiple dependent calls into single round-trips
- **Multiple transports** - HTTP Batch, WebSocket, and WebTransport/HTTP/3
- **Type-safe** - Full type hints compatible with pyright/mypy
- **Async/await** - Built on Python's asyncio
- **Bidirectional RPC** - Peer-to-peer capability passing
- **100% Interoperable** - Fully compatible with TypeScript reference implementation
**Beta-Testing-Ready":**
- 352 tests passing, 76% coverage
- 0 linting errors, 0 typing errors
- Hook-based architecture (clean, maintainable)
- ~99% protocol compliance
## Why Use Cap'n Web?
**Traditional RPC has problems:**
- No security model (anyone can call anything)
- No resource management (memory leaks)
- Poor performance (round-trip per call)
**Cap'n Web solves these:**
- **Security**: Capabilities are unforgeable - you can only call what you have a reference to
- **Resource Management**: Explicit disposal with reference counting prevents leaks
- **Performance**: Promise pipelining batches dependent calls into one round-trip
- **Flexibility**: Pass capabilities as arguments - the server decides who gets access
## Installation
```bash
pip install capnweb
# or
uv add capnweb
# For WebTransport support (optional):
pip install capnweb[webtransport]
```
## Quick Start
**Server:**
```python
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:
match method:
case "add": return args[0] + args[1]
case "multiply": return args[0] * args[1]
case _: raise RpcError.not_found(f"Unknown method: {method}")
async def get_property(self, property: str) -> any:
raise RpcError.not_found("No properties")
async def main():
server = Server(ServerConfig(host="127.0.0.1", port=8080))
server.register_capability(0, Calculator())
await server.start()
await asyncio.Event().wait() # Run forever
```
**Client:**
```python
from capnweb.client import Client, ClientConfig
async with Client(ClientConfig(url="http://localhost:8080/rpc/batch")) as client:
result = await client.call(0, "add", [5, 3])
print(f"5 + 3 = {result}") # Output: 8
```
**Promise Pipelining** (advanced):
```python
async with Client(config) as client:
batch = client.pipeline()
# These calls are batched into a single HTTP request!
user = batch.call(0, "getUser", ["alice"])
profile = batch.call(0, "getProfile", [user.id]) # Property access on promise!
posts = batch.call(0, "getPosts", [user.id])
u, p, posts_data = await asyncio.gather(user, profile, posts)
```
## Current Status (v0.4.0)
**Transports:**
- ✅ HTTP Batch
- ⚠️ WebSocket (partial support - client→server RPC only, bidirectional RPC in progress)
- ✅ WebTransport/HTTP/3 (requires aioquic)
**Protocol Features:**
- ✅ Wire protocol (all message types)
- ✅ Promise pipelining
- ✅ Expression evaluation (including `.map()`)
- ⚠️ Bidirectional RPC (HTTP Batch only, WebSocket support in progress)
- ✅ Resume tokens
- ✅ Reference counting
- ✅ Structured errors
- ⚠️ IL plan execution (only remap supported, full IL is low priority)
**Code Quality:**
- ✅ 352 tests passing (100% success rate)
- ✅ 76% test coverage
- ✅ 0 linting errors (ruff)
- ✅ 0 typing errors (pyrefly)
- ✅ TypeScript interoperability verified
## Documentation
- **[Quickstart Guide](docs/quickstart.md)** - Get started in 5 minutes
- **[API Reference](docs/api-reference.md)** - Complete API documentation
- **[Architecture Guide](docs/architecture.md)** - Understand the internals
- **[Examples](examples/)** - Working code examples
## Examples
**Included examples:**
- `examples/calculator/` - Simple RPC calculator
- `examples/batch-pipelining/` - Promise pipelining demonstration
- `examples/peer_to_peer/` - Bidirectional RPC (Alice & Bob) - HTTP Batch only
- `examples/chat/` - ⚠️ Real-time WebSocket chat (requires bidirectional WebSocket - in progress)
- `examples/microservices/` - Service mesh architecture
- `examples/actor-system/` - Distributed actor system with supervisor/worker
- `examples/webtransport/` - WebTransport/HTTP/3 standalone demo
- `examples/webtransport-integrated/` - WebTransport with full RPC
Each example includes a README with running instructions.
## Transport Limitations
**Current WebSocket Support:**
- ✅ Client can connect to server via `ws://` or `wss://` URLs
- ✅ Client can call server methods (request-response RPC)
- ✅ Server can respond to client requests
- ❌ Server **cannot** initiate calls to clients (no bidirectional RPC yet)
- ❌ Chat example currently non-functional due to this limitation
**Workaround for bidirectional RPC:**
Use HTTP Batch transport instead - it supports full bidirectional RPC including:
- Passing client capabilities to server
- Server calling methods on client capabilities
- See `examples/peer_to_peer/` for working bidirectional RPC example
**WebTransport:**
- Full bidirectional support
- Requires `aioquic` library: `pip install capnweb[webtransport]`
## Development
```bash
# Clone and install
git clone https://github.com/abilian/py-capnweb.git
cd py-capnweb
uv sync
# Run tests
pytest
# or
make test
# Run linting & type checking
ruff check
pyrefly check
# or
make check
# Run with coverage
pytest --cov=capnweb --cov-report=term-missing
```
## Protocol Compliance
This implementation follows the [Cap'n Web protocol specification](https://github.com/cloudflare/capnweb/blob/main/protocol.md).
**Interoperability Testing:**
Cross-implementation testing with TypeScript reference validates all combinations:
- Python Server ↔ Python Client ✅
- Python Server ↔ TypeScript Client ✅
- TypeScript Server ↔ Python Client ✅
- TypeScript Server ↔ TypeScript Client ✅
Run interop tests: `cd interop && bash run_tests.sh`
## What's New
See [CHANGES.md](CHANGES.md) for detailed release notes.
**v0.4.0** (latest):
- WebTransport/HTTP/3 support with certificate management
- Actor system example with distributed capabilities
- "Perfect" code quality (0 linting errors, 0 typing errors)
- 352 tests passing
**v0.3.1**:
- Comprehensive documentation (quickstart, architecture, API reference)
- 85% test coverage (up from 67%)
- Legacy code removed (clean hook-based architecture)
**v0.3.0**:
- Promise pipelining support
- 100% TypeScript interoperability
- Array escaping for compatibility
## License
Dual-licensed under MIT or Apache-2.0, at your option.
Raw data
{
"_id": null,
"home_page": null,
"name": "py-capnweb",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.11",
"maintainer_email": null,
"keywords": "rpc, capabilities, capnweb, websockets, http3",
"author": "Cap'n Web Contributors",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/d9/ca/bf9024c723782f103b1e2b7be37255017a0c23c4540648f6ea2e25275aee/py_capnweb-0.4.2.tar.gz",
"platform": null,
"description": "# Cap'n Web Python\n\nA complete Python implementation of the [Cap'n Web protocol](https://github.com/cloudflare/capnweb) - a capability-based RPC system with promise pipelining, structured errors, and multiple transport support.\n\n## What's in the Box\n\n**Core Features:**\n- **Capability-based security** - Unforgeable object references with explicit disposal\n- **Promise pipelining** - Batch multiple dependent calls into single round-trips\n- **Multiple transports** - HTTP Batch, WebSocket, and WebTransport/HTTP/3\n- **Type-safe** - Full type hints compatible with pyright/mypy\n- **Async/await** - Built on Python's asyncio\n- **Bidirectional RPC** - Peer-to-peer capability passing\n- **100% Interoperable** - Fully compatible with TypeScript reference implementation\n\n**Beta-Testing-Ready\":**\n- 352 tests passing, 76% coverage\n- 0 linting errors, 0 typing errors\n- Hook-based architecture (clean, maintainable)\n- ~99% protocol compliance\n\n## Why Use Cap'n Web?\n\n**Traditional RPC has problems:**\n- No security model (anyone can call anything)\n- No resource management (memory leaks)\n- Poor performance (round-trip per call)\n\n**Cap'n Web solves these:**\n- **Security**: Capabilities are unforgeable - you can only call what you have a reference to\n- **Resource Management**: Explicit disposal with reference counting prevents leaks\n- **Performance**: Promise pipelining batches dependent calls into one round-trip\n- **Flexibility**: Pass capabilities as arguments - the server decides who gets access\n\n## Installation\n\n```bash\npip install capnweb\n# or\nuv add capnweb\n\n# For WebTransport support (optional):\npip install capnweb[webtransport]\n```\n\n## Quick Start\n\n**Server:**\n```python\nfrom capnweb.server import Server, ServerConfig\nfrom capnweb.types import RpcTarget\nfrom capnweb.error import RpcError\n\nclass Calculator(RpcTarget):\n async def call(self, method: str, args: list) -> any:\n match method:\n case \"add\": return args[0] + args[1]\n case \"multiply\": return args[0] * args[1]\n case _: raise RpcError.not_found(f\"Unknown method: {method}\")\n\n async def get_property(self, property: str) -> any:\n raise RpcError.not_found(\"No properties\")\n\nasync def main():\n server = Server(ServerConfig(host=\"127.0.0.1\", port=8080))\n server.register_capability(0, Calculator())\n await server.start()\n await asyncio.Event().wait() # Run forever\n```\n\n**Client:**\n```python\nfrom capnweb.client import Client, ClientConfig\n\nasync with Client(ClientConfig(url=\"http://localhost:8080/rpc/batch\")) as client:\n result = await client.call(0, \"add\", [5, 3])\n print(f\"5 + 3 = {result}\") # Output: 8\n```\n\n**Promise Pipelining** (advanced):\n```python\nasync with Client(config) as client:\n batch = client.pipeline()\n\n # These calls are batched into a single HTTP request!\n user = batch.call(0, \"getUser\", [\"alice\"])\n profile = batch.call(0, \"getProfile\", [user.id]) # Property access on promise!\n posts = batch.call(0, \"getPosts\", [user.id])\n\n u, p, posts_data = await asyncio.gather(user, profile, posts)\n```\n\n## Current Status (v0.4.0)\n\n**Transports:**\n- \u2705 HTTP Batch\n- \u26a0\ufe0f WebSocket (partial support - client\u2192server RPC only, bidirectional RPC in progress)\n- \u2705 WebTransport/HTTP/3 (requires aioquic)\n\n**Protocol Features:**\n- \u2705 Wire protocol (all message types)\n- \u2705 Promise pipelining\n- \u2705 Expression evaluation (including `.map()`)\n- \u26a0\ufe0f Bidirectional RPC (HTTP Batch only, WebSocket support in progress)\n- \u2705 Resume tokens\n- \u2705 Reference counting\n- \u2705 Structured errors\n- \u26a0\ufe0f IL plan execution (only remap supported, full IL is low priority)\n\n**Code Quality:**\n- \u2705 352 tests passing (100% success rate)\n- \u2705 76% test coverage\n- \u2705 0 linting errors (ruff)\n- \u2705 0 typing errors (pyrefly)\n- \u2705 TypeScript interoperability verified\n\n## Documentation\n\n- **[Quickstart Guide](docs/quickstart.md)** - Get started in 5 minutes\n- **[API Reference](docs/api-reference.md)** - Complete API documentation\n- **[Architecture Guide](docs/architecture.md)** - Understand the internals\n- **[Examples](examples/)** - Working code examples\n\n## Examples\n\n**Included examples:**\n- `examples/calculator/` - Simple RPC calculator\n- `examples/batch-pipelining/` - Promise pipelining demonstration\n- `examples/peer_to_peer/` - Bidirectional RPC (Alice & Bob) - HTTP Batch only\n- `examples/chat/` - \u26a0\ufe0f Real-time WebSocket chat (requires bidirectional WebSocket - in progress)\n- `examples/microservices/` - Service mesh architecture\n- `examples/actor-system/` - Distributed actor system with supervisor/worker\n- `examples/webtransport/` - WebTransport/HTTP/3 standalone demo\n- `examples/webtransport-integrated/` - WebTransport with full RPC\n\nEach example includes a README with running instructions.\n\n## Transport Limitations\n\n**Current WebSocket Support:**\n- \u2705 Client can connect to server via `ws://` or `wss://` URLs\n- \u2705 Client can call server methods (request-response RPC)\n- \u2705 Server can respond to client requests\n- \u274c Server **cannot** initiate calls to clients (no bidirectional RPC yet)\n- \u274c Chat example currently non-functional due to this limitation\n\n**Workaround for bidirectional RPC:**\nUse HTTP Batch transport instead - it supports full bidirectional RPC including:\n- Passing client capabilities to server\n- Server calling methods on client capabilities\n- See `examples/peer_to_peer/` for working bidirectional RPC example\n\n**WebTransport:**\n- Full bidirectional support\n- Requires `aioquic` library: `pip install capnweb[webtransport]`\n\n## Development\n\n```bash\n# Clone and install\ngit clone https://github.com/abilian/py-capnweb.git\ncd py-capnweb\nuv sync\n\n# Run tests\npytest\n# or\nmake test\n\n# Run linting & type checking\nruff check\npyrefly check\n# or\nmake check\n\n# Run with coverage\npytest --cov=capnweb --cov-report=term-missing\n```\n\n## Protocol Compliance\n\nThis implementation follows the [Cap'n Web protocol specification](https://github.com/cloudflare/capnweb/blob/main/protocol.md).\n\n**Interoperability Testing:**\nCross-implementation testing with TypeScript reference validates all combinations:\n- Python Server \u2194 Python Client \u2705\n- Python Server \u2194 TypeScript Client \u2705\n- TypeScript Server \u2194 Python Client \u2705\n- TypeScript Server \u2194 TypeScript Client \u2705\n\nRun interop tests: `cd interop && bash run_tests.sh`\n\n## What's New\n\nSee [CHANGES.md](CHANGES.md) for detailed release notes.\n\n**v0.4.0** (latest):\n- WebTransport/HTTP/3 support with certificate management\n- Actor system example with distributed capabilities\n- \"Perfect\" code quality (0 linting errors, 0 typing errors)\n- 352 tests passing\n\n**v0.3.1**:\n- Comprehensive documentation (quickstart, architecture, API reference)\n- 85% test coverage (up from 67%)\n- Legacy code removed (clean hook-based architecture)\n\n**v0.3.0**:\n- Promise pipelining support\n- 100% TypeScript interoperability\n- Array escaping for compatibility\n\n## License\n\nDual-licensed under MIT or Apache-2.0, at your option.\n",
"bugtrack_url": null,
"license": "MIT OR Apache-2.0",
"summary": "Python implementation of the Cap'n Web protocol",
"version": "0.4.2",
"project_urls": {
"Changelog": "https://github.com/abilian/py-capnweb/blob/main/CHANGES.md",
"Documentation": "https://github.com/abilian/py-capnweb#readme",
"Homepage": "https://github.com/abilian/py-capnweb",
"Issues": "https://github.com/abilian/py-capnweb/issues",
"Repository": "https://github.com/abilian/py-capnweb.git"
},
"split_keywords": [
"rpc",
" capabilities",
" capnweb",
" websockets",
" http3"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "f035fdbb060ef7c1056cc4739e3fc514c6731c7f45ef0a6cfa97827450d6933d",
"md5": "d2cc85f6914f07378d94cf53e6edac8a",
"sha256": "4ac28c1e707d4376b3df1d40c7950ec7d7b6a784070170e0a2d6a2d0d7b5e44a"
},
"downloads": -1,
"filename": "py_capnweb-0.4.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "d2cc85f6914f07378d94cf53e6edac8a",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.11",
"size": 53325,
"upload_time": "2025-10-23T09:30:24",
"upload_time_iso_8601": "2025-10-23T09:30:24.386458Z",
"url": "https://files.pythonhosted.org/packages/f0/35/fdbb060ef7c1056cc4739e3fc514c6731c7f45ef0a6cfa97827450d6933d/py_capnweb-0.4.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "d9cabf9024c723782f103b1e2b7be37255017a0c23c4540648f6ea2e25275aee",
"md5": "538cec3e7d60f5535b2b6e1cbfa4ec31",
"sha256": "724119f997bdef00008eb2a041db9e584c1b2ac27276c4d3e05b1de1811ac79c"
},
"downloads": -1,
"filename": "py_capnweb-0.4.2.tar.gz",
"has_sig": false,
"md5_digest": "538cec3e7d60f5535b2b6e1cbfa4ec31",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.11",
"size": 44191,
"upload_time": "2025-10-23T09:30:25",
"upload_time_iso_8601": "2025-10-23T09:30:25.719435Z",
"url": "https://files.pythonhosted.org/packages/d9/ca/bf9024c723782f103b1e2b7be37255017a0c23c4540648f6ea2e25275aee/py_capnweb-0.4.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-10-23 09:30:25",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "abilian",
"github_project": "py-capnweb",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "py-capnweb"
}