CDX AGENT DOCK DEVELOPER API REFERENCE

CDX Agent Dock Developer Documentation

Complete API reference for LangChain, CrewAI, and AutoGen cross-framework adapters, slimmer / mcp_proxy / route runtime optimization options, Customer-Owned Standard Storage (JSON / SQLite3 BYOS) CRUD for explicit entity masking (CDXCloak) & tool routing (CDXArbiterEngine), Docker Sidecar v2.1, and Open-Core Security Architecture.

SDK & Sidecar Version: v2.1.0 GA (Python SDK & Docker Sidecar) Stable

1. Installation & Quickstart (Python SDK v2.1.0 & Docker Sidecar)

cdx-dock v2.1.0 supports both in-process Python SDK (pip) and language-agnostic reverse-proxy container (Docker Sidecar) deployments.

1.1A Official PyPI Package Installation (Python)

# [Standard Install] 4 Core Engines (Multilingual Arbiter · CDX-Tab · Slimmer · Adapters) + TokenPack-10K pip install cdx-dock # [With VaultPack-2K Encryption] Includes cryptography for local AES-256-GCM + AAD vaulting pip install "cdx-dock[vault]" # [Emergency 1-Flag Safe Pass-Through] Bypass all optimizations instantly without code changes export CDX_BYPASS=1

1.1B Official Docker Hub Container Installation (Node.js / Go / Java / K8s)

# Pull Docker Sidecar v2.1.0 image (OpenAI-compatible local proxy) docker pull cdxno1/cdx-a2a-sidecar:2.1.0

1.2 System Requirements & Compatibility Matrix

Requires Python 3.10+ · numpy>=1.24.0 or a standard Docker runtime environment. Operates with Zero Outbound Network Dependencies (100% Offline Air-Gap) and zero external database servers.

ComponentSupported SpecificationNotes
Python SDKPython 3.10+ (numpy>=1.24.0)Compatible with Linux, macOS, and Windows (Zero Outbound Network Dependencies · 100% Offline Air-Gap)
Docker Sidecarcdxno1/cdx-a2a-sidecar:2.1.0 (linux/amd64, arm64)OpenAI-compatible HTTP proxy for Node.js, Go, Java, Rust, and K8s
Agent FrameworksLangChain, CrewAI, AutoGen, Hermes AgentAutomatic protocol detection for invoke(), run(), GroupChat, and SKILL.md (agentskills.io)
BYOS Storage.json / .db (.sqlite3)Customer-owned local volumes & Docker volume mounts (-v /data)
Package ArchitectureOpen-Core (.py + .pyd/.so)Inspectable open-source adapter layer + pre-compiled native execution core

1.3 30-Second Quickstart

from cdx_dock import as_crewai_tool from crewai import Agent # [1] Reference an existing LangChain agent my_langchain_agent = ... # Existing AgentExecutor instance # [2] 1-Line conversion into a CrewAI tool (slimmer=True cuts payload tokens by 48.2%) sql_tool = as_crewai_tool(my_langchain_agent, name="db_searcher", slimmer=True) # [3] Assign to a CrewAI agent analyst = Agent( role="Senior Data Analyst", goal="Quarterly revenue analysis", tools=[sql_tool] )

1.4 License Key (CDX_LICENSE_KEY) Setup & Offline Verification

During the 30-Day Free Sandbox (150,000 monthly steps · All 7 engines unlocked), no license key is required—simply install and run. When a monthly step quota or 30-day Sandbox limit is reached, the SDK and Sidecar never halt customer pipelines; they automatically enter Zero-Downtime Safe Pass-Through Mode and emit a runtime/header/console upgrade notice. Upon subscribing to a paid plan (Starter through Enterprise), configure your cryptographically signed offline Ed25519 key (CDX2.<payload>.<sig>) below (unsigned or tampered keys raise CDXLicenseError / HTTP 401):

# [Zero-Key 30-Day Sandbox] No key required — inspect active Sandbox status python -m cdx_dock --status # [Paid Plan Method A] OS / Container Environment Variable & CLI Offline Verification export CDX_LICENSE_KEY="CDX2.<payload>.<ed25519_sig>" python -m cdx_dock --verify --key "$CDX_LICENSE_KEY" # [Paid Plan Method B] Programmatic Configuration & Verification in Python Application Startup import cdx_dock cdx_dock.set_license_key("CDX2.<payload>.<ed25519_sig>") # Inspect active license status, plan quota, and node ID (100% offline check) info = cdx_dock.get_license_info() print(info["tier"], info["status"], info["current_machine_id"])

2. Cross-Framework Adapter Specifications

Core adapter functions that normalize invocation signatures and input/output contracts across heterogeneous agent frameworks, along with an architectural comparison of agent design paradigms.

2.0 Agent Architecture Comparison: Prompt-Only Agents vs. 4 Enterprise Frameworks

While a Prompt-Only Agent (assigning a system prompt persona) can hold conversations, it cannot query internal databases, execute code, enforce step-by-step workflows, or coordinate multi-agent verification. Enterprise teams rely on specialized Agent Frameworks, and cdx-dock bridges and optimizes all of them in a single line:

Paradigm / FrameworkCore Operating MetaphorPrimary StrengthStandalone Bottleneckcdx-dock Integration Benefit
Prompt-Only Agent
(Custom GPTs, etc.)
Verbal-Only Receptionist
System prompt persona without orchestration code
Built in 1 minute without coding Cannot execute internal tools or enforce deterministic workflow steps Seamless upgrade path to enterprise frameworks via unified adapters
LangChain / LangGraph Conveyor-Belt Factory (DAG)
Strict step-by-step graph (Step A → Step B → Conditional Branch)
Fine-grained control for financial & enterprise backend pipelines Cumulative JSON state across chain steps inflates token consumption as_langchain_tool / CDXLangChainDock compresses inter-step payloads by 48.2%
CrewAI Corporate Org-Chart & Role-Play Team
Assigns Role, Goal, and Backstory to collaborating specialist agents
Intuitive task delegation for research, planning, and report generation Verbose inter-agent handoffs and incompatibility with non-CrewAI tools as_crewai_tool / CDXCrewAIDock adapts external agents in 1 line with payload slimming
Microsoft AutoGen Multi-Agent Debate Room (GroupChat)
Coder, Critic, and Executor converse in a loop until consensus
High accuracy for code generation, debugging, and complex reasoning Multi-turn conversation history grows exponentially across turns as_autogen_agent / CDXAutoGenDock trims per-turn message overhead automatically
Nous Hermes Agent
(agentskills.io)
Terminal Operator with Procedural Notebook (SKILL.md)
Executes CLI/SSH tasks and records reusable Markdown skills
Autonomous DevOps operations and reusable procedural skill libraries Injecting dozens of SKILL.md files overflows context and risks leaking secrets CDXHermesDock provides <10ms Top-K skill routing + SKILL.md slimming + secret pinning

2.1 as_crewai_tool()

Converts a LangChain agent, AutoGen agent, or standard Python callable into a CrewAI-compatible tool object.

def as_crewai_tool( agent: Any, name: Optional[str] = None, description: Optional[str] = None, slimmer: bool = False, mcp_proxy: bool = False, route: bool = False ) -> CrewAIToolWrapper
ParameterTypeDefaultDescription
agentAnyRequiredSource agent instance or callable object to adapt
namestrNoneCrewAI tool identifier (auto-extracted from metadata if omitted)
descriptionstrNoneFunctional description referenced by the agent during tool selection
slimmerboolFalseWhen True, applies Mode B structural compression (-48.2% payload tokens)
mcp_proxyboolFalseWhen True, optimizes tool schema metadata (-36%) and preserves prompt cache alignment
routeboolFalseWhen True, enables <10ms in-memory tool routing (-90% schema context overhead)

2.2 as_langchain_tool()

Converts a CrewAI or AutoGen agent into a LangChain BaseTool compatible instance.

from cdx_dock import as_langchain_tool lc_tool = as_langchain_tool( crew_researcher, name="market_researcher", description="Specialized agent tool for market trend and competitor analysis", slimmer=True )

2.3 as_autogen_agent()

Converts a LangChain or CrewAI agent into an AutoGen ConversableAgent for participation in GroupChat sessions.

from cdx_dock import as_autogen_agent from autogen import GroupChat, GroupChatManager autogen_member = as_autogen_agent( my_langchain_agent, name="financial_analyst", slimmer=True ) groupchat = GroupChat(agents=[autogen_member, ...], messages=[]) manager = GroupChatManager(groupchat=groupchat)

2.4 bridge(source, target)

Creates a 1:1 execution pipeline that pipes the output of an upstream agent directly into a downstream agent.

from cdx_dock import bridge # Direct pipeline: Agent A (Researcher) ➔ Agent B (Report Writer) pipeline = bridge(crewai_researcher, langchain_writer, slimmer=True) final_report = pipeline("Q3 2026 Enterprise Cloud Infrastructure Outlook")

2.5 adapt(agent, to='...')

Unified polymorphic interface that returns the appropriate adapter based on the target framework identifier string.

from cdx_dock import adapt tool_for_crew = adapt(agent, to="crewai", slimmer=True) tool_for_lc = adapt(agent, to="langchain", slimmer=True, mcp_proxy=True) agent_for_ag = adapt(agent, to="autogen")

2.6 CDXHermesDock (Nous Hermes Agent & agentskills.io Adapter)

Dedicated adapter for Nous Research's Hermes Agent and agentskills.io (SKILL.md procedural Markdown files), combining ① lossless SKILL.md Markdown compression, ② <10ms in-memory Top-K skill routing, ③ CDXCloak explicit secret pinning, and ④ 1-line export to CrewAI, LangChain, and AutoGen.

from cdx_dock import CDXHermesDock # 1) Wrap a Hermes Agent instance (or callable) with CDXHermesDock hermes_dock = CDXHermesDock( hermes_agent, name="devops_hermes_operator", slimmer=True, # Compress SKILL.md and input/output payloads cloak=True, # Locally mask pinned secrets and restore on output route=True, # Select Top-K relevant SKILL.md procedures in <10ms top_k_skills=2 ) # 2) Execute with SKILL.md compression + explicit secret pinning + Top-K skill routing result = hermes_dock.invoke( "Verify production DB migration and check settlement account status", skills=my_skills_catalog, skill_md=raw_skill_markdown, pin_secrets={"SETTLEMENT_ACC": "ACC-9981-7721-0042", "DB_HOST": "10.240.18.99"} ) print(result["output"]) # Final response (secrets restored locally) print(result["selected_skills"]) # Top-K skills routed in <10ms # 3) Export Hermes Agent as a CrewAI / LangChain / AutoGen tool in 1 line crew_tool = hermes_dock.to_crewai_tool() lc_tool = hermes_dock.to_langchain_tool()

3. Runtime Context Optimization Options

All CDX Agent Dock adapters operate in transparent pass-through mode by default. Enable runtime optimizations selectively via boolean flags.

3.1 slimmer=True — Mode A ↔ Mode B Bijective Codec (48.2% Inter-Agent Payload Compression)

DockSlimmer switches payloads reversibly based on who reads the data (Machine DB/APIs vs. Cloud LLMs). Outbound LLM prompts are compressed into Mode B (-48.2% tokens) by stripping JSON punctuation bloat, while enterprise DB writes and REST API responses reconstruct Mode A (Standard JSON) with 1:1 lossless roundtrip fidelity.

DimensionMode A (Standard JSON — DB & APIs)Mode B (Structured Compact — Cloud LLMs)
Syntax Structure Repeats braces { }, brackets [ ], double quotes " ", and commas , Strips punctuation bloat using indentation and colons (:)
Token & Latency 142 Tokens (baseline) 74 Tokens (-48.2% saved) · P50 ~0.18ms · consistent LLM accuracy (internal benchmark)
Primary Role & API Enterprise DB storage, REST API responses, slimmer.to_mode_a() reconstruction Inter-agent LLM messaging across LangChain, CrewAI, AutoGen, and Hermes (slimmer.to_mode_b())
from cdx_dock import as_crewai_tool, DockSlimmer # 1) Enable automatic Mode B compression on any adapter sql_tool = as_crewai_tool(my_agent, slimmer=True) # 2) Direct 1:1 reversible roundtrip (Mode A Standard JSON -> Mode B -> Mode A) slimmer = DockSlimmer() sample_payload = {"tx_id": "TX_9942", "verified": True, "tags": ["finance", "kyc"]} mode_b_text = slimmer.to_mode_b(sample_payload) restored_json = slimmer.to_mode_a(mode_b_text) # Restores exact Python dict / JSON

3.2 mcp_proxy=True (36% Tool Schema Reduction & Prompt Cache Alignment)

Prunes non-essential JSON Schema metadata fields and normalizes static prefixes to maintain high KV-Cache hit rates across OpenAI, Anthropic, and Google models.

# Optimize tool schema metadata and preserve prompt cache hits sql_tool = as_crewai_tool(my_agent, mcp_proxy=True)

3.3 route=True (<10ms In-Memory Top-K Tool Routing)

Evaluates query intent in local memory in 0.25ms–10ms without external LLM or embedding API calls, selecting only the most relevant tools for the turn.

# 1) Enable directly on the adapter sql_tool = as_crewai_tool(my_agent, route=True) # 2) Standalone 1-line tool routing function from cdx_dock import route_tool decision = route_tool(my_tools, "Retrieve Q3 corporate tax settlement records") print(decision["tool_name"]) # 'query_corporate_tax' (0.3ms latency)

3.4 Combined Production Configuration

# Enable payload compression, schema normalization, and in-memory routing concurrently sql_tool = as_crewai_tool(my_agent, slimmer=True, mcp_proxy=True, route=True)

3.5 CDX-CoT-Guard — Reasoning Loop Breaker (<think>) & CDX Proprietary KV-Cache Damper

cot_middleware.py breaks runaway repetition loops inside <think>...</think> reasoning traces of modern CoT models (GPT-6 Astra, Claude Sonnet 5.5 Thinking, Gemini 4 Carbon, DeepSeek-R1, QwQ), saving 40–60%+ of wasted reasoning tokens while providing an adaptive reasoning depth clutch gate and CDX proprietary KV-Cache memory optimization (~75% memory reduction).

Class / APIDeployment ModeCore Capability
CDXCoTProxyMiddleware API Proxy (OpenAI / vLLM / Ollama) prepare_request() applies premature </think> exit clutch (depth_control) and CDXCloak pinning · inspect_and_guard_stream() breaks streaming CoT loops early
CDXCoTMiddleware On-Premise Context Manager with CDXCoTMiddleware(model): performs real-time reasoning stagnation detection, adaptive depth control, and step_kv_cache() CDX proprietary KV-Cache memory optimization
from cdx_dock import CDXCoTProxyMiddleware, CDXCoTMiddleware # [Model 1] API Proxy Mode (OpenAI / vLLM / Ollama Gateways) cot_proxy = CDXCoTProxyMiddleware( min_think_steps=6, enable_slimmer=True, enable_cloak=True ) req = cot_proxy.prepare_request( {"model": "deepseek-r1", "messages": [{"role": "user", "content": "Audit Q3"}]}, step_idx=2, pinned_secrets={"SETTLEMENT_ACC": "ACC-9981-7721-0042"} ) guard_res = cot_proxy.inspect_and_guard_stream(reasoning_chunks, lang="en") print(guard_res["loop_broken"], guard_res["token_savings_pct"]) # [Model 2] On-Premise Context Manager & CDX Proprietary KV-Cache Damper with CDXCoTMiddleware(local_model, min_think_steps=6) as cot_guard: damped_kv, kv_meta = cot_guard.step_kv_cache(kv_tensor) print(kv_meta["memory_savings_pct"]) # ~74.8% KV-Cache memory reduction

3.6 CDX-TokenPack-10K — Zero-Vector-DB Local Folder (pack_dir) 8-Language 10,000-Token Shared Memory

token_pack.py synchronizes up to 10,000 tokens of high-density long-term memory across heterogeneous frameworks (CDXLangChainDock, CDXCrewAIDock, CDXAutoGenDock, CDXHermesDock) via a single local SQLite storage file (cdx_token_pack_10k.db) inside a user-specified folder (pack_dir)—requiring zero external Vector DB servers. Routine logs are automatically evicted above 10,000 tokens while critical specs, IDs, and numerical facts are permanently retained, with <1.0ms Top-K recall across 8 global languages (KO·EN·JA·ZH·ES·DE·FR·RU).

from cdx_dock import CDXTokenPack10K, CDXLangChainDock, CDXCrewAIDock # 1) Initialize a 10,000-token importance-aware memory pack in a user-specified folder pack = CDXTokenPack10K(pack_dir="./shared_agent_memory") # 2) Ingest critical facts across 8 global languages (KO·EN·JA·ZH·ES·DE·FR·RU) pack.ingest("[CRITICAL SPEC] Production DB connection timeout=1500ms, max_pool_size=64.") pack.ingest("[CRITICAL SPEC] Settlement gateway max_retries=3, timeout=800ms.") # 3) <1.0ms Top-K recall and automatic prompt augmentation recalled = pack.recall("What is the production DB connection timeout?", top_k=2) augmented_prompt, stats = pack.augment_prompt( "Verify current DB connection timeout compliance", top_k=2 ) # 4) Share the same 10K memory folder across heterogeneous agent frameworks in real time lc_dock = CDXLangChainDock(langchain_agent, pack_dir="./shared_agent_memory") crew_dock = CDXCrewAIDock(crewai_agent, pack_dir="./shared_agent_memory")

3.7 [v2.1.0] CDX-VaultPack-2K (10K ∥ 2K Parallel Encrypted Vault) & CDX-Tab Columnar Compression

CDXDualTokenPack physically isolates daily conversation context (10K ContextPack) from permanent sensitive slots (2K VaultPack) so payment cards, addresses, and API keys are never evicted during long sessions. All ciphertext and master keys stay 100% on the customer's local host (Zero-Knowledge) with AES-256-GCM + AAD tamper detection, PCI-DSS transient CVV/CVC stripping, and 1-Bit RBAC least-privilege decryption. (Unlocked in 30-Day Sandbox Trial and Growth $1,490+ plans; Starter tier falls back gracefully via Safe Pass-Through. Provided as a Defense-in-Depth local guardrail—customers retain sole responsibility for master key management and regulatory compliance.)
In addition, DockSlimmer.to_mode_b() automatically applies lossless columnar dictionary encoding (CDXTAB1:) to uniform tabular JSON arrays (4+ rows), reducing payload size by 54–66% with exact 100% roundtrip restoration via to_mode_a().

from cdx_dock import ( CDXDualTokenPack, DockSlimmer, ROLE_CLOUD_PLANNER, ROLE_PAYMENT_EXECUTOR, ) # 1) Initialize Parallel 10K ContextPack || 2K Local AES-256-GCM VaultPack (Zero-Knowledge) dual = CDXDualTokenPack(pack_dir="./agent_dual_pack") turn = dual.ingest_turn("Card 4532-1122-3344-5566 CVV=831, email ceo@acme.io") # -> turn["safe_text"]: card replaced with [[VPACK:CARD:...]], CVV stripped and never stored # 2) 1-Bit RBAC: Cloud Planner (0x00) always denied; consented local Payment Executor decrypts card_handle = [h for h in turn["vault"]["handles"] if ":CARD:" in h][0] dual.resolve_for_tool(card_handle, role_mask=ROLE_CLOUD_PLANNER, user_consent=True) # authorized=False dual.resolve_for_tool(card_handle, role_mask=ROLE_PAYMENT_EXECUTOR, user_consent=True) # authorized=True # 3) Automatic CDX-Tab columnar lossless compression for uniform JSON tables slimmer = DockSlimmer() encoded = slimmer.to_mode_b([{"id": i, "status": "COMPLETED", "region": "us-east-1"} for i in range(25)]) restored = slimmer.to_mode_a(encoded) # 100% lossless roundtrip

4. BYOS Data Governance: Explicit Entity Masking (CDXCloak) & Router CRUD

All entity masking dictionaries and tool catalogs are stored strictly on customer-owned storage (BYOS) using universal Standard UTF-8 JSON and SQLite3 relational tables.

4.1 Explicit Entity Masking (CDXCloak) — Zero Unintended Text Mutation Pinning

Enforces strict_pin_mode=True by default so ordinary dates, quantities, and public identifiers are never misidentified by generic pattern scanners. Masks only explicitly pinned entities and restores them locally upon response completion.

from cdx_dock import CDXCloak # 1) Bind to Customer-Owned SQLite3 (.db) or JSON (.json) vault (strict_pin_mode=True) cloak = CDXCloak(storage_path="./enterprise_vault.db") # 2) [CREATE / UPDATE] Explicitly pin sensitive entities in local SQLite vault token = cloak.pin_secret("ACC-9981-7721-0042", label="MAIN_SETTLEMENT_ACC") cloak.pin_secret("$145,000", label="EXEC_BUDGET") # 3) [READ] List all registered entries or inspect a single entry all_secrets = cloak.list_explicit_secrets() entry = cloak.get_explicit_secret("MAIN_SETTLEMENT_ACC") # 4) [MASK & UNMASK] Dates (2026-10-17) stay intact; only pinned secrets are masked masked, session = cloak.mask_text( "On 2026-10-17, approve $145,000 transfer to ACC-9981-7721-0042" ) restored = cloak.unmask_text(masked, session) # 5) [DELETE] Remove specific entry from memory and disk cloak.remove_explicit_secret("EXEC_BUDGET")

4.1.1 Architectural Principle: Why Explicit Pinning (pin_secret) Works Across All Agent Frameworks with Minimal False Positives (Internal Benchmark)

Traditional pattern or heuristic AI scanners frequently corrupt agent reasoning by over-masking ordinary dates (2026-10-17) and quantities, or under-masking internal codenames (Project Titan). CDXCloak achieves consistent deterministic accuracy (internal benchmark) across LangChain, CrewAI, AutoGen, and Hermes using strict_pin_mode=True and explicit pinning (pin_secret) based on two structural invariants:

Structural PrincipleTechnical MechanismDeveloper & Security Advantage
① Framework Prompt Template & Variable Binding Law Every enterprise agent framework constructs prompts via Prompt Templates bound to Python variables (e.g., "Check account {account_num} for customer {customer_name}") rather than hardcoded strings. Because developers already hold the exact Python variables fetched from internal DBs/APIs (customer_name, account_num, db_key), they can pin those variables directly in 1 line (cloak.pin_secret("ACCOUNT", account_num)) without pattern guesswork.
② Final Outbound Gateway String Serialization Law Regardless of whether an agent orchestrates via chains (LangChain), role-play (CrewAI), group debate (AutoGen), or terminal skills (Hermes), every framework serializes the final outbound LLM payload into a plain text string/JSON at the invocation boundary (invoke / run). cdx-dock intercepts this final gateway to replace pinned variable values with deterministic tokens (<CDX_PIN_ACCOUNT_1>) before outbound transmission, and immediately restores (unmask_text) the original values in local memory upon receiving the LLM response.
# [Universal Pattern] Framework Template Variables + CDXCloak Explicit Pinning customer_name = db.get_vip_customer(user_id) # e.g., "VP Chul-soo Kim" settlement_acc = db.get_account_number(user_id) # e.g., "ACC-9981-7721-0042" # Directly pin sensitive variables held by the app (zero regex false positives) cloak.pin_secret("VIP_CUSTOMER", customer_name) cloak.pin_secret("SETTLEMENT_ACC", settlement_acc) # Masked at outbound gateway across LangChain / CrewAI / AutoGen / Hermes prompt = ( f"Summarize transactions for {customer_name} " f"on account {settlement_acc} as of 2026-10-17." ) masked_prompt, session = cloak.mask_text(prompt) # ➔ Outbound LLM Payload: # "Summarize transactions for [[VAULT_PIN_VIP_CUSTOMER_F07F]] # on account [[VAULT_PIN_SETTLEMENT_ACC_124F]] as of 2026-10-17."

4.2 In-Memory Tool Router (CDXArbiterEngine) — Standard Catalog CRUD

Stores clean relational metadata (name, description, required_params, tags) on disk with zero proprietary binary blobs, allowing direct management via DBeaver or SQLite CLI.

from cdx_dock import create_arbiter # 1) Bind to Customer-Owned Standard SQLite3 (.db) or JSON (.json) catalog arbiter = create_arbiter(storage_path="./enterprise_tools.db") # 2) [CREATE / UPDATE] Register tool metadata (persisted to cdx_arbiter_tools table) arbiter.add_tool( name="execute_sql_warehouse", description="Execute read-only SQL queries on enterprise revenue warehouse.", required_params=["query"], tags=["sql", "warehouse", "analytics"] ) # 3) [READ] List all registered tools or inspect specific tool metadata print(arbiter.list_tools()) print(arbiter.get_tool("execute_sql_warehouse")) # 4) [ROUTE] 0.25ms~10ms intent-aware tool selection decision = arbiter.route("Analyze Q3 semiconductor division revenue in SQL warehouse") print(decision.selected_tool, decision.latency_ms) # 5) [DELETE] Remove a tool from the catalog arbiter.remove_tool("execute_sql_warehouse")

5. Docker Sidecar v2.1 Polyglot Deployment & API Control

Non-Python backend services (Node.js, Go, Java, Rust, C#, Kubernetes) can invoke all cdx-dock v2.1.0 capabilities via OpenAI-compatible /v1/chat/completions proxy endpoints using cdxno1/cdx-a2a-sidecar:2.1.0.

5.1 3-Way Container Control Interface (Env Vars · HTTP Headers · REST API)

# [Method 1] Global container defaults via environment variables & volume mounts docker run -d --name cdx-sidecar -p 8080:8080 \ -v $(pwd)/cdx_data:/data \ -e CDX_LICENSE_KEY="CDX2.YOUR_SIGNED_LICENSE_KEY" \ -e UPSTREAM_LLM_URL="https://api.openai.com" \ -e CDX_BYOS_SQLITE="/data/enterprise_vault.db" \ -e CDX_PINS="PROJECT_CODE=PRJ-TITAN,SETTLEMENT_ACC=110-384-918273" \ -e CDX_TOP_K="2" \ -e CDX_SLIMMER="true" \ cdxno1/cdx-a2a-sidecar:2.1.0 # [Method 2] Per-request dynamic override via HTTP Headers (Node.js / Go / curl) curl -X POST http://localhost:8080/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "X-CDX-License-Key: CDX2.YOUR_SIGNED_LICENSE_KEY" \ -H "Content-Type: application/json" \ -H "X-CDX-Slimmer: true" \ -H "X-CDX-Top-K: 2" \ -H "X-CDX-Pins: CONTRACT_ID=CT-2026-9981" \ -d '{"model": "gpt-6-astra", "messages": [{"role": "user", "content": "Review CT-2026-9981"}]}' # [Method 3] Live runtime REST API control (/v2/cloak/pin, /v2/cloak/pins) curl -X POST http://localhost:8080/v2/cloak/pin \ -H "X-CDX-License-Key: CDX2.YOUR_SIGNED_LICENSE_KEY" \ -d '{"key": "PARTNER_ID", "secret": "ACME-9981"}' curl -X GET http://localhost:8080/v2/cloak/pins \ -H "X-CDX-License-Key: CDX2.YOUR_SIGNED_LICENSE_KEY" curl -X DELETE "http://localhost:8080/v2/cloak/pin?key=PARTNER_ID" \ -H "X-CDX-License-Key: CDX2.YOUR_SIGNED_LICENSE_KEY"

5.2 Production Deployment Manifests (docker-compose.yml & Kubernetes Sidecar Pod)

Copy-paste ready infrastructure manifests for co-locating the CDX Sidecar on localhost:8080 alongside your backend service with zero network hop latency and automated /healthz liveness probes:

# [A] docker-compose.yml — Co-locate Backend App + CDX Sidecar version: "3.9" services: cdx-sidecar: image: cdxno1/cdx-a2a-sidecar:2.1.0 container_name: cdx-sidecar restart: unless-stopped ports: - "8080:8080" volumes: - ./cdx_data:/data environment: CDX_LICENSE_KEY: "${CDX_LICENSE_KEY}" UPSTREAM_LLM_URL: "https://api.openai.com" CDX_BYOS_SQLITE: "/data/enterprise_vault.db" CDX_SLIMMER: "true" CDX_TOP_K: "2" healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/healthz"] interval: 15s timeout: 3s retries: 3 backend-api: build: . depends_on: cdx-sidecar: condition: service_healthy environment: OPENAI_BASE_URL: "http://cdx-sidecar:8080/v1" OPENAI_API_KEY: "${OPENAI_API_KEY}"
# [B] k8s-deployment.yaml — Kubernetes Pod Sidecar Pattern (Shared localhost Loopback) apiVersion: apps/v1 kind: Deployment metadata: name: enterprise-agent-api spec: replicas: 3 selector: matchLabels: app: enterprise-agent-api template: metadata: labels: app: enterprise-agent-api spec: containers: - name: app-server image: myorg/agent-backend:latest env: - name: OPENAI_BASE_URL value: "http://127.0.0.1:8080/v1" # Local Pod loopback (0ms hop) - name: cdx-sidecar image: cdxno1/cdx-a2a-sidecar:2.1.0 ports: - containerPort: 8080 env: - name: CDX_LICENSE_KEY valueFrom: secretKeyRef: name: cdx-license-secret key: license_key - name: UPSTREAM_LLM_URL value: "https://api.openai.com" - name: CDX_BYOS_SQLITE value: "/data/enterprise_vault.db" livenessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 5 periodSeconds: 10 volumeMounts: - name: cdx-vault-storage mountPath: /data volumes: - name: cdx-vault-storage emptyDir: {}

6. Enterprise Open-Core Architecture & Security Compliance

To satisfy enterprise security and compliance reviews (static source code inspection) while delivering sub-millisecond execution performance and runtime integrity, cdx-dock v2.1.0 separates the Open Adapter Layer (.py) from the Pre-Compiled Native Core Engine (.pyd / .so).

6.1 Package Layer Specifications

Architecture LayerIncluded ModulesDistribution FormatSecurity Audit & Operational Benefit
Open Adapter Layer universal_adapter.py, adapters/*, config.py Open-Source Pure Python (.py) Full source transparency for integration code touching customer agents; enables static verification of zero external data exfiltration
Native Core Engine Layer slimmer_engine, arbiter_engine, shield_engine, etc. Pre-Compiled C-Extensions (.pyd / .so) Delivers < 1ms native execution performance and guarantees tamper-resistant runtime integrity
On-Premise License Guard license_guard, fingerprint Native Binary & Node Identifier Supports air-gapped VPC deployments with offline hardware node-bound license verification (cdx_mach_...)

6.2 Inspecting Package Layers & Node Identifier

import cdx_dock.universal_adapter as adapter_layer import cdx_dock.slimmer_engine as native_engine from cdx_dock.fingerprint import MachineFingerprint # 1) Verify Open Adapter Layer path (Inspectable .py source for internal security review) print(adapter_layer.__file__) # -> .../site-packages/cdx_dock/universal_adapter.py # 2) Verify Pre-Compiled Native Core path (.pyd / .so binary) print(native_engine.__file__) # -> .../site-packages/cdx_dock/slimmer_engine.cp313-win_amd64.pyd # 3) Retrieve Hardware Node ID for On-Premise Air-Gapped Licensing print(MachineFingerprint.get_machine_id()) # -> 'cdx_mach_...'

7. Live Local Telemetry, Self-Audit Report Builder & 1:1 Raw BYOS Export

Cantor Labs enforces a strict Zero Data Custody policy—zero prompts, token counts, tool schemas, or masking records are ever transmitted externally. Your engineering team can query live local telemetry via dock_telemetry, build factual internal reports without vendor estimates via CDXInternalReportBuilder, and export unmodified raw BYOS records in .json or .csv.

7.1 Live Local Telemetry & Persistent BYOS Ledger API (dock_telemetry)

Whenever adapters (slimmer=True), tool routing (CDXArbiter), reasoning guards (CDX-CoT-Guard), entity vaults (CDXCloak), or memory packs (TokenPack-10K) execute, counters update automatically in local memory. Calling bind_byos_storage() persists counters to your SQLite3 (cdx_telemetry_ledger table) or JSON file across server restarts.

from cdx_dock import dock_telemetry # 1) [Optional] Persist counters to customer-owned SQLite3 (.db) or JSON (.json) across restarts dock_telemetry.bind_byos_storage("./enterprise_vault.db", load_existing=True) # 2) Inspect real measured local telemetry (returns exact 0 if zero calls have executed) summary = dock_telemetry.get_summary() print(summary["total_agent_calls"]) # Total calls including any fallback events print(summary["completion_rate_pct"]) # Actual completion rate (%) & summary["fallback_calls"] print(summary["net_tokens_delta"]) # Signed net token delta (reports negative delta honestly if expanded) print(summary["average_latency_ms"]) # Real perf_counter() measured average latency (ms) print(summary["module_token_savings"]) # Per-module measured deltas (Arbiter / Slimmer / CoT-Guard / TokenPack) print(summary["cloak_byos"]) # Masked/unmasked call counts & exact entity counts

7.2 Self-Audit Report Builder & Custom Template Slot Mapping (CDXInternalReportBuilder)

To avoid any vendor bias or guessed dollar figures ($) in internal reviews, live mode (use_live_telemetry=True, default) populates ONLY actual measured runtime counters and real local AST static import checks of installed open adapters (.py). In addition to the 3 built-in templates (Token Settlement / Runtime Ops / Security Audit), any custom template registered via register_template() automatically binds all live {slot_key} variables.

📥 Sample Report Layout Preview PDFs (English formatting previews — live SDK execution outputs 100% actual customer BYOS data): 📘 Combined Layout Preview PDF (4p) ① Token Settlement Layout PDF ② Runtime Ops Layout PDF ③ Security Audit Layout PDF
Report ScopeMeasured Fields (Zero Price Guesswork)Local Data SourceAuto-Bound Template Slots ({slot_key})
Header
(org_info)
Department / Author / Period / Environment / Internal LLM Rate Note Customer input (org_info={...}) {company_name}, {author_name}, {reporting_period}, {deployment_mode}, {customer_llm_contract_note}
① Token Settlement
(cfo_roi_settlement_report)
Measured calls · Raw vs. slimmed tokens · Signed net delta (+/-) · Per-module savings · Internal cost formula summary['total_agent_calls']
summary['net_tokens_delta']
summary['module_token_savings']
{monthly_agent_calls}, {raw_tokens_total}, {slimmed_tokens_total}, {saved_tokens_total}, {stage1_arbiter_saved_tokens}, {stage2_slimmer_saved_tokens}, {stage3_cot_guard_saved_tokens}, {stage4_5_memory_saved_tokens}, {customer_cost_formula}
② Runtime Ops
(cto_agent_runtime_report)
Measured runs & completion rate (%) · Avg latency (ms) · <think> loops broken · TokenPack recall latency · Fallback count summary['completion_rate_pct']
summary['average_latency_ms']
summary['fallback_calls']
{connected_frameworks}, {total_pipeline_runs}, {avg_dock_overhead_ms}, {cot_guard_loops_detected}, {cot_timeouts_prevented}, {cot_wasted_tokens_saved}, {tokenpack_recall_latency}, {fallback_activations}
③ Security Audit
(ciso_security_audit_report)
BYOS vault path · Outbound bytes (0 Byte) · Pinned categories · Masked/restored counts · Live AST static import scan reporter.cloak.vault_db_file
summary['cloak_byos']
verify_open_adapter_static_imports()
{byos_storage_location}, {vendor_data_transmission}, {cloak_pinned_categories}, {total_masked_outbound_calls}, {local_unmask_restorations}, {false_positive_mutations}, {static_code_audit_result}
from cdx_dock import CDXInternalReportBuilder reporter = CDXInternalReportBuilder( storage_path="./enterprise_vault.db", arbiter_storage_path="./enterprise_tools.db", token_pack_dir="./shared_agent_memory", persist_telemetry=True, lang="en", # Outputs native corporate English built-in templates & A4 HTML sign-off layout ) # 1) Export built-in reports in .md, .html (A4 print-ready), .csv (Excel-ready), or .json reporter.save_report( template_id="cfo_roi_settlement_report", output_path="./reports/token_settlement.md", org_info={"company_name": "AI Platform Div.", "author_name": "Alex Kim", "reporting_period": "2026-10"}, use_live_telemetry=True, ) reporter.save_report("cto_agent_runtime_report", "./reports/runtime_ops.csv", use_live_telemetry=True) reporter.save_report("ciso_security_audit_report", "./reports/security_audit.html", use_live_telemetry=True) # 2) Register a custom corporate template — all {slot_key} variables auto-bind to live BYOS counters reporter.register_template( template_id="weekly_ops_digest", title="Weekly AI Agent Measured Telemetry Digest", template_markdown=( "Team: {company_name} | Calls: {monthly_agent_calls} | Net Delta: {saved_tokens_total}\n" "Avg Overhead: {avg_dock_overhead_ms} | Masked Calls: {total_masked_outbound_calls}" ), sample_org_info={"company_name": "AI Platform Div."}, ) digest_md = reporter.render_report("weekly_ops_digest")

7.3 1:1 Raw BYOS Data Export (export_byos_raw_data) & License Quota API

To feed internal BI dashboards or compliance pipelines directly, export_byos_raw_data() extracts unmodified raw records across all four BYOS stores (cdx_explicit_vault, cdx_arbiter_tools, pack_entries, cdx_telemetry_ledger) into .json or .csv. Commercial plan pricing and add-on details are available on the Product Pricing Configurator (dock_en.html#pricing).

import cdx_dock from cdx_dock import get_tier_spec # 1) Export unmodified 1:1 raw records from all customer BYOS stores (.json or Excel-ready .csv) raw_bundle = reporter.export_byos_raw_data( output_path="./reports/byos_raw_passthrough.csv", include_secret_values=False, # False omits plaintext secret values; True exports full self-custody records ) # 2) Programmatically inspect active license tier and step quota specifications lic_status = cdx_dock.get_license_info() scale_quota = get_tier_spec("SCALE") print(lic_status["tier"], scale_quota["monthly_dock_calls"])

8. Production Hybrid Pipeline Recipes

Common architecture patterns for cross-framework multi-agent systems in production.

8.1 LangChain SQL Agent ➔ CrewAI Collaborative Team

from langchain_community.agent_toolkits import create_sql_agent from crewai import Agent, Crew, Task from cdx_dock import as_crewai_tool # [1] Create LangChain SQL Agent sql_agent = create_sql_agent(llm=..., db=..., verbose=False) # [2] 1-Line conversion into a CrewAI tool (Payload compression enabled) db_tool = as_crewai_tool(sql_agent, name="enterprise_db", slimmer=True) # [3] Assign tool to CrewAI agent and execute task analyst = Agent( role="Lead Financial Analyst", goal="Query corporate revenue datasets and generate quarterly reports", tools=[db_tool], verbose=True ) task = Task( description="Analyze Q3 2026 key transaction records", agent=analyst ) crew = Crew(agents=[analyst], tasks=[task]) result = crew.kickoff()

8.2 [Python Backend Standard] FastAPI + OpenAI SDK End-to-End Integration (Multi-User Request-Scoped Isolation)

Production web server blueprint demonstrating how concurrent user requests isolate their sensitive entities via request-scoped session maps—Combining CDXCloak (entity masking) + CDXArbiterEngine (Top-K tool routing) + the official openai Python SDK:

from fastapi import FastAPI from pydantic import BaseModel from openai import OpenAI import cdx_dock from cdx_dock import CDXCloak, create_arbiter app = FastAPI() cdx_dock.set_license_key("CDX2.YOUR_SIGNED_LICENSE_KEY") # 1) Initialize shared BYOS SQLite3 Vault & In-Memory Tool Router at server startup cloak = CDXCloak(storage_path="./enterprise_vault.db") arbiter = create_arbiter(storage_path="./enterprise_tools.db") llm_client = OpenAI() class ChatRequest(BaseModel): user_id: str customer_name: str account_number: str query: str @app.post("/api/v1/agent/chat") def handle_agent_chat(req: ChatRequest): # 2) Pin request-specific secrets & create isolated request-scoped `session` cloak.pin_secret(req.customer_name, label=f"CUST_{req.user_id}") cloak.pin_secret(req.account_number, label=f"ACC_{req.user_id}") raw_prompt = f"Customer {req.customer_name} ({req.account_number}): {req.query}" masked_prompt, session = cloak.mask_text(raw_prompt) # 3) Route to most relevant tool schema in <10ms (-90%+ schema overhead) routed = arbiter.route(masked_prompt) # 4) Outbound LLM call (Zero raw PII/secrets ever leave your VPC boundary) completion = llm_client.chat.completions.create( model="gpt-6-astra", messages=[ {"role": "system", "content": f"Tool: {routed.selected_tool}"}, {"role": "user", "content": masked_prompt} ] ) # 5) Restore original entities in local memory using the request-scoped `session` llm_reply = completion.choices[0].message.content final_answer = cloak.unmask_text(llm_reply, session) return {"reply": final_answer, "routed_tool": routed.selected_tool}

8.3 [Node.js / TypeScript Standard] Next.js & Express with Official openai NPM Package

Zero new SDK dependencies required—Simply point baseURL in the official openai NPM package to your local CDX Sidecar (http://localhost:8080/v1) and pass per-request X-CDX-* headers:

// npm install openai import OpenAI from "openai"; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, baseURL: process.env.CDX_SIDECAR_URL || "http://localhost:8080/v1", defaultHeaders: { "X-CDX-License-Key": process.env.CDX_LICENSE_KEY || "CDX2.YOUR_SIGNED_LICENSE_KEY", "X-CDX-Slimmer": "true", "X-CDX-Top-K": "2", }, }); export async function invokeEnterpriseAgent( customerName: string, accountNo: string, userQuery: string ) { const response = await openai.chat.completions.create( { model: "gpt-6-astra", messages: [ { role: "user", content: `Verify ${customerName} (${accountNo}): ${userQuery}` } ], }, { // Pin request-scoped secrets via HTTP header (Masked & restored locally) headers: { "X-CDX-Pins": `VIP_CUSTOMER=${customerName},SETTLEMENT_ACC=${accountNo}`, }, } ); return response.choices[0].message.content; // Original secrets restored locally }

8.4 [Java Spring Boot Standard] Enterprise Sidecar Integration via RestClient

Standard integration pattern for Java 17+ / Spring Boot 3.2+ financial and enterprise backends routing LLM traffic through the local CDX Sidecar:

import org.springframework.web.client.RestClient; import org.springframework.stereotype.Service; import java.util.Map; import java.util.List; @Service public class CdxAgentGatewayService { private final RestClient restClient = RestClient.builder() .baseUrl("http://localhost:8080/v1") .defaultHeader("X-CDX-License-Key", System.getenv("CDX_LICENSE_KEY")) .defaultHeader("X-CDX-Slimmer", "true") .defaultHeader("X-CDX-Top-K", "2") .build(); public String queryProtectedAgent( String openAiKey, String accountNo, String prompt ) { return restClient.post() .uri("/chat/completions") .header("Authorization", "Bearer " + openAiKey) .header("X-CDX-Pins", "SETTLEMENT_ACC=" + accountNo) .body(Map.of( "model", "gpt-6-astra", "messages", List.of(Map.of("role", "user", "content", prompt)) )) .retrieve() .body(String.class); } }

9. Zero-Downtime Resilience & Emergency Bypass

Defensive engineering guarantees ensuring uninterrupted service even during upstream framework breaking changes.

9.1 3-Tier Polymorphic Fallback Chain

If a method signature fails, execution automatically shifts to the next standard interface:

invoke() ➔ [fallback] ➔ run() ➔ [fallback] ➔ __call__() ➔ raw str()

9.2 Single-Variable Emergency Bypass Switch

In the event of an unexpected upstream library incompatibility, bypass all wrapping with a single variable without refactoring application code:

import cdx_dock.universal_adapter as cdx_guard # Instantly bypass all wrappers and restore native pass-through execution cdx_guard._cdx_adapter_bypass = True

10. Adoption Architecture & Enterprise 2-Week PoC Checklist

Recommended deployment patterns and PoC verification workflows tailored by organization profile—from early-stage startups and mid-market SaaS teams to regulated financial, healthcare, and public-sector organizations and air-gapped on-premise deployments.

10.1 Recommended Docking Architecture Matrix Across 4 Enterprise Personas

Organization ProfileRecommended RuntimeCore Module CombinationPrimary Verification KPIs
1. Startups & AI Agencies In-Process Python SDK (pip install cdx-dock) as_crewai_tool + DockSlimmer (Mode B) 1-line cross-framework docking · 40–55% lossless LLM payload savings (internal benchmark)
2. Mid-Market B2B SaaS & Platform Teams Python SDK or Docker Sidecar v2.1.0 CDXArbiter + CDX-CoT-Guard + TokenPack-10K 85–93% tool schema token savings · runaway reasoning loop protection (internal benchmark)
3. Regulated Industries (Finance, Healthcare & Public Sector) Private VPC / Air-Gapped Sidecar + SQLite3 BYOS CDXCloak (strict_pin_mode=True) + Local BYOS Vault Zero outbound network imports in open adapters · pinned secrets isolated inside customer VPC
4. On-Premise Air-Gapped & Global OEM Fleets Offline Hardware Node Lock (MachineFingerprint) + Native Binary All 7 modules unlocked + SIEM JSONL cryptographic audit logs 100% offline license verification · centralized multi-project cost & security governance

10.2 Frictionless 2-Week Enterprise PoC Checklist (30-Day Sandbox)

# [Days 1-2] Phase 1: Zero-Refactor 1-Line Docking & Static Security Review # - Verify zero external network module imports (requests/urllib/httpx) in cdx_dock open adapters (.py) # - Validate explicit CDXCloak variable pinning & local SQLite3 (.db) BYOS storage isolation # [Days 3-7] Phase 2: Measure Payload Slimming, Routing & CoT-Guard on Mirrored Traffic # - Benchmark DockSlimmer Mode B savings and CDXArbiter Top-K routing latency (< 1.0ms) # [Days 8-14] Phase 3: Export Measured PoC Telemetry Reports & Raw BYOS Records from cdx_dock import CDXInternalReportBuilder reporter = CDXInternalReportBuilder(storage_path="./enterprise_vault.db", persist_telemetry=True, lang="en") reporter.save_report("cfo_roi_settlement_report", "./reports/poc_measured_tokens.md", use_live_telemetry=True) reporter.export_byos_raw_data("./reports/poc_byos_raw_records.csv") # Unmodified 1:1 BYOS CSV export

11. AI Coding Agents & Multi-Subagent Token Diet Recipes

Practical, copy-pasteable integration patterns for cutting quadratic token burn across AI coding harnesses (Claude Code, Cursor, Cline, Windsurf) and custom multi-subagent pipelines (Planner ➔ Coder ➔ Reviewer)—without rewriting your agent logic.

11.1 Why Multi-Subagent & Coding Workflows Burn 10–15x More Tokens (Before vs After)

The table below illustrates an architectural simulation of a single 4-subagent task equipped with 40 MCP tools before and after attaching cdx-dock v2.1.0. (In production, exact per-call token deltas are recorded transparently in your local DockTelemetry ledger.)

Token Drain Bottleneck Without CDX-Dock (Before) With CDX-Dock (After) Active Engine & Mechanism
1. 40 MCP Tool Schemas Full JSON schemas re-injected on every subagent turn (~18,000 tok) ~1,400 tok
(~88–92% reduction)
CDXArbiter selects only Top-2 relevant tools in < 1ms + MCPOptimizer prunes nested $defs bloat
2. Cross-Subagent History Copy (O(N²)) Raw files & prior chat logs pasted verbatim into downstream prompts (~42,000 tok) ~14,500 tok
(~45–65% reduction)
CDXTokenPack10K recalls only Top-2 distilled specs + DockSlimmer Mode B compacts JSON tool outputs
3. Runaway <think> Loops Reasoning model spins on compiler/schema errors until timeout (~22,000 tok) ~3,900 tok
(Early loop termination)
CDX-CoT-Guard detects repetitive reasoning loops and cleanly closes <think> to emit the final patch
4. .env & API Key Exposure Plaintext credentials sent externally whenever an agent reads config files 0 Bytes Egress
(0.04ms local restore)
CDXCloak replaces pinned secrets with [[VAULT_PIN_...]] outbound and unmasks responses locally

11.2 Pattern A [Zero Code Changes] — Attach Local Sidecar Proxy to Cursor · Claude Code · Cline

Launch Docker Sidecar v2.1.0 on your workstation or team dev gateway and point a single Base URL environment variable to http://localhost:8080/v1. Schema pruning, payload slimming, and local secret masking take effect immediately.

# [1] Start CDX Sidecar v2.1.0 locally (30-Day Free Sandbox active out of the box) docker run -d --name cdx-coding-proxy -p 8080:8080 \ -v $(pwd)/cdx_byos:/data \ -e UPSTREAM_LLM_BASE_URL="https://api.openai.com/v1" \ cdxno1/cdx-a2a-sidecar:2.1.0 # [2] Point your CLI / IDE coding agent Base URL to the local sidecar! export OPENAI_BASE_URL="http://localhost:8080/v1" # (Optional) Configure per-request headers in agent settings for Top-K routing & secret pinning: # X-CDX-Slimmer: true # X-CDX-Top-K: 3 # X-CDX-Pins: PROD_DB_PASS=my_super_secret_pw,STRIPE_LIVE_KEY=sk_live_xxx

11.3 Pattern B [MCP Schema Diet] — Prune 40+ MCP Tool Schemas by ~90% per Turn

Connecting Git, Postgres, Kubernetes, Jira, and Slack MCP servers simultaneously can burn 15,000+ prompt tokens on every turn before the model writes a single line of code. Combine create_arbiter, MCPOptimizer, and wrap_anthropic to inject only the compact Top-2 tools needed for the current step.

from anthropic import Anthropic from cdx_dock import create_arbiter, MCPOptimizer, wrap_anthropic # [1] Initialize local BYOS MCP tool router & schema optimizer arbiter = create_arbiter(storage_path="./dev_mcp_tools.db") mcp_opt = MCPOptimizer() # [2] Wrap official Anthropic client in 1 line (auto schema pruning + streaming unmasking) client = wrap_anthropic(Anthropic(), mcp_opt=mcp_opt, slim_prompts=True) def run_coding_turn(task_prompt: str, all_mcp_schemas: list[dict]): # Register MCP catalog once & select only Top-2 relevant tools out of 40+ schemas in ~0.4ms if not arbiter.tools: arbiter.register_tools(all_mcp_schemas) decision = arbiter.route(task_prompt, top_k=2) keep_names = {c["name"] for c in decision.get("candidates", [])} active_tools = [t for t in all_mcp_schemas if t.get("name") in keep_names] or all_mcp_schemas[:2] # MCPOptimizer inside wrap_anthropic further strips redundant descriptions & unused $defs resp = client.messages.create( model="claude-mythos-5-2", max_tokens=2048, tools=active_tools, messages=[{"role": "user", "content": task_prompt}], ) return resp

11.4 Pattern C [Subagent Handoff Diet] — Eliminate O(N²) Context Copy-Pasting Across Planner ➔ Coder ➔ Reviewer

Instead of copying tens of thousands of tokens of raw files and logs into every downstream subagent prompt, store distilled engineering specs in a shared local CDXTokenPack10K directory so downstream subagents recall only the exact Top-2 specs in < 1ms.

from openai import OpenAI from cdx_dock import wrap_openai, CDXCloak, CDXTokenPack10K, DockSlimmer, dock_telemetry # [1] Initialize shared local 10K memory pack & BYOS secret vault across subagents shared_pack = CDXTokenPack10K(pack_dir="./subagent_shared_pack") cloak = CDXCloak(storage_path="./subagent_vault.db") slimmer = DockSlimmer() # Pin local credentials so secrets never leak to external LLM APIs, then wrap OpenAI in 1 line cloak.pin_secret("rk_prod_9988776655", label="INTERNAL_API_KEY") llm = wrap_openai(OpenAI(), cloak=cloak, slimmer=slimmer, slim_prompts=True) # [2] Planner Subagent: Ingest concise architectural spec instead of copying full raw files shared_pack.ingest( "CRITICAL SPEC: Shorten JWT expiry to 900s in auth_middleware.py and enforce refresh_token rotation", metadata={"stage": "planner", "target": "auth_middleware.py"}, ) # [3] Coder / Reviewer Subagents: Recall only Top-2 relevant specs in <1ms (zero full-history copy!) recalled = shared_pack.recall("auth_middleware JWT refresh_token spec", top_k=2) compact_context = "\n".join(item["text"] for item in recalled["items"]) slim_ast_json = slimmer.to_mode_b({"file": "auth_middleware.py", "exports": ["verify_jwt", "rotate_refresh"]}) coder_resp = llm.chat.completions.create( model="gpt-6-astra", messages=[ {"role": "system", "content": f"Target Spec:\n{compact_context}\nAST Summary:{slim_ast_json}"}, {"role": "user", "content": "Generate a minimal patch for verify_jwt and rotate_refresh matching the spec."}, ], ) # [4] Inspect exact measured token delta from your local telemetry ledger print("Measured net token delta:", dock_telemetry.get_summary()["net_tokens_delta"])

12. [AI-Ready] Complete Engine, Option & API Master Reference (v2.1.0)

A single-page canonical reference engineered so human developers and AI coding agents (Cursor · Claude Code · Antigravity) can immediately distinguish built-in core engines from tier-gated/optional modules and integrate cdx-dock v2.1.0 into production on the first pass.

12.1 Built-in Core Engines vs. Optional Modules & Tier Entitlement Matrix

Engine / Public SymbolCategoryPlan EntitlementPrimary Function & Measured Impact
as_crewai_tool / as_langchain_tool / as_autogen_agent / bridge / adapt / @dockCore Engine 01All Tiers (Sandbox–Enterprise)1-line cross-framework agent binding + CDXHermesDock Top-K SKILL.md routing
DockSlimmer (to_mode_b / to_mode_a / CDXTAB1:)Core Engine 02All TiersMode B JSON compaction + automatic lossless columnar CDX-Tab (54.7–66% reduction on 4+ row uniform tables, 4-condition safety guard)
CDXArbiterEngine (Multilingual v2.1)Core Engine 03All TiersEN·KO·JA·ES·DE·FR queries → English SaaS APIs in <1.3ms zero-LLM memory routing (BYOS SQLite/JSON CRUD)
MCPOptimizer · AgentDock · wrap_openai / wrap_anthropic / wrap_geminiCore / WrappersAll TiersMCP schema pruning, local multi-agent mesh bus, and 1-line official LLM SDK wrappers
CDXCloak · CDXDockShieldSecurity Vault (Engine 05)Sandbox / Add-on / Growth+ VoucherExplicit secret pinning (pin_secret) & regex masking/unmasking (0-byte external egress)
CDXCoTMiddleware (CDX-CoT-Guard)Reasoning Guard (Engine 06)Sandbox / Add-onEarly termination of repetitive <think> loops & vLLM KV-Cache memory damping
CDXTokenPack10K (Single 10K)Shared Memory (Engine 07A)Sandbox / Starter–EnterpriseZero-Vector-DB local folder (pack_dir) 10,000-token 8-language shared memory
CDXVaultPack2K · CDXDualTokenPack (10K ∥ 2K)Parallel Vault (Engine 07B)Sandbox Trial · Built into Growth ($1,490)+
(Starter: Safe Pass-Through)
100% customer-local Zero-Knowledge AES-256-GCM + AAD, PCI CVV strip, and 1-Bit RBAC

12.2 CDXVaultPack2K Role-Based Vault Access Badges (1-Bit RBAC) & Setup Options

Why is this needed? In a real AI application, external cloud LLMs and internal tools (shipping, billing, payment) run side by side. 1-Bit RBAC acts like role-based keycards so each component can only unlock the exact vault drawer it is authorized for.
Example flow: When a user enters both a home address and credit card in chat → the Cloud LLM (ROLE_CLOUD_PLANNER) sees only masked handles → the Shipping Tool (ROLE_ADDRESS_TOOL) can read only the address (card access is automatically denied) → and the Payment Executor (ROLE_PAYMENT_EXECUTOR) decrypts the card locally for a split second only after explicit user_consent=True.

RBAC Constant (Bitmask)Allowed Categoriesuser_consent=TrueIntended Caller
ROLE_CLOUD_PLANNER (0x00)None (Always Denied)Always DeniedExternal Cloud LLM Planner (0% raw secret exposure)
ROLE_ADDRESS_TOOL (0x01)ADDRESS, PHONE, EMAILOptionalLocal shipping / notification tool
ROLE_BILLING_TOOL (0x02)BANKOptionalLocal refund-account / settlement tool
ROLE_PAYMENT_EXECUTOR (0x04)CARD, RRNRequiredLocal payment execution tool (ephemeral decrypt on consent)
ROLE_AUTH_EXECUTOR (0x08)API_KEY, LICENSERequiredLocal authenticated API execution tool

Key Constructor Options: CDXVaultPack2K(vault_dir="./vault", master_key=kms_32bytes, strict_tier=True) — inject a 32-byte master_key from AWS KMS / HashiCorp Vault; on Starter tier, calls degrade gracefully via Safe Pass-Through and set vault_tier_upgrade_required=True in the returned metadata.

12.3 [Copy-Paste Ready for AI Agents] Full-Stack Production Template (Multilingual Arbiter + CDX-Tab + VaultPack-2K)

import os from cdx_dock import ( CDXArbiterEngine, DockSlimmer, CDXVaultPack2K, CDXDualTokenPack, ROLE_CLOUD_PLANNER, ROLE_ADDRESS_TOOL, ROLE_BILLING_TOOL, ROLE_PAYMENT_EXECUTOR, ROLE_AUTH_EXECUTOR, ) # 1) Multilingual Zero-LLM SaaS Tool Router (EN/KO/JA/ES/DE/FR -> English APIs) arbiter = CDXArbiterEngine(strict_license=False) arbiter.register_tools([ {"name": "stripe_create_refund", "description": "Refund a customer payment charge on Stripe."}, {"name": "google_calendar_book", "description": "Schedule a meeting event on Google Calendar."}, ]) route_ja = arbiter.route("Googleカレンダーで明日の会議を予約して", top_k=2) # -> route_ja["tool_name"] == "google_calendar_book" # 2) Automatic Lossless CDX-Tab Compression for Uniform JSON Tables (Ragged JSON falls back safely) slimmer = DockSlimmer() sample_rows = [{"order_id": i, "status": "COMPLETED", "region": "us-east-1"} for i in range(10)] slim_payload = slimmer.to_mode_b(sample_rows) # "CDXTAB1:..." exact_rows = slimmer.to_mode_a(slim_payload) # 100% exact roundtrip # 3) Customer KMS 32-Byte Master Key Local VaultPack-2K + 1-Bit RBAC Verification kms_key = os.urandom(32) # In production, load 32 bytes from AWS KMS / HashiCorp Vault vault = CDXVaultPack2K(vault_dir="./local_vault", master_key=kms_key, strict_tier=True) masked_txt, v_meta = vault.mask_and_vault_text("Card 4532-1122-3344-5566 CVV=831 email ops@acme.io") if v_meta.get("vault_tier_upgrade_required"): print("Starter Safe Pass-Through active — upgrade to Growth+ for persistent AES-256-GCM VaultPack-2K") else: card_h = [h for h in v_meta["handles"] if ":CARD:" in h][0] email_h = [h for h in v_meta["handles"] if ":EMAIL:" in h][0] assert not vault.resolve_handle(card_h, ROLE_CLOUD_PLANNER, True)["authorized"] assert not vault.resolve_handle(card_h, ROLE_ADDRESS_TOOL, True)["authorized"] assert vault.resolve_handle(email_h, ROLE_ADDRESS_TOOL, False)["authorized"] assert vault.resolve_handle(card_h, ROLE_PAYMENT_EXECUTOR, True)["authorized"]