Skip to content

Fix MCP server startup issues and add tools - #45

Open
chinese1123243 wants to merge 5 commits into
horw:mainfrom
chinese1123243:main
Open

Fix MCP server startup issues and add tools#45
chinese1123243 wants to merge 5 commits into
horw:mainfrom
chinese1123243:main

Conversation

@chinese1123243

@chinese1123243 chinese1123243 commented Feb 5, 2026

Copy link
Copy Markdown

Dear @horw,

I fixed some problems I found when using this MCP server and added some tools.

Issues Fixed

1. Server Startup Failures

  • Event loop nesting errors: The async implementation was causing 'RuntimeError: Already running asyncio in this thread'. Rewrote the server loop to use synchronous communication.
  • JSON-RPC protocol errors: Fixed handling of empty lines from stdin.
  • Subprocess encoding: Added UTF-8 encoding with error replacement.

2. Platform Compatibility

  • Windows Git Bash support: Added automatic path conversion (E:/path → /e/path).
  • Environment variable handling: Improved error messages when ESP-IDF path is not configured.

3. ESP-IDF Path Detection

  • Server now reads IDF_PATH from MCP configuration environment variables.
  • Displays detected ESP-IDF path on initialization.

New Tools Added (23 tools, 30 total)

Project Management

  • get_project_info: Get detailed project information
  • list_components: List all components in project

Build & Flash

  • clean_esp_project: Clean build files
  • erase_flash_esp: Erase flash memory
  • flash_and_monitor_esp: Flash and immediately monitor
  • menuconfig_esp: Run menuconfig

Configuration

  • get_project_config: Get sdkconfig information
  • set_esp_partition: Set partition table
  • get_esp_idf_version: Get ESP-IDF version
  • check_esp_idf_env: Check environment status

Debugging

  • gdb_attach: Attach GDB debugger
  • get_core_dump: Get core dump information

Runtime Analysis

  • get_heap_info: Get heap memory info
  • get_task_stats: Get FreeRTOS task statistics

File Operations

  • read_file: Read file contents
  • write_file: Write content to file
  • list_files: List files and directories

Analysis Tools

  • parse_build_log: Structured build log analysis
  • analyze_memory_map: Memory usage analysis from .map files
  • compare_sdkconfig: Compare sdkconfig differences
  • analyze_dependencies: Analyze component dependencies
  • format_device_log: Format device serial logs

Documentation Updates

  • Updated README.md with complete tool list
  • Added 'Recent Bug Fixes & Improvements' section
  • Documented all 30 tools with descriptions

Notes

  • Original 7 tools remain unchanged in functionality
  • Tested on Windows with Git Bash and ESP-IDF v5.5.1
  • Please feel free to modify or reject these changes

Thank you for creating this MCP server."

Summary by CodeRabbit

  • Documentation

    • Reorganized docs into ~30 tools across 12 categories, added Recent Bug Fixes & Vision sections and expanded installation/usage examples.
  • New Features

    • Per-project and dynamic ESP-IDF path support, Windows Git Bash path handling, multiple sdkconfig defaults, optional flash port and build time tracking.
    • Improved serial port detection and new file/analysis utilities.
  • Bug Fixes

    • Better error handling, logging, subprocess timeouts and encoding robustness.
  • Chores

    • Updated packaging metadata and test inclusion.

@coderabbitai

coderabbitai Bot commented Feb 5, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Reorganizes README into categorized tool sections and expands documentation; adds a new config.py with MCPConfig; converts several esp utility functions from async to synchronous subprocess-based implementations, adds Windows Git Bash path handling, enhanced logging, and improved serial-port detection.

Changes

Cohort / File(s) Summary
Documentation
README.md, esp_mcp.egg-info/PKG-INFO
Replaces "Core Features" with categorized tool list (~30 tools), adds "Recent Bug Fixes & Improvements" and "Vision & Future Work", expands installation/config JSON examples and usage scenarios; updates package description and long-form package metadata.
ESP utilities
esp_utils.py
Replaces async runner with synchronous subprocess.run (timeout, UTF‑8, logging); adds convert_to_bash_path(), normalizes ESP-IDF path resolution, validates export.sh, updates check_esp_idf_installed, and reimplements list_serial_ports with Windows/Git Bash handling and pyserial fallback.
Configuration
config.py
New MCPConfig class with defaults and env-based load_from_env, get_system_root, to_dict; creates global config instance and get_config() accessor.
Packaging / Metadata
pyproject.toml, esp_mcp.egg-info/SOURCES.txt, esp_mcp.egg-info/requires.txt, esp_mcp.egg-info/top_level.txt, esp_mcp.egg-info/dependency_links.txt
Adds/updates egg-info entries and SOURCES list, records dependencies (mcp[cli], pytest), updates project description in pyproject.toml, and tracks new top-level entry.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~28 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • maitiSoutrik

Poem

🐰 I hopped through docs and shuffled every part,
Made commands behave, and gave paths a new heart.
Logs softly thump, configs snug and neat,
Ports now find COMs — oh what a treat! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix MCP server startup issues and add tools' accurately reflects the main changes: server fixes for startup issues and addition of 23 new tools, with expanded documentation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chinese1123243

Copy link
Copy Markdown
Author

I seem unable to start it (Windows 10), so I almost rebuilt it and added some ideas that I thought were suitable for embedded development. In the end, I used AI to help me with the code structure and documentation improvements—I hope you don't mind.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@esp_utils.py`:
- Around line 11-46: run_command_async currently executes a shell string with
shell=True which is vulnerable to command injection when user-controlled values
(e.g., target, project_name, baud, partition_table from main.py) are
interpolated; fix by ensuring all user-supplied inputs are safely escaped before
building the command string (use shlex.quote() on each user value) or, better,
avoid shell=True entirely by reworking the call sites to pass a list of
arguments or pass user values via environment variables to subprocess.run
(update callers in main.py that build commands with f-strings to either quote
inputs with shlex.quote or change to argument lists/env and then call
run_command_async with those safe inputs while keeping the function
signature/behavior consistent).
- Around line 142-201: The call to subprocess.run(["mode"]) in list_serial_ports
can be hijacked on Windows; update the Windows branch in list_serial_ports to
construct a fully-qualified command path using
os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32",
"mode.com") and check os.path.exists on that path, using it as the first choice
for the command; if that file does not exist fall back to ["mode"] to preserve
compatibility. Ensure the subprocess.run invocation (the block that currently
uses ["mode"]) is replaced to use the chosen command variable and keep the same
capture_output/text/timeout settings and subsequent parsing logic.
🧹 Nitpick comments (1)
README.md (1)

20-86: Keep the tool list in sync with the actual registry.
With 30 tools, manual lists tend to drift. Consider generating this section from the tool registry or adding a lightweight check to keep docs aligned with the code.

Comment thread esp_utils.py
Comment thread esp_utils.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@config.py`:
- Around line 86-123: The logger.warning calls that use f-strings without
placeholders should drop the unnecessary f prefix to satisfy Ruff F541; locate
the warnings in the config loader where environment parsing sets
config.SERIAL_PORT_TIMEOUT, config.DEFAULT_FLASH_BAUD,
config.DEFAULT_MONITOR_BAUD, config.MAX_ERRORS, and config.MAX_WARNINGS and
replace strings like f"Invalid ESP_MCP_SERIAL_TIMEOUT value, using default" with
plain string literals (remove the leading f) while leaving the surrounding
try/except and logger.debug lines unchanged.
- Around line 80-105: The env-parsing blocks for DEFAULT_COMMAND_TIMEOUT,
SERIAL_PORT_TIMEOUT, DEFAULT_FLASH_BAUD, and DEFAULT_MONITOR_BAUD should
validate that the parsed int is > 0 before assigning; if the value is <= 0 or
raises ValueError, keep the existing default and call logger.warning with a
descriptive message. Update the try/except blocks around parsing of
ESP_MCP_TIMEOUT, ESP_MCP_SERIAL_TIMEOUT, ESP_MCP_FLASH_BAUD, and
ESP_MCP_MONITOR_BAUD to check the parsed value > 0, assign only on success, and
log the fallback when invalid so subprocess.run(timeout=...) and serial/baud
settings never receive non-positive integers.

In `@esp_mcp.egg-info/PKG-INFO`:
- Around line 1-5: The package metadata contains a placeholder description ("Add
your description here") in the description field of pyproject.toml; replace that
placeholder with a concise, meaningful package description describing esp-mcp's
purpose and functionality (e.g., what it provides, its main responsibility),
updating the description key in pyproject.toml so the package metadata
(Metadata-Version / Name: esp-mcp / Version: 0.1.0) no longer contains the
placeholder.
🧹 Nitpick comments (3)
config.py (1)

5-34: Annotate mutable class attributes as ClassVar (or make immutable).
COMMON_SERIAL_PORTS is a mutable list; marking it as ClassVar clarifies intent for type checkers and avoids instance shadowing. Consider a tuple if you want immutability.

♻️ Suggested change
-from typing import List, Dict, Any
+from typing import List, Dict, Any, ClassVar
@@
-    COMMON_SERIAL_PORTS = [
+    COMMON_SERIAL_PORTS: ClassVar[List[str]] = [
         "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
         "/dev/ttyUSB0", "/dev/ttyUSB1", "/dev/ttyACM0", "/dev/ttyACM1",
         "/dev/cu.usbserial-*", "/dev/cu.SLAB_USBtoUART"
     ]
esp_utils.py (1)

52-57: Make Optional parameters explicit in type hints.
idf_path defaults to None; update the annotation to str | None (and mirror the change in get_export_script and check_esp_idf_installed) to satisfy PEP 484 tooling.

♻️ Suggested change
-def get_esp_idf_dir(idf_path: str = None) -> str:
+def get_esp_idf_dir(idf_path: str | None = None) -> str:
esp_mcp.egg-info/requires.txt (1)

1-2: Move pytest to an optional extra since it's only used as a CLI tool, not a runtime dependency.

pytest is invoked as an external command via subprocess in main.py, not imported as a Python module. Since there are no test files in the repo and pytest is only executed as a CLI tool for users who need that feature, it should be specified as an optional extra (e.g., mcp[cli,pytest]) rather than a hard runtime dependency. This avoids requiring pytest for all users.

Comment thread config.py Outdated
Comment thread config.py Outdated
Comment thread esp_mcp.egg-info/PKG-INFO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant