Stream Interface
The coreStream type powers all ACP connections:
readable: AReadableStreamfor receiving messages from the other sidewritable: AWritableStreamfor sending messages to the other side
The
AnyMessage type includes all JSON-RPC 2.0 message types: requests, responses, and notifications.Using ndJsonStream
The most common way to create a Stream is using thendJsonStream function, which handles newline-delimited JSON encoding:
Example: stdio-based Connection
How ndJsonStream Works
ThendJsonStream function creates a Stream that:
- Encodes outgoing messages: Serializes
AnyMessageobjects to JSON and appends a newline - Decodes incoming messages: Splits input by newlines and parses each line as JSON
- Handles errors: Logs parse errors without disrupting the stream
- Manages buffering: Accumulates partial lines until complete messages arrive
Implementation Details
The writable stream encodes messages:Creating Custom Streams
You can create custom Stream implementations for different transport mechanisms:WebSocket Stream
HTTP Stream (SSE + POST)
Stream Requirements
When creating custom streams, ensure they:Best Practices
- Use ndJsonStream for stdio: It’s battle-tested and handles edge cases
- Test custom streams: Verify message ordering and error handling
- Handle encoding properly: Ensure UTF-8 encoding for text-based transports
- Monitor stream closure: Listen for the connection’s
closedpromise
Related
- Connection Lifecycle - Managing connection state
- Error Handling - Handling stream errors