Skip to main content

Coding Module - MCP Tool Specification

This document defines the Model Context Protocol (MCP) tools for the coding module, which provides comprehensive code execution, sandboxing, review, monitoring, and debugging capabilities.

Implementation Status​

The following tools are implemented in mcp_tools.py via the @mcp_tool decorator:

Implemented Tool FunctionCorresponds to Spec
code_executecoding_execute_code (simplified interface)
code_list_languages(not in original spec)
code_review_filecoding_analyze_file (simplified interface)
code_review_projectcoding_analyze_project (simplified interface)
code_debugcoding_debug_code (simplified interface)

The following tools are specified but not yet implemented in mcp_tools.py:

  • coding_check_quality_gates -- planned
  • coding_monitor_execution -- planned
  • coding_generate_report -- planned
  • coding_run_in_docker -- planned

General Considerations for Coding Tools​

  • Dependencies: Requires logging_monitoring module. Docker is required for sandboxed execution. Static analysis tools (ruff, ty) are required for code review.
  • Initialization: No module-level initialization required. Docker availability is checked at execution time.
  • Error Handling: Errors are logged via logging_monitoring. Tools return structured error objects with status codes.
  • Security: All code execution occurs in isolated Docker containers with resource limits. File operations are sandboxed.

Tool: coding_execute_code​

1. Tool Purpose and Description​

Executes source code in a sandboxed Docker environment with resource limits and timeout controls. Supports multiple programming languages and provides secure, isolated execution for untrusted code.

2. Invocation Name​

coding_execute_code

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
languageenum["python", "javascript", "java", "cpp", "c", "go", "rust", "bash"]YesProgramming language of the code"python"
codestringYesSource code to execute"print('Hello, World!')"
stdinstringNoStandard input to provide to the program"test input"
timeoutintegerNoMaximum execution time in seconds (1-300). Default: 3060
session_idstringNoSession identifier for persistent environments"session-abc123"

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
stdoutstringStandard output from the program"Hello, World!\n"
stderrstringStandard error output""
exit_codeintegerProcess exit code (0 for success)0
execution_timefloatActual execution time in seconds0.234
statusenum["success", "timeout", "error", "setup_error"]Execution status"success"
error_messagestringDetailed error message if status is not "success"null

5. Error Handling​

  • setup_error: Docker unavailable, invalid language, or code validation failed
  • timeout: Execution exceeded the specified timeout
  • error: Runtime error during code execution
  • Return Format: Always returns the structured output; errors reflected in status and error_message fields

6. Idempotency​

  • Idempotent: Partially
  • Explanation: Execution of deterministic code produces consistent results. Code with side effects (file I/O, network, random) may produce different outputs. Session-based execution maintains state between calls.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_execute_code",
"arguments": {
"language": "python",
"code": "import sys\ndata = input()\nprint(f'Received: {data}')\nprint(f'Python version: {sys.version}')",
"stdin": "Hello from stdin",
"timeout": 30
}
}

Example with session persistence:

{
"tool_name": "coding_execute_code",
"arguments": {
"language": "python",
"code": "x = 42",
"session_id": "my-session"
}
}

8. Security Considerations​

  • Input Validation: Language validated against supported list. Code is not validated for malicious content but executed in isolation.
  • Permissions: Code runs in Docker container with restricted permissions (no network by default, limited filesystem access).
  • Data Handling: All execution artifacts are cleaned up after completion.
  • Resource Limits: Memory, CPU, and execution time are strictly limited via Docker.
  • File Paths: Temporary files created in isolated directories; cleaned up on completion.
  • Network Isolation: Containers have no network access by default.

Tool: coding_analyze_file​

1. Tool Purpose and Description​

Performs comprehensive static analysis on a single source file, including linting, type checking, complexity analysis, and security scanning. Returns detailed findings with severity levels and fix suggestions.

2. Invocation Name​

coding_analyze_file

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
file_pathstringYesPath to the file to analyze"./src/module.py"
analysis_typesarray[enum["lint", "type", "security", "complexity", "dead_code"]]NoTypes of analysis to perform. Default: all["lint", "security"]
severity_thresholdenum["error", "warning", "info"]NoMinimum severity to report. Default: "info""warning"

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether analysis completedtrue
file_pathstringAnalyzed file path"./src/module.py"
languagestringDetected language"python"
issuesarray[object]List of detected issuesSee below
issues[].severitystringIssue severity"warning"
issues[].lineintegerLine number42
issues[].columnintegerColumn number10
issues[].messagestringIssue description"Unused variable 'x'"
issues[].rulestringRule identifier"F841"
issues[].categorystringIssue category"lint"
issues[].suggestionstringFix suggestion"Remove unused variable"
metricsobjectCode metricsSee below
metrics.lines_of_codeintegerTotal lines150
metrics.cyclomatic_complexityfloatAverage complexity3.2
metrics.maintainability_indexfloatMaintainability score (0-100)78.5
issue_countsobjectIssue counts by severity{"error": 0, "warning": 5, "info": 12}

5. Error Handling​

  • FileNotFoundError: Specified file does not exist
  • UnsupportedLanguageError: File type not supported for analysis
  • ToolNotFoundError: Required analysis tool not installed
  • Return Format: {"success": false, "error": "Analysis failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Static analysis is read-only. Identical file content produces identical results.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_analyze_file",
"arguments": {
"file_path": "./src/codomyrmex/coding/execution/executor.py",
"analysis_types": ["lint", "type", "complexity"],
"severity_threshold": "warning"
}
}

8. Security Considerations​

  • Input Validation: File path validated to exist and be readable.
  • Permissions: Read-only access to source file.
  • Data Handling: Source code content not logged or transmitted externally.
  • File Paths: Path traversal prevented; analysis restricted to allowed directories.

Tool: coding_analyze_project​

1. Tool Purpose and Description​

Performs comprehensive static analysis on an entire project or directory, aggregating findings across all files and producing quality metrics and reports.

2. Invocation Name​

coding_analyze_project

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
pathstringYesPath to project directory"./src/codomyrmex/"
include_patternsarray[string]NoGlob patterns for files to include. Default: all supported["**/*.py"]
exclude_patternsarray[string]NoGlob patterns for files to exclude["**/test_*.py", "**/__pycache__/**"]
output_pathstringNoPath to save detailed report"./reports/analysis.json"
report_formatenum["json", "html", "markdown"]NoReport output format. Default: "json""html"

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether analysis completedtrue
files_analyzedintegerNumber of files processed87
total_issuesintegerTotal issues found142
issue_summaryobjectIssues by severity{"error": 3, "warning": 45, "info": 94}
quality_scorefloatOverall quality score (0-100)82.5
metricsobjectAggregated code metricsSee below
metrics.total_locintegerTotal lines of code12450
metrics.avg_complexityfloatAverage cyclomatic complexity4.2
metrics.avg_maintainabilityfloatAverage maintainability index71.3
top_issuesarray[object]Most critical issuesSee coding_analyze_file
files_with_issuesarray[string]Files containing issues["./src/module.py"]
output_pathstringPath to saved report"./reports/analysis.json"

5. Error Handling​

  • DirectoryNotFoundError: Specified path does not exist or is not a directory
  • AnalysisError: Critical failure during analysis
  • Return Format: {"success": false, "error": "Project analysis failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Static analysis is read-only. Produces consistent results for unchanged code.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_analyze_project",
"arguments": {
"path": "./src/codomyrmex/",
"include_patterns": ["**/*.py"],
"exclude_patterns": ["**/tests/**", "**/__pycache__/**"],
"output_path": "./reports/codomyrmex-analysis.html",
"report_format": "html"
}
}

8. Security Considerations​

  • Input Validation: Path validated as directory. Glob patterns sanitized.
  • Permissions: Read access to source files, write access to output path.
  • Data Handling: Source code analyzed locally; not transmitted externally.
  • File Paths: Path traversal prevented; restricted to allowed directories.

Tool: coding_check_quality_gates​

1. Tool Purpose and Description​

Evaluates code against configurable quality gates (thresholds for complexity, coverage, issue counts, etc.). Used in CI/CD pipelines to enforce quality standards.

2. Invocation Name​

coding_check_quality_gates

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
pathstringYesPath to analyze"./src/"
gatesobjectNoQuality gate thresholds (uses defaults if not specified)See below
gates.max_complexityfloatNoMaximum allowed average complexity. Default: 108.0
gates.min_maintainabilityfloatNoMinimum maintainability index. Default: 5060.0
gates.max_errorsintegerNoMaximum error-level issues. Default: 00
gates.max_warningsintegerNoMaximum warning-level issues. Default: 5020
fail_on_violationbooleanNoReturn failure status on violation. Default: truetrue

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether all quality gates passedtrue
gates_checkedintegerNumber of gates evaluated4
gates_passedintegerNumber of gates that passed4
resultsarray[object]Per-gate resultsSee below
results[].gatestringGate name"max_complexity"
results[].passedbooleanWhether gate passedtrue
results[].thresholdfloatConfigured threshold10.0
results[].actualfloatActual measured value5.3
results[].marginfloatDistance from threshold4.7
overall_statusenum["pass", "fail", "warn"]Overall quality status"pass"

5. Error Handling​

  • AnalysisError: Unable to compute metrics
  • ConfigurationError: Invalid gate configuration
  • Return Format: {"success": false, "error": "Quality gate check failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Read-only analysis with deterministic gate evaluation.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_check_quality_gates",
"arguments": {
"path": "./src/codomyrmex/coding/",
"gates": {
"max_complexity": 8.0,
"min_maintainability": 65.0,
"max_errors": 0,
"max_warnings": 10
},
"fail_on_violation": true
}
}

8. Security Considerations​

  • Input Validation: Path validated. Gate thresholds validated as positive numbers.
  • Permissions: Read-only access to source files.
  • Data Handling: No sensitive data involved.

Tool: coding_debug_code​

1. Tool Purpose and Description​

Autonomous debugging tool that analyzes execution failures, diagnoses errors, generates fix patches using LLM assistance, and verifies repairs. Designed for automated code repair pipelines.

2. Invocation Name​

coding_debug_code

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
source_codestringYesThe source code that failed"def divide(a, b):\n return a / b"
stdoutstringYesStandard output from failed execution""
stderrstringYesStandard error from failed execution (includes stack trace)"ZeroDivisionError: division by zero"
exit_codeintegerYesExit code from failed execution1
languagestringNoProgramming language. Default: auto-detect"python"
max_retriesintegerNoMaximum fix attempts. Default: 35

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether a fix was found and verifiedtrue
fixed_codestringRepaired source code (if successful)"def divide(a, b):\n if b == 0:\n return None\n return a / b"
diagnosisobjectError diagnosis detailsSee below
diagnosis.error_typestringClassified error type"ZeroDivisionError"
diagnosis.line_numberintegerLine where error occurred2
diagnosis.root_causestringIdentified root cause"Division by zero not handled"
patches_attemptedintegerNumber of fix attempts1
patch_descriptionstringDescription of applied fix"Added zero division guard"
verificationobjectFix verification resultSee below
verification.tests_passedbooleanWhether fixed code executes cleanlytrue

5. Error Handling​

  • DiagnosisError: Unable to diagnose the error
  • PatchGenerationError: Could not generate fix suggestions
  • VerificationError: All fix attempts failed verification
  • Return Format: {"success": false, "error": "Debugging failed: <details>", "diagnosis": {...}}

6. Idempotency​

  • Idempotent: No
  • Explanation: LLM-generated patches may vary between calls. The debugging process attempts multiple fixes until one succeeds.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_debug_code",
"arguments": {
"source_code": "def process_data(items):\n total = sum(items)\n return total / len(items)",
"stdout": "",
"stderr": "Traceback (most recent call last):\n File \"<string>\", line 3, in process_data\nZeroDivisionError: division by zero",
"exit_code": 1,
"language": "python",
"max_retries": 3
}
}

8. Security Considerations​

  • Input Validation: Source code and error messages are processed but not executed during diagnosis.
  • Permissions: LLM API access required for patch generation.
  • Data Handling: Source code sent to LLM provider; avoid debugging code containing secrets.
  • Verification: Fixed code is re-executed in sandboxed environment.
  • Output Sanitization: Generated patches should be reviewed before deployment.

Tool: coding_monitor_execution​

1. Tool Purpose and Description​

Real-time monitoring tool for tracking code execution metrics including CPU usage, memory consumption, I/O operations, and execution timeline. Useful for performance profiling and resource optimization.

2. Invocation Name​

coding_monitor_execution

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
languagestringYesProgramming language"python"
codestringYesCode to execute with monitoring"import time; time.sleep(1)"
sample_interval_msintegerNoMetric sampling interval. Default: 10050
include_memory_profilebooleanNoDetailed memory profiling. Default: falsetrue
timeoutintegerNoExecution timeout in seconds. Default: 6030

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether execution completedtrue
execution_resultobjectStandard execution outputSee coding_execute_code
metricsobjectCollected performance metricsSee below
metrics.peak_memory_mbfloatPeak memory usage in MB45.2
metrics.avg_cpu_percentfloatAverage CPU utilization23.5
metrics.total_duration_msfloatTotal execution duration1023.4
metrics.io_read_bytesintegerBytes read from disk4096
metrics.io_write_bytesintegerBytes written to disk1024
timelinearray[object]Time-series metric samplesSee below
timeline[].timestamp_msfloatSample timestamp100.0
timeline[].memory_mbfloatMemory at sample32.1
timeline[].cpu_percentfloatCPU at sample15.2

5. Error Handling​

  • MonitoringError: Unable to collect metrics
  • ExecutionError: Code execution failed
  • Return Format: {"success": false, "error": "Monitoring failed: <details>", "partial_metrics": {...}}

6. Idempotency​

  • Idempotent: Partially
  • Explanation: Execution may have side effects. Metrics for identical code vary due to system load.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_monitor_execution",
"arguments": {
"language": "python",
"code": "import numpy as np\ndata = np.random.rand(10000, 10000)\nresult = np.linalg.svd(data)",
"sample_interval_ms": 100,
"include_memory_profile": true,
"timeout": 120
}
}

8. Security Considerations​

  • Input Validation: Code executed in sandboxed environment (see coding_execute_code).
  • Permissions: Same restrictions as code execution.
  • Data Handling: Performance metrics may reveal system information.
  • Resource Limits: Monitoring adds overhead; timeout enforced.

Tool: coding_generate_report​

1. Tool Purpose and Description​

Generates comprehensive code quality reports from analysis results in various formats (HTML, PDF, Markdown). Suitable for documentation, CI/CD artifacts, and stakeholder communication.

2. Invocation Name​

coding_generate_report

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
analysis_resultsobjectYesResults from coding_analyze_project or equivalent{...}
output_pathstringYesPath for generated report"./reports/quality-report.html"
formatenum["html", "markdown", "json"]NoReport format. Default: "html""html"
include_chartsbooleanNoInclude visual charts (HTML only). Default: truetrue
include_recommendationsbooleanNoInclude improvement recommendations. Default: truetrue
titlestringNoReport title"Codomyrmex Code Quality Report"

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether report was generatedtrue
output_pathstringPath to generated report"./reports/quality-report.html"
formatstringReport format"html"
size_bytesintegerReport file size45678
sections_includedarray[string]Report sections["summary", "issues", "metrics", "recommendations"]

5. Error Handling​

  • InvalidResultsError: Analysis results malformed
  • WriteError: Unable to write report file
  • Return Format: {"success": false, "error": "Report generation failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Identical inputs produce identical reports. Output file is overwritten.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_generate_report",
"arguments": {
"analysis_results": {
"files_analyzed": 42,
"total_issues": 23,
"quality_score": 85.5
},
"output_path": "./reports/weekly-quality.html",
"format": "html",
"include_charts": true,
"title": "Weekly Code Quality Report - Codomyrmex"
}
}

8. Security Considerations​

  • Input Validation: Analysis results validated for expected structure.
  • Permissions: Write access required for output path.
  • Data Handling: Report may include file paths and code snippets from analysis.
  • File Paths: Output path validated and restricted to allowed directories.

Tool: coding_run_in_docker​

1. Tool Purpose and Description​

Low-level tool for executing code in a specific Docker container configuration. Provides fine-grained control over container settings, environment variables, and volume mounts.

2. Invocation Name​

coding_run_in_docker

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
languagestringYesProgramming language"python"
codestringYesCode to execute"print('Hello')"
imagestringNoDocker image. Default: language-specific default"python:3.11-slim"
environmentobjectNoEnvironment variables{"DEBUG": "true"}
memory_limitstringNoMemory limit. Default: "256m""512m"
cpu_limitfloatNoCPU cores limit. Default: 1.02.0
network_enabledbooleanNoEnable network access. Default: falsefalse
timeoutintegerNoExecution timeout in seconds. Default: 3060

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
stdoutstringStandard output"Hello\n"
stderrstringStandard error""
exit_codeintegerExit code0
execution_timefloatExecution duration in seconds0.45
statusstringExecution status"success"
container_idstringDocker container ID used"abc123def"
resource_usageobjectContainer resource usageSee below
resource_usage.memory_peak_mbfloatPeak memory45.2
resource_usage.cpu_secondsfloatCPU time used0.32

5. Error Handling​

  • DockerNotAvailableError: Docker daemon not running
  • ImageNotFoundError: Specified image not available
  • ContainerError: Container execution failed
  • ResourceLimitError: Exceeded resource limits
  • Return Format: {"success": false, "error": "Docker execution failed: <details>", "status": "setup_error"}

6. Idempotency​

  • Idempotent: Partially
  • Explanation: Deterministic code produces consistent results. Network-enabled execution may vary.

7. Usage Examples (for MCP context)​

{
"tool_name": "coding_run_in_docker",
"arguments": {
"language": "python",
"code": "import requests\nprint(requests.get('https://api.example.com/health').status_code)",
"image": "python:3.11-slim",
"environment": {
"PYTHONUNBUFFERED": "1"
},
"memory_limit": "512m",
"cpu_limit": 1.0,
"network_enabled": true,
"timeout": 30
}
}

8. Security Considerations​

  • Input Validation: Image name validated against allowed list. Environment variables sanitized.
  • Permissions: Docker daemon access required. Container runs with restricted user.
  • Data Handling: Code and output isolated within container.
  • Network Isolation: Network disabled by default. Enable only when necessary.
  • Resource Limits: Strictly enforced via Docker cgroups.
  • File Paths: No host filesystem access except explicitly mounted volumes.