code-mode-toon
Optimizes SRE workflows and infrastructure audits by compressing large Kubernetes manifests and log datasets by up to 83%.
Enables efficient querying of Perplexity AI with automatic TOON compression on the returned search results to save token usage.
Allows parallelized data fetching from Wikipedia as part of research workflows to synthesize findings with minimal context overhead.
CodeModeTOON MCP Server
A lightweight Model Context Protocol (MCP) orchestrator designed for efficiency at scale. It features TOON compression (reducing token usage by 30-90%) and Lazy Loading, making it the ideal solution for complex, multi-tool agentic workflows.
The "Context Trap" in Agentic Workflows
Recent articles from Anthropic and Cloudflare (see Here) highlights a critical bottleneck: AI agents struggle with complex, multi-step workflows because they lack state.
While Code Execution (e.g., TypeScript) allows agents to maintain state and structure workflows effectively, it introduces a new problem: Data Bloat. Real-world operations (like SRE log analysis or database dumps) generate massive JSON payloads that explode the context window, making stateful execution prohibitively expensive.
CodeModeTOON bridges this gap. It enables:
Stateful Execution: Run complex TypeScript workflows to maintain context outside the model.
Context Efficiency: Use TOON Compression to "zip" the results, allowing agents to process massive datasets without blowing their token budget.
Related MCP server: LW MCP Agents
How It Works
graph LR
A[AI Agent<br/>Claude/Cursor] -->|JSON-RPC| B[CodeModeTOON<br/>Server]
B -->|Lazy Load| C[Perplexity]
B -->|Lazy Load| D[Context7]
B -->|Lazy Load| E[Custom Servers]
C -->|Raw JSON| B
D -->|Raw JSON| B
E -->|Raw JSON| B
B -->|TOON<br/>Compressed| A
style B fill:#4f46e5,color:#fff
style A fill:#10b981,color:#fffData Flow: Requests route through CodeModeTOON β Servers are lazy-loaded on-demand β Responses are TOON-compressed before returning to the agent.
π₯ Key Features
ποΈ TOON Compression
Reduces token usage by 30-90% for structured data.
Validated: ~83% savings on Kubernetes audits
Best for: SRE logs, database dumps, API responses
How it works: Schema extraction + value compression
β‘ Lazy Loading
Servers only start when needed. Zero overhead for unused tools.
Best for: Multi-tool workflows, resource-constrained environments
Performance: Sub-100ms startup for active servers
π Sandboxed Execution
Secure JS execution with auto-proxied MCP tool access.
Best for: Complex stateful workflows, batch operations
Security: Uses Node.js
vmmodule (not for multi-tenant use)
π€ Agent-Friendly Features
Designed for programmatic discovery and self-correction.
suggest_approach: Meta-tool that recommends the best execution strategy (code vs workflow vs direct call).Efficiency Metrics:
execute_codereturns operation counts and compression savings to reinforce efficient behavior.Recovery Hints: Error messages include actionable next steps for agents (e.g., "Server not found? Try list_servers").
Table of Contents
When to Use CodeModeTOON
β Perfect for:
Multi-step AI workflows requiring state management
Processing large structured datasets (logs, DB dumps, K8s manifests)
Coordinating multiple MCP servers in parallel
Token-constrained environments (reducing API costs)
β Not ideal for:
Simple single-tool queries
Unstructured text-heavy responses (compression <10%)
Multi-tenant production servers (vm module security limitation)
Installation
OneβClick (Cursor)
Manual Setup
Add this to your ~/.cursor/mcp.json:
{
"mcpServers": {
"code-mode-toon": {
"type": "stdio",
"command": "npx",
"args": ["-y", "code-mode-toon"],
"env": {
"CODE_MODE_TOON_CONFIG": "~/.cursor/mcp.json"
}
}
}
}π§ Claude Skills
CodeModeTOON includes a pre-built Claude Skill to make your AI assistant an expert at using this orchestrator.
code-mode-toon-workflow-expert
A specialized skill that teaches Claude how to:
Decide when to use a workflow vs ad-hoc code.
Create new workflows following best practices.
Orchestrate multiple tools efficiently.
Installation:
Unzip
claude-skills/code-mode-toon-workflow-expert.skillPlace the folder in your
.claude/skills/directory (or import via Claude desktop app).
π€ AI Assistant Prompts
Copy these prompts into your AI's custom instructions (e.g., .cursorrules or Claude Project instructions) to maximize CodeModeTOON's potential.
1. System Identity & Orchestration (Essential)
Goal: Teaches the AI to act as an orchestrator and prioritize workflows.
YOU ARE AN AGENTIC ORCHESTRATOR. You have access to "CodeModeTOON", a high-efficiency MCP bridge.
1. PRIORITIZE WORKFLOWS: Before running single tools, check `list_workflows`. If a workflow exists (e.g., `research`, `k8s-detective`), USE IT. It is faster and saves tokens.
2. HANDLE COMPRESSED DATA: Outputs may be "TOON encoded" (highly compressed JSON). This is normal. Do not complain about "unreadable data" - simply parse it or ask for specific fields if needed.
3. BATCH OPERATIONS: Never run 3+ sequential tool calls if they can be batched. Use `execute_code` to run them in a single block.2. Tool Discovery (Lazy Loading)
Goal: Prevents the AI from giving up if a tool isn't immediately visible.
TOOLS ARE LAZY LOADED. If you need a capability (e.g., "search", "kubernetes", "database") and don't see the tool:
1. DO NOT assume it's missing.
2. RUN `search_tools({ query: "..." })` to find it.
3. RUN `get_tool_api({ serverName: "..." })` to learn how to use it.
4. Only then, execute the tool.3. Efficiency & TOON Compression
Goal: Enforces token-saving behaviors for large data operations.
OPTIMIZE FOR TOKENS. When fetching large datasets (logs, docs, API responses):
1. ALWAYS wrap the output in `TOON.encode(data)` inside `execute_code`.
2. PREFER structured data (JSON/Objects) over plain text. TOON compresses structure by ~83%, but text by only ~4%.
3. IF synthesizing data, do it server-side (via workflow `synthesize: true`) to avoid pulling raw data into context.Quick Start
After installation, try this 30-second demo in Claude or Cursor:
// Ask your AI assistant to run this via execute_code
const api = await get_tool_api({ serverName: 'perplexity' });
const result = await servers['perplexity'].perplexity_ask({
messages: [{ role: 'user', content: "Explain TOON compression" }]
});
console.log(result); // See compression in action! ~40% token savingsWhat just happened? The response was automatically TOON-encoded, saving tokens.
Usage Examples
// Inside execute_code
const api = await get_tool_api({ serverName: 'perplexity' });
// Request large data - automatically compressed!
const result = await servers['perplexity'].perplexity_ask({
messages: [{ role: 'user', content: "Summarize the history of Rome" }]
});
console.log(result); // Returns TOON-encoded string, saving ~40% tokens// Fetch large documentation from Context7
const api = await get_tool_api({ serverName: 'context7' });
const docs = await servers['context7']['get-library-docs']({
context7CompatibleLibraryID: 'kubernetes/kubernetes'
});
console.log(TOON.encode(docs)); // Massive compression on structured data// Run a complex research workflow
const result = await workflows.research({
goal: "Compare xsync vs sync.Map performance",
queries: ["xsync vs sync.Map benchmarks"],
synthesize: true,
outputFile: "/tmp/research.toon"
});
console.log(result.synthesis); // LLM-synthesized findingsWorkflows
CodeModeTOON supports Workflowsβpre-defined, server-side TypeScript modules that orchestrate multiple MCP tools.
Research Workflow
A powerful research assistant that:
Parallelizes data fetching from multiple sources (Context7, Wikipedia, Perplexity).
Synthesizes findings using LLMs (optional).
Outputs TOON-encoded files for maximum context efficiency.
Retries failed requests automatically.
See .workflows/README.md for detailed documentation, usage examples, and AI prompts.
Performance Benchmark
Why This Matters
Scenario 2 (92% savings) demonstrates CodeModeTOON's strength:
Metric | Original | TOON | Savings |
Characters | 37,263 | 2,824 | ~83% |
Estimated Tokens* | ~9,315 | ~706 | ~8,600 tokens |
Cost (Claude Sonnet)** | $0.028 | $0.002 | $0.026 |
*Assuming 4 chars/token average
***$3/M tokens input pricing*
Key Insight: For infrastructure audits, log analysis, or database dumps, TOON compression can reduce token costs by 90%+, making complex agentic workflows feasible within budget.
Scenario 1: Natural Language Query (History of Rome) Unstructured text compresses poorly, as expected.
Original JSON: 11,651 chars
TOON Encoded: 11,166 chars
Compression Ratio: ~4.16% Savings
Scenario 2: Kubernetes Cluster Audit (50 Pods) Highly structured, repetitive JSON (infrastructure dumps) compresses extremely well.
Original JSON: 37,263 chars
TOON Encoded: 2,824 chars
Compression Ratio: ~83% Savings π
Troubleshooting
"Server not found" error
Cause: CodeModeTOON can't locate your MCP config.
Solution: Ensure CODE_MODE_TOON_CONFIG points to your config:
export CODE_MODE_TOON_CONFIG=~/.cursor/mcp.jsonTOON encoding not working
Cause: Results aren't being encoded.
Solution: Use console.log(TOON.encode(data)), not console.log(data).
Lazy server won't load
Cause: Server name mismatch.
Solution: Verify server name matches your config. Use get_tool_api({ serverName: 'name' }) to inspect available servers.
Security Note
β οΈ The vm module is NOT a security sandbox. Suitable for personal AI assistant use (Claude, Cursor) with trusted code. Not for multi-tenant or public services.
Acknowledgments
Anthropic: Code execution with MCP
Cloudflare: Code Mode announcement
Author
Built by Ziad Hassan (Senior SRE/DevOps) β LinkedIn Β· GitHub
Contributing
Contributions are welcome! π
Ways to Contribute
Report bugs - Open an issue with reproduction steps
Suggest features - Discuss use cases in Issues
Add workflows - See Workflows
Improve docs - Documentation PRs always welcome
Development Setup
git clone https://github.com/ziad-hsn/code-mode-toon.git
cd code-mode-toon
npm install
npm testLicense
MIT License β see LICENSE for details.
Available Tools
9 toolsexecute_codeA
WHEN TO USE:
Batching 3+ MCP tool calls (saves round-trips, maintains state)
Processing large structured data (TOON compression: 30-90% savings)
Complex logic with conditionals/loops across tool results
DO NOT USE:
Single simple tool call β use direct MCP
Unstructured prose β TOON compression <10%
AVAILABLE SERVERS: LAZY-LOAD ON DEMAND:
WORKFLOWS (use execute_workflow instead for these):
k8s-detective: Comprehensive Kubernetes cluster security and health auditor | USAGE: Scans pods, deployments, services, and events for security vulnerabilities, resource inefficiencies, and stability issues. Outputs detailed findings with severity ratings. EXAMPLE: "Audit my production cluster for security risks" PARAMETERS:
outputFile: Path to save TOON-compressed audit data (required)
namespace: Specific namespace to scan (optional, default: all)
includeEvents: Analyze recent events for warnings (optional, default: true) REQUIRES: kubectl configured with cluster access NOTES: Requires kubectl in PATH. Large clusters auto-TOON-encode. Run from bastion or local with kubeconfig.
post-mortem: Intelligent log analysis with pattern clustering and anomaly detection | USAGE: Parses log files, clusters similar messages by signature, extracts dynamic data (timestamps, IDs, IPs), identifies anomalies and errors, and generates an actionable report. EXAMPLE: "Analyze application logs from the outage and find the root cause" PARAMETERS:
logFile: Path to the log file to analyze (required)
outputFile: Path to save TOON-compressed analysis (required)
maxExamples: Max example lines per cluster (optional, default: 5)
includePatterns: Include normal patterns in output (optional, default: true) REQUIRES: filesystem access NOTES: Supports large files via streaming. Auto-detects log levels and categories.
research: Multi-source research aggregator with parallel execution and synthesis | USAGE: Orchestrates data fetching from Context7 (library docs), Wikipedia (concepts), and Perplexity (web Q&A). Supports parallel execution, retry logic, rate limiting, optional LLM synthesis, and file output. EXAMPLE: "Research xsync library performance vs sync.Map with benchmarks and theory. libraryIDs: ['puzpuzpuz/xsync'], wikipediaTopics: ['Hash table']" PARAMETERS:
goal: Primary research objective (required)
libraryIDs: Context7 library IDs for docs ["puzpuzpuz/xsync"] (optional)
queries: Perplexity questions ["xsync benchmarks?"] (optional)
wikipediaTopics: Wikipedia articles ["Lock-free data structures"] (optional)
synthesize: LLM synthesis of findings (optional, default: false)
outputFile: Path to save TOON-compressed results (optional)
batchSize: Max parallel requests per source (optional, default: 5) REQUIRES: At least one of: context7, wikipedia, perplexity (optional: brave-search as fallback) NOTES: Gracefully degrades if MCPs unavailable. Large outputs auto-TOON-encode.
USAGE PATTERN:
// 1. Discover tools first
const api = await get_tool_api({serverName: 'perplexity'});
// 2. Call tools via proxy
const result = await servers['perplexity'].perplexity_ask({
messages: [{role: 'user', content: 'Your query'}]
});
// 3. Compress large results
console.log(TOON.encode(result));ERROR RECOVERY:
"Server not found" β list_servers shows available
"Tool undefined" β get_tool_api({serverName}) shows tools
"Timeout (60s)" β break into smaller operations
All results TOON-compressed by default.
Inputs: code (required).
execute_workflowB
USE WHEN you need research, K8s auditing, or incident analysis. Pre-built automation with parallel execution and automatic retries.
Inputs: workflowName (required), parameters.
get_tool_apiB
CALL BEFORE using a server to see exact parameter schemas. Returns all tools with their input requirements.
Inputs: serverName (required).
list_serversA
CALL FIRST to see what MCP servers are available. Shows loaded, lazy (on-demand), and disabled servers.
Inputs: no named parameters.
list_workflowsA
CALL FIRST to discover available automations before writing custom code. Returns workflow names, descriptions, and required parameters.
Inputs: no named parameters.
search_toolsA
USE WHEN you don't know which server has the tool you need. Searches across all loaded MCP servers by name/description.
Inputs: query (required), detailLevel, hydrateLazy, maxLazyServers.
set_project_rootC
Set project root for path resolution
Inputs: path (required).
suggest_approachA
CALL WHEN UNSURE whether to use execute_code, execute_workflow, or direct MCP.
Analyzes your task and recommends the most efficient approach. Considers: operation count, data size, existing workflows.
Inputs: task (required), data_type, estimated_operations.
usage_guideA
CALL WHEN confused about CodeModeTOON. Returns step-by-step guides for quickstart, troubleshooting, and best practices.
Inputs: section.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
TDQS
Scored across 9 tools
Most tools have distinct purposes, but execute_code and execute_workflow could be confused without reading descriptions. suggest_approach and usage_guide also overlap slightly in guiding the user.
All tool names follow a consistent verb_noun pattern in snake_case, with no mixing of conventions.
9 tools is appropriate for a meta-orchestration server, covering listing, searching, execution, and guidance without being overwhelming.
The tool surface covers key actions like executing code/workflows, discovering resources, and getting help. A tool to view workflow status or cancel executions would make it more complete.
Maintenance
Related MCP Connectors
A hosted MCP suite providing workflow primitives: web search, content fetching, compression, deduplication, cost/budget management, and agent memory pipelines.
LLM Orchestration Agent (Mcp)
Task management your AI agents can actually run. One line becomes a context-ready task over MCP.
MCP-first toolbox for agents: KV storage, auth, queue, and utility tools. Free in early access.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA state-based agent orchestration system that allows transitions between different states (IDLE, PLANNING, RESEARCHING, EXECUTING, REVIEWING, ERROR) while maintaining conversation context and providing state-specific prompts.2-
- AlicenseNot gradedqualityDmaintenanceA lightweight framework for building and orchestrating AI agents through the Model Context Protocol, enabling users to create scalable multi-agent systems using only configuration files.MIT
- AlicenseAqualityDmaintenanceA Model Context Protocol implementation that enables LLMs to execute complex, multi-step workflows combining tool usage with cognitive reasoning, providing structured, reusable paths through tasks with advanced control flow.914 npm29MIT
- AlicenseNot gradedqualityDmaintenanceA lightweight Claude MCP gateway that dynamically loads tools only when needed, cutting MCP token clutter by up to 95% and keeping your context lean, fast, and focused.7MIT