Skill: athola/nm-conserve-mcp-code-execution (version 1.0.2)

--- name: mcp-code-execution description: | Optimize multi-tool workflow chains via MCP server integration for processing large datasets, files, or complex pipelines version: 1.9.5 metadata: {"openclaw": {"homepage": "https://github.com/athola/claude-night-market/tree/master/plugins/conserve", "emoji": "\ud83e\udd9e", "requires": {"config": ["night-market.context-optimization", "night-market.token-conservation", "night-market.mcp-subagents", "night-market.mcp-patterns", "night-market.mcp-validation"]}}} source: claude-night-market source_plugin: conserve --- > **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin. ## Table of Contents - [Quick Start](#quick-start) - [When to Use](#when-to-use) - [Core Hub Responsibilities](#core-hub-responsibilities) - [Required TodoWrite Items](#required-todowrite-items) - [Step 1 – Assess Workflow](#step-1-assess-workflow-mcp-code-executionassess-workflow) - [Workflow Classification](#workflow-classification) - [MECW Risk Assessment](#mecw-risk-assessment) - [Step 2 – Route to Modules](#step-2-route-to-modules-mcp-code-executionroute-to-modules) - [Module Orchestration](#module-orchestration) - [Step 3 – Coordinate MECW](#step-3-coordinate-mecw-mcp-code-executioncoordinate-mecw) - [Cross-Module MECW Management](#cross-module-mecw-management) - [Step 4 – Synthesize Results](#step-4-synthesize-results-mcp-code-executionsynthesize-results) - [Result Integration](#result-integration) - [Module Integration](#module-integration) - [With Context Optimization Hub](#with-context-optimization-hub) - [Performance Skills Integration](#performance-skills-integration) - [Emergency Protocols](#emergency-protocols) - [Hub-Level Emergency Response](#hub-level-emergency-response) - [Success Metrics](#success-metrics) # MCP Code Execution Hub ## Quick Start ### Basic Usage \`\`\`bash # Run the main command python -m module_name # Show help python -m module_name --help \`\`\` **Verification**: Run with `--help` flag to confirm installation. ## When To Use - **Automatic**: Keywords: `code execution`, `MCP`, `tool chain`, `data pipeline`, `MECW` - **Tool Chains**: >3 tools chained sequentially - **Data Processing**: Large datasets (>10k rows) or files (>50KB) - **Context Pressure**: Current usage >25% of total window (proactive context management) > **MCP Tool Search (Claude Code 2.1.7+)**: When MCP tool descriptions exceed 10% of context, tools are automatically deferred and discovered via MCPSearch instead of being loaded upfront. This reduces token overhead by ~85% but means tools must be discovered on-demand. Haiku models do not support tool search. Configure threshold with `ENABLE_TOOL_SEARCH=auto:N` where N is the percentage. > **Subagent MCP Access Fix (Claude Code 2.1.30+)**: SDK-provided MCP tools are now properly synced to subagents. Prior to 2.1.30, subagents could not access SDK-provided MCP tools — workflows delegating MCP tool usage to subagents were silently broken. No workarounds needed on 2.1.30+. > **Claude.ai MCP Connectors (Claude Code 2.1.46+)**: Users logged into Claude Code with a claude.ai account may have additional MCP tools auto-loaded from claude.ai/settings/connectors. These tools contribute to the tool search threshold count. If workflows unexpectedly trigger tool search or context inflation, check `/mcp` for claude.ai-sourced connectors. Known reliability issue: connectors can silently disappear (GitHub #21817). > **MCP Prompt Cache Fix (Claude Code 2.1.70+)**: MCP servers with instructions connecting after the first turn no longer bust the prompt cache. Previously, a late-connecting MCP server would invalidate cached prompt prefixes, increasing token costs for the rest of the session. On 2.1.70+, prompt cache reuse is preserved regardless of when MCP servers connect. > **ToolSearch Reliability Fix (Claude Code 2.1.70+)**: Empty model responses after ToolSearch are fixed. The server was rendering tool schemas with system-prompt-style tags that could confuse models into stopping early. ToolSearch-heavy workflows (many deferred MCP tools) are now more reliable. ## When NOT To Use - Simple tool calls that don't chain - Context pressure is low and tools are fast ## Core Hub Responsibilities - Orchestrates MCP code execution workflow - Routes to appropriate specialized modules - Coordinates MECW compliance across submodules - Manages token budget allocation for submodules ## Required TodoWrite Items 1. `mcp-code-execution:assess-workflow` 2. `mcp-code-execution:route-to-modules` 3. `mcp-code-execution:coordinate-mecw` 4. `mcp-code-execution:synthesize-results` ## Step 1 – Assess Workflow (`mcp-code-execution:assess-workflow`) ### Workflow Classification ```python def classify_workflow_for_mecw(workflow): """Determine appropriate MCP modules and MECW strategy""" if has_tool_chains(workflow) and workflow.complexity == 'high': return { 'modules': ['mcp-subagents', 'mcp-patterns'], 'mecw_strategy': 'aggressive', 'token_budget': 600 } elif workflow.data_size > '10k_rows': return { 'modules': ['mcp-patterns', 'mcp-validation'], 'mecw_strategy': 'moderate', 'token_budget': 400 } else: return { 'modules': ['mcp-patterns'], 'mecw_strategy': 'conservative', 'token_budget': 200 } ``` **Verification:** Run the command with `--help` flag to verify availability. ### MECW Risk Assessment Delegate to mcp-validation module for detailed risk analysis: ```python def delegate_mecw_assessment(workflow): return mcp_validation_assess_mecw_risk( workflow, hub_allocated_tokens=self.token_budget * 0.5 ) ``` **Verification:** Run the command with `--help` flag to verify availability. ## Step 2 – Route to Modules (`mcp-code-execution:route-to-modules`) ### Module Orchestration ```python class MCPExecutionHub: def __init__(self): self.modules = { 'mcp-subagents': MCPSubagentsModule(), 'mcp-patterns': MCPatternsModule(), 'mcp-validation': MCPValidationModule() } def execute_workflow(self, workflow, classification): results = [] # Execute modules in optimal order for module_name in classification['modules']: module = self.modules[module_name] result = module.execute( workflow, mecw_budget=classification['token_budget'] // len(classification['modules']) ) results.append(result) return self.synthesize_results(results) ``` **Verification:** Run the command with `--help` flag to verify availability. ## Step 3 – Coordinate MECW (`mcp-code-execution:coordinate-mecw`) ### Cross-Module MECW Management - Monitor total context usage across all modules - Enforce 50% context rule globally - Coordinate external state management - Implement MECW emergency protocols ## Step 4 – Synthesize Results (`mcp-code-execution:synthesize-results`) ### Result Integration ```python def synthesize_module_results(module_results): """Combine results from MCP modules into structured output""" return { 'status': 'completed', 'token_savings': calculate_savings(module_results), 'mecw_compliance': verify_mecw_rules(module_results), 'hallucination_risk': assess_hallucination_prevention(module_results), 'results': consolidate_results(module_results) } ``` **Verification:** Run the command with `--help` flag to verify availability. ## Module Integration ### Available Modules - See `modules/mcp-coordination.md` for cross-module orchestration - See `modules/mcp-patterns.md` for common MCP execution patterns - See `modules/mcp-subagents.md` for subagent delegation strategies - See `modules/mcp-validation.md` for MECW compliance validation ### With Context Optimization Hub - Receives high-level MECW strategy from context-optimization - Returns detailed execution metrics and compliance data - Coordinates token budget allocation ### Performance Skills Integration - uses python-performance-optimization through mcp-patterns - Aligns with cpu-gpu-performance for resource-aware execution - validates optimizations maintain MECW compliance ## Emergency Protocols ### Hub-Level Emergency Response When MECW limits exceeded: 1. Delegates immediately to mcp-validation for risk assessment 2. Route to mcp-subagents for further decomposition 3. Apply compression through mcp-patterns 4. Return minimal summary to preserve context ## Success Metrics - **Workflow Success Rate**: >95% successful module coordination - **MECW Compliance**: 100% adherence to 50% context rule - **Token Efficiency**: Maintain >80% savings vs traditional methods - **Module Coordination**: <5% overhead for hub orchestration ## Troubleshooting ### Common Issues **Command not found** Ensure all dependencies are installed and in PATH **Permission errors** Check file permissions and run with appropriate privileges **Unexpected behavior** Enable verbose logging with `--verbose` flag

path: modules/mcp-coordination.md
content: # MCP Subagent Coordination Patterns

> **Version Note (Claude Code 2.1.14+)**: Parallel subagent execution is significantly more stable in Claude Code 2.1.14+, which fixed memory issues that could cause crashes when running parallel subagents. Earlier versions may experience heap out of memory errors with 3+ concurrent agents.

## Pipeline Coordination

Execute subagents in sequence with MECW monitoring:

```python
def coordinate_pipeline_subagents(subagents, input_data):
    """Execute subagents in sequence with MECW monitoring"""

    current_data = input_data
    results = []

    for subagent in subagents:
        # Monitor context before each subagent
        if estimate_context_usage() > get_mecw_limit() * 0.8:
            apply_emergency_compaction()

        # Execute subagent with minimal context
        subagent_result = subagent.execute_focused_task({
            'data': current_data,
            'context_limit': get_mecw_limit() * 0.4
        })

        current_data = subagent_result.get('next_input', current_data)
        results.append(subagent_result)

        # Store intermediate results externally
        store_intermediate_result(subagent.purpose, subagent_result)

    return results
```

### When to Use Pipeline
- **Sequential dependencies**: Each step depends on previous result
- **Linear workflows**: Clear progression from input to output
- **Token conservation**: Share minimal context between steps
- **Error isolation**: Failures don't cascade to all subagents

## Parallel Coordination

Execute multiple subagents simultaneously:

```python
def coordinate_parallel_subagents(subagents, input_data):
    """Execute multiple subagents simultaneously"""

    # Split input data for parallel processing
    data_splits = split_input_for_parallel(input_data, len(subagents))

    # Launch subagents with minimal context
    futures = []
    for subagent, data_split in zip(subagents, data_splits):
        future = subagent.execute_async({
            'data': data_split,
            'context_limit': get_mecw_limit() // len(subagents)
        })
        futures.append(future)

    # Collect results with external storage
    results = []
    for future in futures:
        result = future.get_result()
        store_external_result(result.subagent_id, result.data)
        results.append(result)

    return synthesize_parallel_results(results)
```

### When to Use Parallel
- **Independent tasks**: No dependencies between subagents
- **Time-sensitive**: Need faster completion
- **Resource distribution**: Share MECW budget across subagents
- **Diverse expertise**: Different domains being processed

## Hybrid Coordination

Combine pipeline and parallel patterns:

```python
def coordinate_hybrid_subagents(phase_groups):
    """Execute phases sequentially, subagents within each phase in parallel"""

    all_results = []

    for phase in phase_groups:
        # Execute subagents in this phase in parallel
        phase_results = coordinate_parallel_subagents(
            phase.subagents,
            phase.input_data
        )

        # Synthesize phase results before next phase
        synthesized = synthesize_phase_results(phase_results)
        all_results.append(synthesized)

        # Pass synthesized results to next phase
        if phase.has_next():
            phase.next().set_input_data(synthesized)

    return combine_phase_results(all_results)
```

### When to Use Hybrid
- **Complex workflows**: Mix of sequential and parallel steps
- **Phase dependencies**: Groups of parallel tasks with inter-group dependencies
- **Resource optimization**: Balance speed (parallel) with coordination (sequential)

## Emergency Patterns

### Context Overflow Recovery

```python
def handle_context_overflow(subagent, current_state):
    """Emergency handling when subagent exceeds MECW limits"""

    # 1. Immediately store current state externally
    store_emergency_state(subagent.id, current_state)

    # 2. Split task into smaller sub-subagents
    subtasks = emergency_decompose(current_state.task)

    # 3. Delegate to focused sub-subagents
    subresults = []
    for subtask in subtasks:
        sub_subagent = create_minimal_subagent(
            subtask,
            max_tokens=50  # Ultra-conservative
        )
        subresults.append(sub_subagent.execute())

    # 4. Synthesize minimal summary
    return create_minimal_synthesis(subresults)
```

### Coordination Failure Recovery

```python
def recover_from_coordination_failure(failed_subagent, error):
    """Handle subagent execution failures gracefully"""

    # Log failure for debugging
    log_subagent_failure(failed_subagent.id, error)

    # Attempt recovery strategies
    if error.type == "timeout":
        return retry_with_reduced_scope(failed_subagent)
    elif error.type == "context_overflow":
        return handle_context_overflow(failed_subagent, error.state)
    elif error.type == "validation_failure":
        return skip_and_mark_for_review(failed_subagent)
    else:
        return escalate_to_parent(failed_subagent, error)
```

## Best Practices

### Context Budget Allocation

```python
# Pipeline: Progressive budget allocation
def allocate_pipeline_budgets(subagents, total_budget):
    base_budget = total_budget // len(subagents)
    budgets = []

    for i, subagent in enumerate(subagents):
        # Later stages get slightly more budget for synthesis
        budget = base_budget * (1 + 0.1 * (i / len(subagents)))
        budgets.append(min(budget, total_budget * 0.4))  # Cap at 40%

    return budgets

# Parallel: Equal distribution
def allocate_parallel_budgets(subagents, total_budget):
    return [total_budget // len(subagents)] * len(subagents)
```

### Result Validation

```python
def validate_subagent_results(results):
    """Ensure all subagent results meet quality standards"""

    for result in results:
        # Check MECW compliance
        if result.tokens_used > result.allocated_budget:
            raise MecwViolation(f"{result.id} exceeded budget")

        # Validate external storage
        if not verify_external_storage(result.external_location):
            raise StorageFailure(f"Missing external data for {result.id}")

        # Check result completeness
        if result.status != "completed":
            log_incomplete_result(result)

    return True
```

## Monitoring & Debugging

### Coordination Metrics

```python
def track_coordination_metrics(coordination_session):
    return {
        'total_subagents': len(coordination_session.subagents),
        'parallel_groups': count_parallel_groups(coordination_session),
        'pipeline_depth': calculate_pipeline_depth(coordination_session),
        'context_efficiency': calculate_context_efficiency(coordination_session),
        'failure_rate': coordination_session.failures / coordination_session.total,
        'average_subagent_time': calculate_average_time(coordination_session)
    }
```

### Debug Logging

```python
def log_coordination_event(event_type, subagent_id, details):
    """Structured logging for debugging coordination issues"""

    log_entry = {
        'timestamp': datetime.now().isoformat(),
        'event': event_type,
        'subagent': subagent_id,
        'details': details,
        'context_snapshot': capture_context_state()
    }

    append_to_coordination_log(log_entry)
```


path: modules/mcp-patterns.md
content: ---
name: mcp-patterns
description: Apply Model Context Protocol patterns for tool chain transformation
  and efficient code execution.
location: plugin
token_budget: 200  # Optimized pattern application
progressive_loading: true
dependencies:
  hub: [mcp-code-execution]
  modules: []
---
# MCP Patterns Module
## Quick Start
Transform tool chains into MCP code execution patterns
for optimized token savings.

## When to Use
- **Automatic**: Keywords: `pattern`, `transform`, `optimize`, `code execution`
- **Tool Chains**: Multiple sequential tool operations
- **Performance Issues**: Slow response times due to tool overhead
- **Token Efficiency**: Need to reduce intermediate context accumulation

## Tool Reference
All patterns use the standard `tools/extracted_tool.py` interface:

```bash
# Basic usage
python tools/extracted_tool.py --input data.json --output results.json

# Advanced options
python tools/extracted_tool.py --input data.json --verbose --output results.json
```

## Required TodoWrite Items
1. `mcp-patterns:identify-tool-chains`
2. `mcp-patterns:apply-transformations`
3. `mcp-patterns:optimize-execution`
4. `mcp-patterns:validate-efficiency`
## Core MCP Patterns
### Before: Tool Chain (High Cost)
```python
# Multiple tool calls, each adds context
data = fetch_database_data()      # +5k tokens
filtered = filter_records(data)   # +3k tokens
transformed = standardize(data)   # +4k tokens
analyzed = calculate_insights(data) # +6k tokens
# Total: 18k+ tokens in intermediate results
```

### After: MCP Code Execution (95% Savings)
```python
# Single execution, minimal context
with mcp_code_execution() as exec:
    result = exec.process_pipeline(data, [
        ('fetch', fetch_database_data),
        ('filter', filter_records),
        ('transform', standardize),
        ('analyze', calculate_insights)
    ])
# Total: ~750 tokens (95% reduction)
```
## Step 1 – Identify Tool Chains (`mcp-patterns:identify-tool-chains`)
### Pattern Detection
Uses the standard tool interface (see Tool Reference above).

### Conversion Triggers
- **High Impact**: >3 tool chains, >10k records, >50KB files
- **Medium Impact**: 2-3 tools, 1-10k records, 10-50KB files
- **Low Impact**: Single operations, <1k records, <10KB files
## Step 2 – Apply Transformations (`mcp-patterns:apply-transformations`)
### Transformation Templates

#### Data Processing Pipeline
Uses the standard tool interface (see Tool Reference above).

#### Analysis Workflow
Uses the standard tool interface (see Tool Reference above).

#### Report Generation
Uses the standard tool interface (see Tool Reference above).

### Progressive Tool Loading
Uses the standard tool interface (see Tool Reference above).
## Step 3 – Optimize Execution (`mcp-patterns:optimize-execution`)
### Execution Optimization Patterns

#### Source-Side Filtering
Uses the standard tool interface (see Tool Reference above).

#### Batch Processing
Uses the standard tool interface (see Tool Reference above).

#### Context-Aware Execution
Uses the standard tool interface (see Tool Reference above).
## Step 4 – Validate Efficiency (`mcp-patterns:validate-efficiency`)
### Efficiency Metrics
Uses the standard tool interface (see Tool Reference above).

### Success Criteria
- **Token Savings**: >50% for large operations
- **Response Time**: >30% improvement
- **Functionality**: 100% preservation
- **MECW Compliance**: Context usage <50% of total window
## Pattern Library
### Available Patterns
- **Data Processing Pipeline**: Sequential data transformation
- **Analysis Workflow**: Multi-step analysis with progressive loading
- **Report Generation**: Template-based document creation
- **Monitoring Pipeline**: Real-time data processing and alerting

### Anti-Patterns to Avoid
- Simple single-tool operations
- Real-time requirements needing immediate response
- Security contexts requiring full intermediate visibility
- Debugging scenarios requiring step-by-step results

## Success Metrics
- **Pattern Application Rate**: >80% of applicable workflows transformed
- **Token Efficiency**: >70% average token savings
- **MECW Compliance**: 100% of patterns stay under 50% context limit
- **Performance Improvement**: >40% average speed enhancement


path: modules/mcp-subagents.md
content: ---
name: mcp-subagents
description: Create focused, single-purpose subagents for complex workflow
  decomposition with MECW compliance.
location: plugin
token_budget: 80  # Optimized with modules
progressive_loading: true
dependencies:
  hub: [mcp-code-execution]
  modules: [mcp-patterns, mcp-coordination]
---

# MCP Subagents Module

## Quick Start
Decompose complex workflows into focused subagents that operate within MECW limits.

## Critical: Base Overhead Reality

**Every subagent inherits ~8-16k tokens of system context** (tool definitions,
permissions, system prompts) regardless of your instruction length.

### The Efficiency Formula

```
Efficiency = Task_Reasoning_Tokens / (Task_Reasoning_Tokens + Base_Overhead)
```

| Task Reasoning | + Overhead (~8k) | Efficiency | Verdict |
|---------------|------------------|------------|---------|
| 50 tokens | 8,050 | **0.6%** | ❌ Parent does it |
| 500 tokens | 8,500 | **5.9%** | ❌ Parent does it |
| 2,000 tokens | 10,000 | **20%** | ⚠️ Borderline |
| 5,000 tokens | 13,000 | **38%** | ✅ Use subagent |
| 15,000 tokens | 23,000 | **65%** | ✅ Definitely use |

**Minimum threshold**: Task should require **>2,000 tokens of reasoning** to justify subagent overhead.

## CRITICAL: Check BEFORE Invoking

**The complexity check MUST happen BEFORE calling the Task tool.**

```
❌ WRONG: Invoke subagent → Subagent bails → 8k tokens wasted
✅ RIGHT: Parent checks → Skip invocation → 0 tokens spent
```

### Pre-Invocation Checklist

Before ANY Task invocation:
1. Can I do this in one command? → Do it directly
2. Is reasoning < 500 tokens? → Do it directly
3. Check agent's ⚠️ PRE-INVOCATION CHECK in description → Follow it

## SDK MCP Tool Access Fix (Claude Code 2.1.30+)

**Critical fix**: Prior to 2.1.30, subagents could not access SDK-provided MCP tools because they were not synced to the shared application state. This meant any workflow delegating MCP tool usage to subagents was **silently broken** — the subagent would simply not have the MCP tools available.

**Now fixed**: MCP tools are properly synced across subagent boundaries. No workarounds needed.

## Claude.ai MCP Connector Sync (Claude Code 2.1.46+)

Claude.ai MCP connectors (configured at
claude.ai/settings/connectors) are now available in
Claude Code. These tools should sync to subagents via
the same mechanism as the 2.1.30+ SDK MCP fix, but this
has not been independently verified for claude.ai-sourced
connectors. If subagents report missing MCP tools that
are visible in the parent's `/mcp`, check whether the
tools originate from claude.ai connectors.

To opt out of claude.ai MCP servers entirely (2.1.63+),
set `ENABLE_CLAUDEAI_MCP_SERVERS=false`. This prevents
claude.ai-configured connectors from loading in Claude
Code sessions. Useful for controlled environments where
only locally-configured MCP servers should be available.

## Sub-Agent Spawning Restrictions (Claude Code 2.1.33+)

Agent `tools` frontmatter now supports `Task(agent_type)` to restrict which sub-agents can be spawned. This provides governance over delegation chains and prevents uncontrolled spawning.

```yaml
tools:
  - Read
  - Bash
  - Task(research-agent)
  - Task(testing-agent)
```

Use for orchestrator agents that should only delegate to specific workers. Combined with the pre-invocation complexity check, this ensures both *whether* and *to whom* delegation occurs is controlled.

## Background Agent MCP Restriction (Claude Code 2.1.49+)

**Critical**: Agents launched with `background: true` **cannot use MCP tools**. This means any subagent that requires MCP tool access (code execution servers, external service connectors, SDK-provided tools) must NOT be backgrounded. If you need both parallel execution and MCP access, use foreground `Task` invocations or `isolation: worktree` without the `background` flag.

## When to Use
- **Automatic**: Keywords: `subagent`, `decompose`, `break down`, `modular`
- **Complex Workflows**: Multi-step processes requiring specialization
- **MECW Pressure**: When single approach would exceed 50% context rule
- **Task Specialization**: Different phases require different expertise
- **NOT for simple tasks**: Parent should execute directly if reasoning < 2k tokens

## Required TodoWrite Items
1. `mcp-subagents:analyze-complexity`
2. `mcp-subagents:create-subagents`
3. `mcp-subagents:coordinate-execution`
4. `mcp-subagents:synthesize-results`

## Subagent Design Principles

### MECW-Compliant Structure
- Each subagent operates within strict token limits (default: 125 tokens)
- Dynamic budget allocation based on task complexity
- External state management for intermediate results
- Progressive loading to minimize context pressure

See [MCP Patterns](mcp-patterns.md) for implementation examples.

## Workflow Decomposition

### Step 1 – Analyze Complexity
- Assess workflow complexity factors (tool chain length, data volume, context pressure)
- Determine optimal decomposition strategy (sequential, parallel, or single)
- Plan coordination pattern (pipeline, parallel, or direct)

### Step 2 – Create Subagents
- Use factory patterns for common subagent types
- Configure MECW-compliant token budgets
- Set up external storage for intermediate results

### Step 3 – Coordinate Execution
- Monitor context usage before each subagent
- Execute with minimal context sharing
- Store intermediate results externally

### Step 4 – Synthesize Results
- Load external results within MECW limits
- Combine results with token-aware synthesis
- Validate MECW compliance and efficiency

## Advanced Patterns

For detailed coordination patterns, code examples, and troubleshooting:
- **[Coordination Patterns](mcp-coordination.md)** - Pipeline and parallel orchestration
- **[Implementation Patterns](mcp-patterns.md)** - Factory patterns and code examples

## Success Metrics
- **Subagent Efficiency**: >90% complete within token budget
- **MECW Compliance**: 100% adherence to 50% context rule
- **Decomposition Quality**: <5% need for emergency re-decomposition
- **Synthesis Accuracy**: >95% preservation of original insights


path: modules/mcp-validation.md
content: ---
name: mcp-validation
description: Monitor MECW compliance and hallucination prevention
  with validation checks.
location: plugin
token_budget: 150  # Streamlined validation focus
progressive_loading: true
dependencies:
  hub: [mcp-code-execution]
  modules: []
---

# MCP Validation Module

## Quick Start
Monitor MECW compliance and hallucination prevention for MCP workflows
with real-time risk assessment.

## When to Use
- **Automatic**: Keywords: `validate`, `check`, `monitor`, `compliance`, `MECW`
- **Pre-Execution**: Before running MCP workflows
- **Post-Execution**: After completing transformations
- **Continuous Monitoring**: During long-running workflows

## Required TodoWrite Items
1. `mcp-validation:assess-mecw-risk`
2. `mcp-validation:monitor-compliance`
3. `mcp-validation:validate-hallucination-prevention`
4. `mcp-validation:generate-alerts`

## MECW Risk Assessment

### Context Risk Analysis
- **Critical Risk**: Context usage >50% (very high hallucination risk)
- **High Risk**: Current usage >MECW threshold (70-90% risk)
- **Low Risk**: Context under threshold (<20% risk)

### Task-Specific MECW Thresholds
- Simple data processing: 250 tokens
- Tool chain conversion: 375 tokens
- Complex analysis: 125 tokens
- Report generation: 150 tokens

## Step 1 – Assess MECW Risk (`mcp-validation:assess-mecw-risk`)

### Risk Indicators
Monitor context pressure, MECW violations, response consistency,
fact coherence, and hallucination patterns.

### Early Warning System
- **Warning**: Context pressure >40% (60-80% hallucination probability)
- **Critical**: MECW violations detected (90% to 100% probability)
- **Safe**: All indicators normal (<20% probability)

## Step 2 – Monitor Compliance (`mcp-validation:monitor-compliance`)

### Compliance Validation
- **Context Usage**: Must stay under 50% of total window
- **Hallucination Rate**: Must stay under 20%
- **Token Efficiency**: Must maintain >50% savings
- **MECW Adherence**: Follow task-specific thresholds

### Continuous Tracking
Track compliance history, violation counts, and trend analysis
to identify patterns and prevent future issues.

## Step 3 – Validate Hallucination Prevention
(`mcp-validation:validate-hallucination-prevention`)

### Hallucination Detection
Check for factual inconsistency, logical contradictions,
confidence mismatch, and context drift.

### Prevention Measurement
- **Target**: >80% reduction in hallucination rates
- **MECW Impact**: Context reduction to under 50%
- **Accuracy Preservation**: Maintain or improve baseline accuracy

## Step 4 – Generate Alerts (`mcp-validation:generate-alerts`)

### Alert Levels
- **Critical**: Immediate action required, execution stop
- **Warning**: Review recommended, monitoring increased
- **Info**: Normal operation, continue monitoring

### Emergency Response
For critical violations: stop execution, compact context, migrate state,
decompose into subagents.

## Success Metrics

### Validation Criteria
- **MECW Compliance Rate**: >95% of executions under 50% context
- **Hallucination Prevention**: >80% reduction in rates
- **Early Warning Accuracy**: >90% of risks correctly predicted
- **Response Time**: <5% overhead from validation

## Integration Points

### With MCP Code Execution Hub
- Receives workflow data for validation
- Returns compliance assessments and recommendations
- Coordinates emergency response procedures

### With Context Optimization
- Shares MECW risk assessments
- Coordinates validation strategies
- Provides compliance metrics for optimization


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)