# MCP Code Mode - Research & Integration Analysis

**Date:** November 20, 2025  
**Status:** Research Complete - Integration Recommended  
**Repository:** https://github.com/draphonix/mcp-code-mode

---

## Executive Summary

MCP Code Mode is a **code execution MCP server** that enables AI agents to write Python code that orchestrates MCP tool calls programmatically. This solves critical limitations in traditional MCP implementations: context window bloat, latency, token costs, and composability issues.

**Key Innovation:** Instead of making sequential MCP tool calls, the LLM writes a single Python script that orchestrates all operations internally, calling MCP tools as needed.

**Integration Value for OpenCodeKit:**

- ✅ Reduces token usage (single code generation vs. multiple tool calls)
- ✅ Enables complex multi-step workflows in one execution
- ✅ Better composability (code can orchestrate tools programmatically)
- ✅ Lower latency (one execution vs. sequential tool calls)

---

## Architecture Overview

### Traditional MCP Flow (Current OpenCodeKit)

```
User Request
    ↓
Claude calls tool1 → MCP Server → Result
    ↓
Claude calls tool2 → MCP Server → Result
    ↓
Claude calls tool3 → MCP Server → Result
    ↓
Response (3+ round trips, high token cost)
```

### Code Mode Flow (Proposed)

```
User Request
    ↓
Claude writes Python code (with access to MCP tools)
    ↓
Code Mode Server executes code
    ├─ Calls tool1 internally
    ├─ Calls tool2 internally
    └─ Calls tool3 internally
    ↓
Response (1 execution, lower token cost)
```

---

## Core Components

### 1. FastMCP Server (`executor_server.py`)

Exposes `execute_code` tool via MCP protocol:

```python
@mcp.tool
async def execute_code(code: str):
    # Validates code against guardrails
    # Executes in Local Python Executor (default)
    result = await executor.run(code)
    return result
```

**Key Features:**

- Sandboxed execution (Pyodide or Local Python Executor)
- Guardrails: 8k char/400 line limits, import allowlist, no dangerous tokens
- Timeout enforcement
- Structured error handling

### 2. MCP Server Manager (`mcp_manager.py`)

Configuration-driven tool discovery:

```json
// mcp_servers.json
{
  "servers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"],
      "description": "Local file system operations"
    }
  }
}
```

**Workflow:**

1. Reads `mcp_servers.json`
2. Connects to configured MCP servers
3. Calls `list_tools()` on each server
4. Converts to DSpy tools
5. Makes tools available to code execution environment

### 3. Tool Schema Formatter (`tool_formatter.py`)

Formats discovered MCP tools into LLM-readable documentation:

```
Available Tools:
- read_file(path: str) → str
  Read file contents from filesystem

- write_file(path: str, content: str) → None
  Write content to file
```

This context is passed to the LLM **before** code generation, so it knows what tools exist.

### 4. Code Execution Agent (`agent.py`)

DSpy-based agent using `ProgramOfThought` or `CodeAct`:

```python
class CodeExecutionAgent:
    def __init__(self, tools, tool_context):
        self.tools = tools  # Callable MCP tools
        self.tool_context = tool_context  # LLM documentation

    def generate_code(self, task: str) -> str:
        # LLM generates Python code with access to tools
        pass
```

---

## Information Flow

```
1. mcp_servers.json (Defines MCP servers)
   ↓
2. MCPServerManager.initialize()
   ├─ Connect to configured servers
   ├─ Call list_tools() on each
   └─ Convert to DSpy tools
   ↓
3. ToolSchemaFormatter.format_for_llm()
   └─ Creates readable documentation
   ↓
4. CodeExecutionAgent
   └─ Stores both callable tools and schemas
   ↓
5. Agent Generation (LLM)
   └─ Writes Python code using available tools
   ↓
6. Code Execution
   └─ Code runs in sandbox, calling MCP tools via tool bridge
```

---

## Why Code Mode Solves Problems

### Problem 1: Context Window Bloat

**Traditional MCP:**

- Every tool definition consumes tokens
- 100 tools = thousands of tokens used per request
- Limits scalability

**Code Mode:**

- Tool schemas passed as input field (outside main context)
- LLM only sees tool documentation when generating code
- Context window used for actual task logic

### Problem 2: Token Cost

**Traditional MCP:**

- Multiple back-and-forth tool calls
- Each call = full context + response tokens
- 5 tool calls = 5x token cost

**Code Mode:**

- Single code generation
- All tool calls happen internally during execution
- 1x token cost (code generation only)

### Problem 3: Latency

**Traditional MCP:**

- Sequential tool invocations
- Each call waits for response before next
- Cumulative delays

**Code Mode:**

- Single execution
- Tools called programmatically in parallel if possible
- Lower total latency

### Problem 4: Composability

**Traditional MCP:**

- Complex workflows = many discrete steps
- Hard to orchestrate loops, conditionals, error handling

**Code Mode:**

- LLM writes Python code with full language features
- Loops, conditionals, error handling, data transformations
- Natural composability

---

## Integration Options for OpenCodeKit

### Option 1: Custom Command Integration (Recommended)

Add `/execute-code` command that uses mcp-code-mode server:

```markdown
# @.opencode/command/execute-code.md

---

## description: Execute complex workflows via code generation

Use `code-mode` MCP server to write and execute Python code that orchestrates MCP tools.

**When to Use:**

- Complex multi-step workflows (≥5 tool calls)
- Need loops, conditionals, or data transformations
- Want lower token cost for repetitive operations
- Parallel tool execution needed

**Workflow:**

1. Analyze task complexity
2. Generate Python code using available MCP tools
3. Execute code via mcp-code-mode server
4. Return structured result
```

### Option 2: Agent-Level Integration

Add code execution capability to `@build` or `@rush` agents:

```yaml
# @.opencode/agent/build.md
tools:
  bash: true
  edit: true
  # ... existing tools
  code-mode*: true # Enable code execution via MCP
```

### Option 3: Skill-Based Integration

Create skill at `@.opencode/skills/specialized/code-mode/`:

```markdown
# @.opencode/skills/specialized/code-mode/SKILL.md

---

name: code-mode
description: Code execution for complex MCP tool orchestration

---

Use when:

- Task requires 5+ sequential tool calls
- Need programmatic control (loops, conditionals)
- Want to reduce token costs
- Complex data transformations needed
```

---

## Implementation Plan

### Phase 1: Setup (1-2 hours)

1. **Install mcp-code-mode:**

   ```bash
   cd ~/.config/opencode/mcp-servers/
   git clone https://github.com/draphonix/mcp-code-mode.git
   cd mcp-code-mode
   python3.11 -m venv .venv
   source .venv/bin/activate
   pip install -e .[dev]
   ```

2. **Configure MCP servers:**

   ```bash
   # Edit mcp_servers.json to include OpenCode MCP tools
   # (filesystem, gkg, backlog, memory, etc.)
   ```

3. **Test server:**
   ```bash
   python -m mcp_code_mode.executor_server
   python scripts/debug_executor.py
   ```

### Phase 2: OpenCodeKit Integration (2-3 hours)

1. **Add to MCP config:**

   ```json
   // ~/.config/opencode/mcp.json or project-local config
   {
     "mcpServers": {
       "code-mode": {
         "command": "python",
         "args": ["-m", "mcp_code_mode.executor_server"],
         "env": {
           "OPENAI_API_KEY": "${OPENAI_API_KEY}"
         }
       }
     }
   }
   ```

2. **Create custom command:**

   ```bash
   # @.opencode/command/code-execute.md
   # (see Option 1 above)
   ```

3. **Update agent prompts:**
   - Add guidance on when to use code execution
   - Document available MCP tools in code context
   - Add examples of code-mode workflows

### Phase 3: Testing & Validation (1-2 hours)

1. **Test workflows:**
   - Multi-file refactoring (read → transform → write)
   - Complex search patterns (grep → filter → aggregate)
   - Parallel tool execution scenarios

2. **Performance benchmarking:**
   - Token usage comparison (traditional vs. code mode)
   - Latency comparison
   - Success rate measurement

3. **Documentation:**
   - Add examples to `@.opencode/memory/`
   - Update `AGENTS.md` with code-mode guidance
   - Create workflow templates

---

## Security Considerations

### Guardrails (Built-in)

✅ **Import Allowlist:**

- Only safe modules: `json`, `math`, `re`, `datetime`, `collections`, etc.
- Blocks: `subprocess`, `os.system`, `eval`, `exec`, `__import__`

✅ **Size Limits:**

- Max 8k characters
- Max 400 lines

✅ **Token Blocklist:**

- Dangerous tokens rejected: `subprocess`, `eval`, `exec`, `compile`

✅ **Timeout Enforcement:**

- Configurable execution timeout
- Prevents infinite loops

### Additional Hardening

⚠️ **Local Python Executor:**

- Default executor runs in same process as server
- Network I/O allowed (needed for MCP tool calls)
- Trade-off: flexibility vs. strict sandboxing

🔒 **Pyodide Sandbox (Optional):**

- WebAssembly-based isolation
- Strict sandboxing
- Limitation: Network I/O restrictions may break MCP tool calls
- Enable via: `MCP_EXECUTOR=pyodide`

**Recommendation:** Use default Local Python Executor with guardrails for OpenCodeKit integration.

---

## Benefits for OpenCodeKit Architecture

### 1. Fits Two-Layer Architecture

```
Memory (Persistent)    → Backlog (Multi-session) → Code Execution (Tool Orchestration)
@.opencode/memory/       @backlog/tasks/           mcp-code-mode server
```

Code-mode complements existing architecture:

- **Memory:** Stores code patterns and learnings
- **Backlog:** Tracks multi-session tasks
- **Code Execution:** Orchestrates MCP tools efficiently

### 2. Enhances Agent Capabilities

**@build agent:**

- Can delegate complex tool orchestration to code-mode
- Reduces token usage for repetitive operations
- Maintains observability (code is visible)

**@researcher agent:**

- Multi-source research via code (parallel API calls)
- Data aggregation and transformation
- Lower latency for complex queries

**@plan agent:**

- Generate executable plans as Python code
- Facts/Guesses/Plans → executable workflow

### 3. Improves Custom Commands

**Example: `/fix/hard` command enhancement:**

```python
# Traditional: Multiple sequential tool calls
gkg_search → gkg_read → grep → edit → bash (test)

# Code Mode: Single execution
code = """
# 1. Find definitions
defs = gkg_search_codebase_definitions(["AuthService"])

# 2. Read implementations
for d in defs:
    code = gkg_read_definitions([d.name])

    # 3. Apply fix pattern
    if "vulnerable_pattern" in code:
        fixed = apply_security_fix(code)
        write_file(d.file_path, fixed)

# 4. Run tests
result = bash("pytest tests/test_auth.py")
return result
"""
```

---

## Risks & Mitigations

### Risk 1: Code Generation Quality

**Risk:** LLM generates incorrect or inefficient code  
**Mitigation:**

- Guardrails prevent dangerous operations
- Structured error handling in executor
- Validation before execution
- Iterative refinement (agent can retry)

### Risk 2: Debugging Complexity

**Risk:** Harder to debug code execution vs. direct tool calls  
**Mitigation:**

- Code is visible in response
- Structured error messages with traceback
- Can inspect intermediate results
- Git commits show code used

### Risk 3: Learning Curve

**Risk:** Users/agents need to understand code-mode paradigm  
**Mitigation:**

- Clear documentation and examples
- Start with simple use cases
- Gradual adoption (optional tool)
- Template code snippets in memory

### Risk 4: Dependency Management

**Risk:** mcp-code-mode has Python 3.11+ and Node.js dependencies  
**Mitigation:**

- Isolated installation in `~/.config/opencode/mcp-servers/`
- Virtual environment for dependencies
- Clear setup documentation
- Optional integration (not required for core functionality)

---

## Recommendations

### Immediate Actions (Phase 1)

1. ✅ **Install and test mcp-code-mode locally**
   - Verify compatibility with OpenCodeKit MCP tools
   - Test with filesystem, gkg, backlog servers

2. ✅ **Create proof-of-concept integration**
   - Add `/execute-code` custom command
   - Document in `@.opencode/memory/`

3. ✅ **Benchmark performance**
   - Compare token usage: traditional vs. code-mode
   - Measure latency for multi-step workflows

### Short-term (Phase 2)

1. **Create specialized skill**
   - `@.opencode/skills/specialized/code-mode/`
   - Usage guidelines and examples

2. **Update agent prompts**
   - Add code-mode awareness to @build, @researcher
   - Document when to delegate to code execution

3. **Build workflow templates**
   - Common patterns (refactoring, search, analysis)
   - Store in `@.opencode/memory/_templates/`

### Long-term (Phase 3)

1. **Integration with backlog**
   - Complex tasks auto-generate executable code
   - Store code in backlog task notes

2. **Memory integration**
   - Learn successful code patterns
   - Reuse proven code snippets

3. **Custom DSpy modules**
   - OpenCodeKit-specific code generation signatures
   - Domain-specific tool orchestration patterns

---

## Success Metrics

### Quantitative

- **Token Reduction:** Target 40-60% reduction for complex workflows (≥5 tool calls)
- **Latency:** Target 30-50% reduction vs. sequential tool calls
- **Success Rate:** Target >90% for code execution (guardrails + validation)

### Qualitative

- **Agent Capability:** Can handle more complex workflows without context overflow
- **Developer Experience:** Easier to orchestrate multi-step operations
- **Code Quality:** Generated code is readable and maintainable

---

## References

### Documentation

- **Repository:** https://github.com/draphonix/mcp-code-mode
- **DSpy:** https://dspy.ai
- **Model Context Protocol:** https://modelcontextprotocol.io
- **FastMCP:** https://github.com/jlowin/fastmcp

### Related OpenCodeKit Files

- `@.opencode/AGENTS.md` - Agent system architecture
- `@.opencode/INTEGRATION_OVERVIEW.md` - Two-layer architecture
- `@.opencode/skills/` - Skill system documentation

---

## Next Steps

1. **Validate approach:** Discuss with team/community
2. **Proof of concept:** Implement Phase 1 integration
3. **Measure results:** Benchmark token/latency improvements
4. **Document patterns:** Create templates and examples
5. **Gradual rollout:** Optional tool → recommended for complex tasks → default for workflows

---

**Status:** Research complete, integration recommended  
**Confidence:** High - Architecture aligns well with OpenCodeKit patterns  
**Risk Level:** Low - Optional integration, strong guardrails, clear value proposition
