8.8 KiB
Stream-JSON Chaining in Claude Flow
🔁 Overview: Stream Chaining in Claude Code
Stream chaining in Claude Code is the technique of connecting multiple claude -p (non-interactive) processes using real-time JSON streams, allowing you to build modular, recursive, multi-agent pipelines.
Stream-JSON chaining enables Claude instances to pipe their outputs directly to other Claude instances, creating a seamless workflow where agents can build upon each other's work without intermediate storage.
🧱 How It Works
Core Claude Code Flags
Claude Code supports two key flags that enable stream chaining:
--output-format stream-json: emits newline-delimited JSON (NDJSON) with every token, turn, and tool interaction--input-format stream-json: accepts a stream of messages in NDJSON format, simulating a continuous conversation
By combining them:
claude -p --output-format stream-json "First task" \
| claude -p --input-format stream-json --output-format stream-json "Process results" \
| claude -p --input-format stream-json "Final report"
Each agent processes input, emits structured responses, and hands them off to the next agent in the chain.
Automatic Chaining in Claude Flow
When tasks have dependencies and stream-json output format is enabled, Claude Flow automatically:
- Detects task dependencies from workflow definitions
- Captures the stdout stream from the dependency task
- Pipes it directly to stdin of the dependent task
- Adds
--input-format stream-jsonflag to the receiving agent - Maintains the stream connection throughout execution
🔄 What You Can Do With Stream Chaining
- Subagent orchestration: planner → executor → reviewer
- Recursive pipelines: refinement loops, ablation agents, iterative optimization
- Live feedback systems: feed Claude output into a scoring or mutation agent
- Task decomposition: outer loop breaks work into subtasks, inner loop completes each
- Multi-stage analysis: data analysis → feature engineering → model training → validation
- Complex workflows: research → design → implementation → testing → documentation
🧠 Key Features
Structured Message Types
Stream-JSON format includes structured message types:
init: Session initializationmessage: Assistant/user messagestool_use: Tool invocations with parameterstool_result: Tool execution resultsresult: Final task completion status
Advanced Control Options
- Supports
--sessionfor session management --max-turnsfor granular conversation control- Works seamlessly with shell scripts,
jq, and Python SDKs - Can simulate multi-turn conversation without REPL
- Preserves full context including reasoning and tool usage
Example Stream-JSON Output
{"type":"init","session_id":"abc123","timestamp":"2024-01-01T00:00:00Z"}
{"type":"message","role":"assistant","content":[{"type":"text","text":"Analyzing data..."}]}
{"type":"tool_use","name":"Bash","input":{"command":"ls -la"}}
{"type":"tool_result","output":"total 64\ndrwxr-xr-x 10 user staff 320 Jan 1 00:00 ."}
{"type":"result","status":"success","duration_ms":1234}
Enabling Stream Chaining
Default Behavior
Stream chaining is enabled by default when using:
- Non-interactive mode (
--non-interactiveor default for mle-star) - Stream-json output format (
--output-format stream-json) - Tasks with dependencies
Commands
# MLE-STAR with automatic chaining
./claude-flow automation mle-star --dataset data.csv --target label --claude --output-format stream-json
# Custom workflow with chaining
./claude-flow automation run-workflow workflow.json --claude --non-interactive --output-format stream-json
# Disable chaining (agents run independently)
./claude-flow automation mle-star --dataset data.csv --target label --claude --output-format stream-json --no-chaining
Benefits
- Context Preservation: Full conversation history flows between agents
- Efficiency: No intermediate file I/O required
- Real-time Processing: Streaming output enables immediate processing
- Memory Efficiency: No need to store large intermediate results
Implementation Details
Task Dependencies
Tasks must declare dependencies to enable chaining:
{
"tasks": [
{
"id": "task1",
"name": "Analyze Data",
"assignTo": "agent1"
},
{
"id": "task2",
"name": "Process Results",
"assignTo": "agent2",
"depends": ["task1"] // This enables chaining from task1
}
]
}
Agent Prompts
When chaining is enabled, agents should be aware they may receive input:
{
"claudePrompt": "You are receiving analysis results from the previous agent via stream-json. Process these insights and continue the chain..."
}
Console Output
Look for these indicators:
🔗 Enabling stream chaining from task1 to task2🔗 Chaining: Piping output from previous agent to Agent Name
Manual Chaining
You can also manually chain Claude instances:
# Traditional piping
claude --print --output-format stream-json "Task 1" | \
claude --print --input-format stream-json --output-format stream-json "Task 2" | \
claude --print --input-format stream-json "Task 3"
⚠️ Limitations
- Non-interactive only: Doesn't work with interactive mode (
claudewithout-p) - Session management: Must manage session IDs and termination guards externally
- JSON compliance: Requires clean JSON compliance—poor error handling if malformed
- Single dependency: Currently chains from the last dependency if multiple exist
- Linear flow: No branching or conditional chaining yet
🚀 Advanced Examples
Recursive Refinement Pipeline
# Initial generation
echo "Generate a Python function to calculate fibonacci" | \
claude -p --output-format stream-json | \
# Code review and improvement
claude -p --input-format stream-json --output-format stream-json \
"Review this code and suggest improvements" | \
# Apply improvements
claude -p --input-format stream-json \
"Apply the suggested improvements and finalize the code"
Multi-Agent Data Pipeline
# Data analyst
claude -p --output-format stream-json \
"Analyze the sales data in data/sales.csv" | \
# Feature engineer
claude -p --input-format stream-json --output-format stream-json \
"Based on the analysis, create feature engineering code" | \
# Model builder
claude -p --input-format stream-json --output-format stream-json \
"Build a predictive model using the engineered features" | \
# Report generator
claude -p --input-format stream-json \
"Generate a comprehensive report of the entire analysis"
Stream Processing with jq
# Extract only tool uses from the stream
claude -p --output-format stream-json "Analyze system performance" | \
jq -c 'select(.type == "tool_use")' | \
claude -p --input-format stream-json \
"Summarize all the commands that were executed"
🛠️ Implementation Details
Stream Format Specification
Each line in the stream is a complete JSON object (NDJSON format):
interface StreamMessage {
type: 'init' | 'message' | 'tool_use' | 'tool_result' | 'result';
timestamp?: string;
session_id?: string;
role?: 'assistant' | 'user';
content?: Array<{
type: 'text' | 'tool_use';
text?: string;
name?: string;
input?: any;
}>;
output?: string;
status?: 'success' | 'error';
duration_ms?: number;
}
Process Spawning
Claude Flow spawns processes with specific stdio configurations:
const claudeProcess = spawn('claude', [
'-p',
'--output-format', 'stream-json',
'--input-format', 'stream-json', // Added for dependent tasks
prompt
], {
stdio: [inputStream ? 'pipe' : 'inherit', 'pipe', 'pipe']
});
// Pipe input stream if chaining
if (inputStream && claudeProcess.stdin) {
inputStream.pipe(claudeProcess.stdin);
}
🎯 Best Practices
- Design for streaming: Write prompts that acknowledge potential input streams
- Handle errors gracefully: Include error handling in your pipeline
- Use session IDs: Track sessions across chained agents
- Monitor performance: Stream chaining reduces latency but increases complexity
- Test incrementally: Build chains step by step, testing each link
💡 Key Insight
Stream chaining turns Claude from a stateless prompt executor into a programmable agent pipeline. It's how you move from chat to computation, enabling complex multi-agent workflows that maintain context and build upon each other's work in real-time.
Future Enhancements
- Support for multiple input streams (merge/join operations)
- Conditional chaining based on output content
- Stream filtering and transformation middleware
- Parallel stream processing with fan-out/fan-in patterns
- Built-in retry and error recovery mechanisms
- Stream replay and debugging tools