Labsco
luismichio logo

Context-Pipe

โ˜… 2

from luismichio

A high-performance, language-agnostic orchestration layer that brings the Unix Philosophy to the AI context window

๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅโœ“ VerifiedFreeAdvanced setup

โ›“๏ธ Context-Pipe

The Universal Standard for Context Engineering.

context-pipe is a high-performance orchestration layer directly inspired by Unix terminal piping โ€” the same philosophy that made cmd1 | cmd2 | cmd3 the most durable composition primitive in computing. Just as the terminal chains processes through stdin/stdout byte streams, Context-Pipe chains AI tool calls through context streams: each node does one thing, passes its output to the next, and the LLM only sees the final, refined signal.

This is not a metaphor โ€” it is a literal extension. Context-Pipe supports both MCP piping (chaining MCP tool calls through the orchestrator) and terminal piping (any binary, shell command, or script that reads stdin and writes stdout is a valid node). The two modes compose freely in a single pipe definition. And through the mcp-pipe CLI, it extends the terminal itself: the mcp-pipe tool subcommand makes any MCP server โ€” context-mode, serena, GitHub, Firecrawl, or any server registered in pipes.json โ€” directly pipeable from the shell, loading on demand, with no wrapper scripts and no IDE required:

cat error.log | mcp-pipe tool semantic-sift sift_logs | rg "CRITICAL"
curl -s https://example.com | mcp-pipe tool firecrawl scrape | mcp-pipe run semantic-refinery

Today, mcp-pipe run <pipe> already gives the terminal first-class access to any named pipe defined in pipes.json, composing terminal binaries through the same orchestrator used by the IDE.


๐Ÿš€ The Vision

The AI agent has a fundamental infrastructure problem: every tool call returns raw, unfiltered output directly into the context window. Logs arrive with timestamps. Search results arrive with boilerplate. Agent A's 40KB analysis gets passed verbatim to Agent B. The context window fills. Signal drowns in noise. The LLM degrades.

context-pipe solves this at the infrastructure layer โ€” before the LLM sees anything.

In the Studio of Two philosophy, we build Systems, not Patches. A patch would be a custom filter per tool. A system is a universal protocol: any tool that reads stdin and writes stdout becomes a node. Any sequence of nodes becomes a pipe. Any pipe is named, versioned, audited, and reusable across every project and every agent framework.

The result is a context supply chain: data enters raw, passes through a sequence of refineries (normalize โ†’ filter โ†’ compress โ†’ distil), and arrives at the LLM as dense, high-signal content. Every byte saved is accounted for in the Context Balance Sheet. Every pipe run is traceable. Every A2A handoff is protected.

This is not a wrapper around semantic-sift. It is the orchestration layer that makes any refinery composable, observable, and production-grade. A node can be a binary, a shell command, a Python script, or a full MCP tool (Figma, GitHub, context-mode, or any server registered in pipes.json). If it reads stdin and writes stdout, it belongs in the pipe.

Example โ€” crawl the web, research it, save it, and ship it:

trigger: tool:web_search | tool:web_fetch
[URL]
    โ†’ firecrawl/scrape             # MCP node: fetch live page as clean text     ~18,400 tokens
    โ†’ markitdown                   # binary node: convert to structured Markdown     ~16,200 tokens
    โ†’ rg 'security|vulnerability'  # shell node: surface only relevant sections      ~3,100 tokens
    โ†’ prettier --parser markdown   # shell node: normalize formatting                ~3,050 tokens
    โ†’ semantic-sift-cli doc        # binary node: distil to high-signal summary        ~420 tokens
          โ†ณ tee โ†’ research.md      # T-pipe: save raw distilled copy to disk
    โ†’ security-auditor             # script node: project-specific logic               ~380 tokens
    โ†’ github/create_issue          # MCP node: open a tracked issue with findings
Context Balance Sheet (illustrative)
  in:  18,400 tokens  โ†’  out: 380 tokens  โ€”  97.9% saved  ยท  1.2s total

Every node is a real subprocess. The T-pipe saves a raw copy at any point without interrupting the chain. The LLM receives only what matters โ€” and every byte in, byte out, and millisecond of latency is recorded in the Context Balance Sheet automatically.


๐Ÿ› ๏ธ Core Components

1. The Context-Pipe Protocol (CPP)

A language-agnostic standard with one rule: a node reads stdin, transforms content, and writes to stdout. Any binary, shell command, Python script, or MCP tool that honours this contract is a valid node. The protocol is defined in doc/CONTEXT_PIPE_PROTOCOL.md and is deliberately simple โ€” no SDKs, no registration, no framework coupling.

2. The Orchestration Spine (orchestrator.py)

The execution engine that chains nodes into pipes. Runs each node as a real OS subprocess with shell=False enforced (no injection surface). Features: per-node timeout guard (PIPE_NODE_TIMEOUT_MS), T-Pipe stream splitting (save raw input to disk before a node processes it), and full trace accounting (input/output size + latency per node).

3. The Universal Switchboard (pipes.json + mappings)

Data-driven routing that resolves the optimal pipe automatically based on three trigger types: tool name (tool:regex), payload size (size:>N), and default fallback. Pipe definitions live in pipes.json (project-level) and optionally ~/.mcp-pipe.json (global, merged with local precedence). No code changes required to add, modify, or re-route pipes.

4. The MCP Surface (server.py + mcp-pipe CLI)

Eight MCP tools expose every capability to AI assistants directly: pipe_run, pipe_run_dynamic, pipe_read_file, pipe_analyze_file, pipe_list_shadow_tools, pipe_agent_handoff, get_pipe_stats, and pipe_onboard. The mcp-pipe CLI mirrors the same surface for terminal-first workflows โ€” no IDE required. Shadow Tool Discovery (pipe_list_shadow_tools) gives the agent a live capability manifest combining configured pipes and curated PATH tools (jq, rg, markitdown, pandocโ€ฆ).

5. Subconscious Interceptors (pipe_hook.py + onboarding.py)

IDE hooks that apply pipes transparently after every tool call โ€” without the agent needing to invoke pipe_run explicitly. Supported: Cursor (postToolUse), VS Code/GitHub (hooks), Claude Code/Qwen/Codex (PostToolUse), Windsurf and Cline (pre-read security gateway), OpenClaw (native plugin), and pi.dev (native TypeScript extension). For OpenCode, the AGENTS.md SOP mandate is the active strategy (see Known Limitations). pipe_onboard injects all hooks, slash commands (/pipe-run, /pipe-dynamic, /pipe-handoff, /pipe-stats), and the full agent SOP in one command.

6. The A2A Bridge (a2a.py)

pipe_agent_handoff() distils Agent A's output before it enters Agent B's context window. Framework-agnostic โ€” no monkey-patching. Works in CrewAI task callbacks, Google ADK transfer hooks, LangGraph edge functions, or any custom handoff point. Available as both a Python function and an MCP tool. Returns the original output unchanged on any error, so the agent chain is never interrupted.

7. The Native Rust Core (crates/cpipe)

cpipe is the high-performance Rust heart of the Context-Pipe ecosystem. It ports the full orchestration engine โ€” config merging, placeholder resolution, stream routing, and the self-aware bypass guard โ€” to a pre-compiled native binary with <2ms startup latency (500ร— faster than the Python runtime). It coexists with the Python server: MCP tools stay in Python (FastMCP), while the Rust binary is available as a Tauri sidecar, a standalone CLI (cpipe run, cpipe list, cpipe serve), or a Cargo library for direct embedding in Rust applications. See crates/cpipe/README.md for the full API.

8. The TypeScript/JavaScript Client (packages/cpipe-js)

@context-pipe/client is the browser-safe, sandboxed client-side port of the engine. It simulates Unix pipes entirely in memory, supports standard nodes (grep, replace), allows custom PWA node registration (RAG database lookups, CORS proxies), and fully integrates with AbortSignal for cancellation. See packages/cpipe-js/README.md for the full API and examples.


โœจ What Makes This Different

FeatureWhat it doesWhere
Unix pipe model for AIChain any stdin and stdout tool into a named pipe. Binary, shell, script, or MCP tool โ€” same contract.Advanced Node Types
MCP Node TypeCall any MCP tool (Figma, GitHub, context-mode) as a first-class pipe node โ€” no wrapper scripts.doc/MCP_NODE_SPEC.md
Compilation-free topologyRouting lives in pipes.json, not in node code. Reroute, branch, or swap a node by editing the map โ€” no code changes, no recompile, no redeploy of any node.doc/ARCHITECTURE.md
Protocol-first MCP compositionSwap any MCP server by changing a server key. No imports, no dependency declarations, no build cycle. Every MCP server speaks the same protocol โ€” the entire ecosystem is a drop-in capability layer.doc/ARCHITECTURE.md
Dynamic PipesAI agents construct and execute ad-hoc node lists at runtime via pipe_run_dynamic โ€” no pipes.json entry required.Dynamic Pipes
Shadow MCP RegistryKeep utility MCP servers invisible to the agent's tool list until needed. pipe_list_shadow_tools queries them on demand.Shadow MCP Registry
A2A Agent HandoffDistil Agent A's output before it enters Agent B's context window โ€” framework-agnostic, no monkey-patching.A2A Handoff
Version AwarenessProactive GitHub-backed update alerts in pipe_verify and pipe_onboard to ensure environment parity.Health Checks
Stream IntegrityHardened orchestration engine with non-UTF8 robustness (errors="replace") and null-safe reading.doc/ARCHITECTURE.md
T-Pipe Stream SplittingSave a raw copy of any node's input to disk before it is distilled โ€” for audit, debugging, and quality measurement.3. T-Pipe Nodes (Stream Splitting)
Adaptive Window PressureSignals remaining context headroom to every node; semantic-sift auto-adjusts --rate accordingly.Environment Variables
Global ConfigShare pipe definitions and MCP server registries across all projects โ€” local pipes.json always wins.doc/ARCHITECTURE.md
Shell Alias Injectionpipe_install_aliases writes mcp-pipe / cpipe into your shell profile โ€” terminal-ready without venv activation.Terminal Usage
Git Protectionpipe_onboard automatically updates .gitignore to protect internal artifacts from being committed.Auto-Onboard
Context Balance SheetEvery pipe run is accounted: chars in, chars out, latency per node, agent attribution, net ROI.Telemetry & ROI

๐Ÿง  The Architecture: Semantic Enums (Solving Schema Bloat)

In standard MCP setups, exposing multiple capabilities (PDF parsing, log searching, HTML cleaning) means exposing multiple tools. This causes Schema Bloat: the LLM's system prompt fills with thousands of tokens of complex tool instructions. For Small Language Models (SLMs), this pushes out chat history, overwhelms the context window, and leads to hallucinations.

context-pipe solves this through Semantic Enums. Instead of teaching the AI how to use complex command-line utilities, you expose a single tool: pipe_run(input, pipe_name). The pipe_name parameter is simply an Enum of your predefined pipelines (e.g., ["parse-and-clean-pdf", "extract-critical-errors"]).

This perfectly separates Intent from Execution:

  • The LLM provides the Intent: "I need the clean text of this PDF, so I'll call the parse-and-clean-pdf pipe."
  • pipes.json provides the Execution: [pandoc -> jq -> semantic-sift]

By using brief, concise pipe names, you achieve extreme prompt compression. The AI gets a menu of high-level "buttons to push" rather than reading an instruction manual for every utility on the host machine. Better yet, if you upgrade your backend tooling (e.g., swapping pandoc for markitdown), you never have to update the LLM's prompt. The AI still calls the same pipe; the engine behind it just gets faster.


๐Ÿ”ง Three Independent Axes of Change

A CPP pipeline separates concerns across three layers that evolve on completely independent cycles:

LayerWhat it isHow you change it
NodesWhat each step does โ€” a dumb stdin/stdout tool, unaware of the pipeline around itSwap the binary, script, or MCP tool
pipes.jsonThe topology โ€” how steps connect, branch, and routeEdit the map. No code change. No recompile. No redeploy.
MCP serversThe capability behind each tool callChange the server key. No imports, no dependency declarations, no build cycle.

Improving a node's quality does not change the topology. Restructuring the routing does not touch any node. Upgrading an MCP server improves every pipe that uses it automatically โ€” with no pipeline changes.

For MCP nodes specifically, this dissolves the traditional dependency model entirely. Every MCP server speaks the same protocol: JSON-RPC, tools/call, text response. The pipe does not depend on what implements the service โ€” it depends on what speaks the protocol. The entire MCP ecosystem is therefore the pipe's capability layer. Every current and future MCP server is already a valid drop-in replacement for any node that serves the same semantic purpose.

In a script, you depend on what you import. In a pipe, you depend on what speaks the protocol.

This separation also means routing is compilation-free. In a traditional script, safeguards and recovery logic are embedded in code โ€” changing how a workflow recovers requires changing, testing, and redeploying the script. In CPP, routing lives in pipes.json. A branch, a reroute, or a node swap is a configuration edit. The feedback loop between "what if I reroute this" and "let me observe what happens" collapses to near zero.


๐Ÿ“š Documentation

Detailed documentation is available in the doc/ directory.


๐Ÿค A2A (Agent-to-Agent) Handoff

When chaining agents, use pipe_agent_handoff to distil Agent A's output before it enters Agent B's context window. Works with any framework โ€” no monkey-patching required.

from context_pipe.a2a import pipe_agent_handoff

# In a CrewAI task callback, ADK transfer hook, or any custom handoff point:
agent_b_input = pipe_agent_handoff(
    agent_a_output,
    pipe_name="semantic-refinery",   # optional; auto-routes if omitted
    from_agent="researcher",
    to_agent="writer",
)

Also available as an MCP tool โ€” ask your AI assistant: "Run pipe_agent_handoff() to distil this agent output before passing it on."

Function signature:

def pipe_agent_handoff(
    output: str,
    pipe_name: str | None = None,   # explicit pipe; auto-routes if omitted
    from_agent: str | None = None,  # producing agent label (telemetry + routing)
    to_agent: str | None = None,    # consuming agent label (telemetry only)
    config_path: str = "pipes.json",
) -> str: ...

Always returns the original output unchanged on any error โ€” the agent chain is never interrupted.


๐Ÿ”— Advanced Node Types

Context-Pipe supports more than just simple binaries. You can chain standard OS tools and expert mandates.

1. Bash Nodes (Sandboxed)

Execute arbitrary shell commands as part of your pipe. By design, all commands are executed natively with shell=False to prevent injection vulnerabilities.

{ "cmd": "grep", "args": ["ERROR"] }

2. Script Nodes

Executes a project-specific script (Python/Shell) or a local instruction set. Resolved from .gemini/scripts/ (default).

{ "type": "script", "cmd": "security-auditor" }

3. T-Pipe Nodes (Stream Splitting)

Save a raw copy of the stream to disk before a node distils it โ€” without interrupting the chain. Useful for debugging pipe quality and auditing what was sifted out.

{
  "cmd": "semantic-sift-cli",
  "args": ["logs"],
  "tee": {
    "sink": "file",
    "path": "logs/{tool_name}_{iso_date}.log",
    "mode": "append"
  }
}

path supports {iso_date} (YYYY-MM-DD) and {tool_name} tokens. A tee failure never interrupts the main chain.

4. MCP Nodes

Call any MCP tool as a pipe node. No wrapper scripts โ€” the orchestrator spawns the MCP server, calls the tool, and passes the result downstream via stdout.

{
  "type": "mcp",
  "server": "figma",
  "tool": "get_file",
  "input_key": "file_id"
}

Server definitions live in a servers block in pipes.json or ~/.mcp-pipe.json. See doc/MCP_NODE_SPEC.md for the full spec.

5. Validator Nodes (Phase 11)

A validator runs a subprocess and routes on its exit code instead of flowing linearly. Use this to build self-healing pipelines that try to fix problems automatically before failing.

{
  "name": "self-healing-lint",
  "nodes": [
    {
      "cmd": "eslint",
      "args": ["--format", "compact", "src/"],
      "type": "validator",
      "id": "lint-check",
      "branches": {
        "0": "done",
        "1": "auto-fix",
        "default": "auto-fix"
      }
    }
  ],
  "branch_sequences": {
    "auto-fix": [
      { "cmd": "eslint", "args": ["--fix", "src/"] },
      { "cmd": "semantic-sift-cli", "args": ["logs"] }
    ],
    "done": [
      { "cmd": "semantic-sift-cli", "args": ["logs"] }
    ]
  }
}
  • Exit 0 โ†’ linting passed, jumps to done (distil the clean report).
  • Exit 1 โ†’ linting failed, jumps to auto-fix (run --fix, then distil).
  • "default" catches any other exit code (e.g. 2 for ESLint config errors).
  • The validator's stdout is forwarded as input to the target sequence.

6. Condition Keys (Phase 11)

Any node can be conditionally skipped without modifying the pipe definition:

{
  "cmd": "neural-summariser",
  "condition": "size:>8000"
}

The node only runs if the current input exceeds 8 000 bytes. Supported predicates:

PredicateExampleWhen the node runs
size:>Nsize:>10000Input length > N bytes
size:<Nsize:<500Input length < N bytes
artifact:exists:<path>artifact:exists:dist/app.jsFile exists on disk
artifact:missing:<path>artifact:missing:output/report.mdFile does NOT exist
contains:<string>contains:ERRORLeading 300 chars contain the substring

Unknown predicates fail-open (warn + run the node) to avoid silently blocking pipelines.

๐Ÿ”— The Ecosystem (Studio of Two)

Context-Pipe is a foundational member of the Studio of Two infrastructure. It is designed to work in high-fidelity harmony with:

  • Semantic-Sift: The intelligent refinery for agentic context. Sift is the flagship distillation engine for Context-Pipe, providing the mathematical and neural sifting nodes used in our standard templates.
  • std-context-lab: The official integration laboratory and test gauntlet. This repository serves as our isolated battle-testing ground where cross-repository capabilities, MCP server combinations, and terminal hook interactions are simulated and verified.
    • Isolated Scenarios: Runs isolated test cases mimicking real-world AI behaviors to reproduce and verify fixes without polluting core runtimes.
    • Empirical Evidence: Every resolved bug or feature is accompanied by a tracked execution log (EVIDENCE.md), serving as empirical proof of success.
    • Platform Parity Gate: Audits Python/Rust CLI parity and shell behaviors across Windows (PowerShell/CMD) and UNIX terminals before release.

๐Ÿงฉ Tool Synergies & Boundaries

Four tools often appear together in a Studio of Two stack. They are complementary, not overlapping โ€” each owns a distinct layer.

ToolLayerPrimary RoleRelationship
context-pipeOrchestrationRoutes content through named pipes; manages node execution, timeouts, T-pipe, telemetry, and A2A handoff.The switchboard. Calls all other tools as nodes when wired together.
semantic-siftDistillationHeuristic + neural compression of text. Removes noise (timestamps, boilerplate, repeated tokens) while preserving signal.Fully standalone CLI and MCP server. The flagship refinery node inside context-pipe pipes.
context-modeIn-session indexingBM25 full-text search over content indexed during the current agent session. Fast retrieval without a vector database.Fully standalone MCP server. Optionally wired as an mcp node to index or search within a pipe.
SerenaCode intelligenceLSP-backed symbol search, refactoring, and code navigation. Understands the AST โ€” not just text.Fully standalone MCP server. Optionally wired as an mcp node to feed precise code symbols into a pipe instead of raw file reads.

When to use which

Use context-pipe when you need to orchestrate: chain tools, apply pipes automatically on tool call, route by trigger, save T-pipe snapshots, account for ROI, or bridge agent handoffs.

Use semantic-sift when you need to compress: a large document, a log file, a search result, or any payload where noise-to-signal ratio is high. Runs standalone via CLI or MCP โ€” and as a node inside context-pipe pipes.

Use context-mode when you need to retrieve: you have already ingested content this session and want fast BM25 search over it. Works standalone as an MCP server in any IDE. Pair it with semantic-sift on both sides โ€” upstream to compress content before indexing (smaller index, faster search), and downstream to distil retrieved chunks before they hit the context window.

Use Serena when you need to navigate code: find a symbol, trace references, inspect types, or perform a refactor. Works standalone as an MCP server. Its structured, precise output is far better than a raw file read as input to any downstream tool โ€” including a sifting pipe.

Complementary setup โ€” reducing token usage

Each tool independently reduces token pressure. Together, the savings compound:

  • Serena returns only the symbol you asked for โ€” not the entire file.
  • semantic-sift compresses content before it enters context-mode (smaller index, faster search) and after retrieval (noise-free chunks into the context window).
  • context-mode returns only the relevant indexed chunks โ€” not the entire ingested corpus.
  • context-pipe ensures this sequence fires automatically and is accounted for โ€” no manual wiring per task.

The result: the agent works with a fraction of the raw token volume, every session, without changing how it thinks or what tools it calls.

Synergy example

[user query]
    โ†’ serena/find_symbol           # MCP node: precise code symbol โ€” not a raw file dump
    โ†’ context-mode/search          # MCP node: retrieve related session context
    โ†’ semantic-sift-cli semantic   # binary node: compress both into a dense summary
    โ†’ security-auditor             # script node: project-specific logic

All four tools in one pipe. Each doing exactly one job.


โš™๏ธ Environment Variables

VariableDefaultDescription
PIPE_CONFIG_PATHpipes.jsonAbsolute path to the project's pipes.json config file.
PIPE_NODE_TIMEOUT_MS30000Per-node execution timeout in milliseconds.
allow_shellfalseEnable arbitrary shell command nodes in dynamic pipes (pipe_run_dynamic MCP tool / run_dynamic_pipe() API). Requires the final node to be a semantic-sift terminal command to guarantee context safety.
PIPE_LOG_LEVEL(none)Default pipeline logging level (compact or verbose). Enables logging for all pipes if set.
PIPE_LOG_PREFIX[PIPE]Default text prepended to pipeline execution logs on stderr.

โš–๏ธ Licensing

context-pipe is licensed under the Apache License 2.0. It is an "Open Source, Closed Contribution" project maintained by the Studio of Two to ensure architectural integrity.


Building High-Fidelity Infrastructure for the Intelligence Age.