AnyRFC
Complete, RFC-compliant protocol clients built with AnyIO structured concurrency

AnyRFC provides RFC-compliant protocol clients that prioritize correctness, security, and modern
async patterns. Built exclusively with AnyIO for structured concurrency.
Why AnyRFC?
๐ฏ RFC Compliance First - Every implementation passes comprehensive RFC test suites
โก Modern Async - Structured concurrency with AnyIO (no asyncio dependency hell)
๐ Security by Default - TLS everywhere, proper certificate validation, secure authentication
๐งช Battle-Tested - Real-world interoperability testing against major servers
๐ Type Safe - Full mypy compliance with strict typing
๐ Complete - Full implementations, not toys or demos
Quick Start
pip install anyrfc
import anyio
from anyrfc import WebSocketClient
async def main():
async with WebSocketClient("wss://echo.websocket.org/") as ws:
await ws.send_text("Hello, AnyRFC!")
async for message in ws.receive():
print(f"Received: {message}")
break
anyio.run(main)
What's Included
๐ WebSocket Client (RFC 6455)
Complete WebSocket implementation with all RFC 6455 features:
from anyrfc import WebSocketClient, CloseCode
async with WebSocketClient("wss://api.example.com/ws") as ws:
await ws.send_text("Hello!")
await ws.send_binary(b"\\x00\\x01\\x02\\x03")
async for message in ws.receive():
if isinstance(message, str):
print(f"Text: {message}")
else:
print(f"Binary: {message.hex()}")
if should_close:
await ws.close(CloseCode.NORMAL_CLOSURE)
break
Features:
- โ
All frame types (text, binary, ping, pong, close)
- โ
Message fragmentation and reassembly
- โ
Proper client-side frame masking
- โ
Extension support framework
- โ
Graceful connection handling
- โ
Real-server compatibility
๐ง Email Clients (IMAP & SMTP)
Battle-tested email clients with full RFC compliance and real-world Gmail compatibility:
from anyrfc import IMAPClient, SMTPClient
async with IMAPClient("imap.gmail.com", use_tls=True) as imap:
await imap.authenticate({"username": "user", "password": "app_password"})
await imap.select_mailbox("INBOX")
messages = await imap.search_messages("UNSEEN")
for msg_id in messages[:5]:
email = await imap.fetch_messages(str(msg_id), "BODY[]")
await imap.store_message_flags(str(msg_id), [b"\\Seen"], "FLAGS")
await imap.append_message("Drafts", email_content, [b"\\Draft"])
bodystructure = await imap.fetch_messages(str(msg_id), "BODYSTRUCTURE")
async with SMTPClient("smtp.gmail.com", use_starttls=True) as smtp:
await smtp.authenticate({"username": "user", "password": "app_password"})
await smtp.send_message(
from_addr="sender@example.com",
to_addrs=["recipient@example.com"],
message="""Subject: Hello from AnyRFC!
This email was sent using AnyRFC's SMTP client!
"""
)
IMAP Features (RFC 9051 Compliant):
- โ
Complete email operations: Read, flag, search, delete
- โ
Draft creation: APPEND with proper literal continuation
- โ
Real-time monitoring: Live email detection with polling
- โ
Attachment extraction: Binary BLOB downloads (PDFs, images, etc.)
- โ
Gmail compatibility: Tested with live Gmail IMAP servers
- โ
Extension support: IDLE, SORT, THREAD, CONDSTORE, QRESYNC
- โ
Battle-tested: Handles 178KB+ attachments and complex operations
Architecture Highlights
AnyIO Structured Concurrency
Every I/O operation uses AnyIO's structured concurrency primitives:
async def websocket_with_timeout():
async with anyio.create_task_group() as tg:
tg.start_soon(websocket_handler)
with anyio.move_on_after(30):
tg.start_soon(heartbeat_sender)
RFC Compliance Testing
from anyrfc.websocket import WebSocketClient
client = WebSocketClient("wss://example.com")
compliance_report = await client.validate_compliance()
assert compliance_report["handshake_validation"] == True
assert compliance_report["frame_parsing"] == True
assert compliance_report["close_sequence"] == True
Type Safety
from anyrfc import WebSocketClient
from anyrfc.websocket import WSFrame, OpCode
client: WebSocketClient = WebSocketClient("wss://api.example.com")
frame: WSFrame = WSFrame(fin=True, opcode=OpCode.TEXT, payload=b"test")
reveal_type(client.websocket_state)
reveal_type(await client.receive())
Installation & Setup
Basic Installation
pip install anyrfc
Development Setup
git clone https://github.com/elgertam/anyrfc.git
cd anyrfc
uv sync --all-extras
pip install -e ".[dev]"
Requirements
- Python: 3.11+
- Core:
anyio>=4.0.0
- HTTP:
httpx>=0.25.0
(approved dependency)
- Types:
typing-extensions>=4.0.0
Real-World Examples
WebSocket Trading Client
from anyrfc import WebSocketClient
import json
async def crypto_prices():
uri = "wss://data-stream.binance.vision/ws/btcusdt@ticker"
async with WebSocketClient(uri, strict_rfc_validation=False) as ws:
async for message in ws.receive():
data = json.loads(message)
if 'c' in data:
price = float(data['c'])
change = float(data['P'])
print(f"๐ฐ BTC-USDT: ${price:,.2f} ({change:+.2f}%)")
Email Monitoring Service
from anyrfc import IMAPClient
import anyio
import re
async def email_monitor():
"""Real-time email monitoring with secret code extraction."""
async with IMAPClient("imap.gmail.com", use_tls=True) as imap:
await imap.authenticate({"username": "user", "password": "app_password"})
await imap.select_mailbox("INBOX")
while True:
unread = await imap.search_messages("UNSEEN")
if unread:
print(f"๐ง {len(unread)} new emails!")
for msg_id in unread:
email_data = await imap.fetch_messages(str(msg_id), "BODY[]")
email_text = email_data[str(msg_id)][b"BODY[]"].decode()
codes = re.findall(r'\b\d{6}\b', email_text)
if codes:
print(f"๐ Verification code found: {codes[0]}")
await imap.store_message_flags(str(msg_id), [b"\\Seen"], "FLAGS")
await anyio.sleep(5)
Testing & Quality
Comprehensive Test Suite
uv run pytest
uv run pytest tests/rfc_compliance/ -v
uv run pytest tests/interop/ -v
uv run mypy src/
uv run ruff check src/
Real-Server Testing
AnyRFC is extensively tested against production servers:
- โ
WebSocket: echo.websocket.org, Binance WebSocket API, major services
- โ
IMAP: Live Gmail operations (read, flag, drafts, attachments)
- โ
SMTP: Gmail, SendGrid, major SMTP services
- โ
Production verified: Real-time email monitoring, 178KB+ file transfers
- โ
Compliance tested: Autobahn WebSocket suite, RFC test vectors
Protocol Roadmap
โ
Phase 1: WebSocket Foundation (Complete)
โ
Phase 2: Email Infrastructure (Complete)
๐ง Phase 3: OAuth & Modern Auth (In Progress)
๐ฎ Phase 4: Advanced Protocols
Performance
AnyRFC is built for high-performance workloads:
async def stress_test():
async with anyio.create_task_group() as tg:
for i in range(100):
tg.start_soon(websocket_worker, f"wss://api{i}.example.com")
async def large_mailbox():
async with IMAPClient("imap.example.com") as imap:
async for message in imap.fetch_messages("1:*", "BODY[]"):
await process_message(message)
Contributing
We welcome contributions! AnyRFC follows strict quality standards:
- RFC Compliance: All features must be RFC-compliant
- AnyIO Only: No asyncio imports allowed
- Type Safety: Full mypy compliance required
- Real-World Testing: Test against actual servers
- Security First: Secure by default
See CONTRIBUTING.md for detailed guidelines.
Security
- ๐ TLS Everywhere: Secure connections by default
- ๐ก๏ธ Input Validation: Strict RFC-compliant parsing
- ๐ Credential Safety: Never logs or stores credentials insecurely
- ๐ Security Audits: Regular dependency and code security reviews
Report security issues to: andrew@elgert.org
License
MIT License - see LICENSE for details.
Why "AnyRFC"?
Any + RFC = Protocol clients that work with any server implementing the RFC standard. Built on
AnyIO for structured concurrency.
Built by Andrew M. Elgert โข Documentation โข Issues โข PyPI