8000 MCP-USE integration with inclusion of context7 mcp server integration by noodleA1 · Pull Request #211 · ai-christianson/RA.Aid · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

MCP-USE integration with inclusion of context7 mcp server integration #211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 46 commits into
base: master
Choose a base branch
from

Conversation

noodleA1
Copy link
@noodleA1 noodleA1 commented Apr 23, 2025

Adjusted the mcp tool to use the repo mcp-use from pietrozullo and the mcp server context7 from upstash to make a more extensible and compatible mcp capable agent, giving the agent the capacity to pull up to date documentation from thousands of packages using context 7

Summary by CodeRabbit

  • New Features

    • Integrated synchronous MCP-Use client wrapper for seamless tool usage.
    • Added interactive CLI mode with continuous input and persistent memory.
    • Enhanced task processing flow with modular functions and improved CLI argument validation.
    • Introduced new MCP server configurations and guidance documents for Context7, GitHub, Task Master, and Tree-sitter.
    • Updated task implementation to return structured results including Task Master integration status.
  • Enhancements

    • Dynamic injection of MCP guidance into research and planning prompts based on active servers.
    • Improved CLI help and usage examples reflecting new MCP-related options and interactive mode.
    • Custom tools now load MCP-Use tools with detailed status panels.
  • Bug Fixes

    • Robust error handling for MCP client initialization and configuration loading.
    • Validation of file existence for relevant CLI arguments.
  • Chores

    • Extended README with detailed MCP server dependencies, setup instructions, and usage guidance.
    • Added default MCP server JSON configuration and multiple MCP guidance text files.

Copy link
coderabbitai bot commented Apr 23, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update introduces comprehensive Model Context Protocol (MCP) integration into the RA.Aid system. It adds new dependencies and configuration options for MCP-Use and Tree-sitter servers, updates the CLI with flags for MCP configuration and server management, and implements a synchronous MCP client wrapper for tool integration. Prompt templates and agent logic are extended to dynamically load and inject server-specific guidance based on active MCP servers. Documentation is updated to detail new dependencies, configuration, and usage patterns. Several new guidance files and a default MCP server configuration are included to support these features.

Changes

File(s) Change Summary
pyproject.toml Added dependencies for mcp-use and mcp-server-tree-sitter; extended Hatch build includes for source and wheel distributions.
README.md Documented MCP integration, new CLI flags, dependencies, default servers, and usage instructions.
examples/default_mcp_servers.json Added JSON config defining default MCP servers: context7, taskmaster-ai, tree_sitter, and github.
ra_aid/__main__.py Added CLI arguments for MCP-Use config, disabling default MCP servers, and disabling Task Master planning; implemented logic to initialize and manage MCP-Use clients and server configurations; updated custom tools loading; added interactive mode and modular task processing.
ra_aid/tool_configs.py Updated get_custom_tools to accept an optional MCP-Use client and load tools from it; imported MCPUseClientSync.
ra_aid/utils/mcp_use_client.py Introduced MCPUseClientSync class for synchronous MCP client and tool integration, with event loop management, error handling, and cleanup.
ra_aid/prompts/research_prompts.py, ra_aid/prompts/planning_prompts.py Added {mcp_guidance} placeholder to prompt templates for dynamic MCP guidance injection.
ra_aid/agents/research_agent.py, ra_aid/agents/planning_agent.py Dynamically load and inject MCP server-specific guidance into prompts based on active servers.
ra_aid/prompts/mcp_guidance/context7.txt, tree_sitter.txt, taskmaster-ai.txt, github.txt Added new guidance documents for each default MCP server, detailing tool usage and integration tips.
ra_aid/tools/agent.py Changed request_task_implementation to accept task_master_id, return a structured dictionary, and removed markdown formatting and crash reporting logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI (main)
    participant MCPUseClientSync
    participant ToolLoader
    participant Agent
    participant PromptSystem

    User->>CLI (main): Launch with MCP flags (e.g., --mcp-use-config)
    CLI (main)->>MCPUseClientSync: Initialize with config (load/merge/disable servers)
    MCPUseClientSync->>MCPUseClientSync: Start event loop, create sessions, load tools
    CLI (main)->>ToolLoader: get_custom_tools(mcp_use_client)
    ToolLoader->>MCPUseClientSync: get_tools_sync()
    ToolLoader-->>CLI (main): Combined custom and MCP tools
    CLI (main)->>Agent: Start agent (e.g., planning/research)
    Agent->>PromptSystem: Build prompt (inject {mcp_guidance})
    PromptSystem->>Agent: Prompt with loaded MCP guidance
    Agent->>CLI (main): Run agent logic using tools and guidance
    CLI (main)->>MCPUseClientSync: Cleanup on exit
Loading

Possibly related PRs

Poem

In the warren where the MCPs hop,
New tools and guidance make the carrots drop!
With servers and prompts, and configs anew,
The rabbits now plan with a much broader view.
Synchronous magic, guidance on tap—
This update’s a feast for a code-loving chap!
🐇✨


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (5)
ra_aid/tool_configs.py (1)

58-58: Function signature updated appropriately to support MCP-Use tools.

The updated signature allows for passing an optional MCPUseClientSync instance, enabling integration with MCP-Use tools while maintaining backward compatibility.

Consider updating the function docstring to document the new mcp_use_client parameter:

def get_custom_tools(mcp_use_client: Optional[MCPUseClientSync] = None) -> List[BaseTool]:
    """Dynamically import and return custom tools from the configured module.
    
    The custom tools module must export a 'tools' attribute that is a list of
    langchain Tool objects (e.g. StructuredTool or other tool classes).
    
    Tools must return a Dict with keys:
    - success: bool
    - can_retry: bool  
    - return_code: int
    - output: str
    
    If can_retry=True, the tool may be retried with the previous output appended
    to the prompt, up to max_retries times.
    
+   Args:
+       mcp_use_client: Optional MCPUseClientSync instance to load MCP-Use tools from
+   
    Returns:
        List[BaseTool]: List of custom tools, or empty list if no custom tools configured
    """
ra_aid/utils/mcp_use_client.py (2)

47-50: Return a copy to protect internal state

get_tools_sync() returns self._tools directly.
Callers can mutate the list and inadvertently corrupt the wrapper’s cache.

-        return self._tools
+        # Return a shallow copy so external code cannot mutate internal list
+        return list(self._tools)

69-80: Error propagation is good – but shield against partial initialisation

If create_all_sessions() or adapter.create_tools() fails, _client may be
None while some resources (e.g. the process that runs the MCP server) are already
started. Make sure to wrap the async body in a try/except and perform
await client.close_all_sessions() on failure to avoid orphaned processes.

ra_aid/__main__.py (2)

939-954: atexit cleanup is great – add manual shutdown on fatal errors

If the main program raises before normal interpreter shutdown, the atexit handler
still fires, but only after stack unwinding. To be safer, expose the instance in
config_repo (or a dedicated singleton) so that other fatal-error handlers can call
mcp_use_client_instance.close() explicitly before sys.exit(1).

No diff needed; just a recommendation.


955-957: Pass tool list instead of client?

get_custom_tools(mcp_use_client=mcp_use_client_instance) couples the function to the
client implementation. Consider passing the already-materialised list of tools
(mcp_use_client_instance.get_tools_sync()) to decouple concerns and enable easier
testing / mocking.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7d9a1f8 and e076139.

📒 Files selected for processing (6)
  • examples/context7.json (1 hunks)
  • pyproject.toml (1 hunks)
  • ra_aid/__main__.py (5 hunks)
  • ra_aid/prompts/research_prompts.py (1 hunks)
  • ra_aid/tool_configs.py (3 hunks)
  • ra_aid/utils/mcp_use_client.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
ra_aid/tool_configs.py (1)
ra_aid/utils/mcp_use_client.py (2)
  • MCPUseClientSync (10-80)
  • get_tools_sync (47-49)
🔇 Additional comments (6)
pyproject.toml (1)

61-61: LGTM! MCP-Use dependency added correctly.

The addition of the mcp-use>=1.2.7 dependency aligns with the PR objective of integrating MCP-USE repository. The version constraint allows for compatibility with future updates.

ra_aid/prompts/research_prompts.py (1)

114-115: Excellent prompt guidance for Context7 tool prioritization.

The added guidance effectively instructs the agent to prioritize using resolve-library-id and get-library-docs tools when working with specific libraries or frameworks. This aligns perfectly with the PR objective of creating a more extensible agent that can access up-to-date documentation.

ra_aid/tool_configs.py (2)

39-39: LGTM! Required import for MCP-Use integration.

Properly imports the MCPUseClientSync wrapper class that's needed for the MCP-Use integration.


111-124: Well-implemented MCP-Use tools integration with proper error handling.

The implementation correctly:

  1. Attempts to get tools from the MCP-Use client only when provided
  2. Extends the existing tools list with the MCP tools
  3. Provides clear console feedback with appropriate color coding
  4. Handles exceptions during tool retrieval

This approach ensures that the MCP-Use tools are properly integrated while maintaining robustness through appropriate error handling.

ra_aid/__main__.py (2)

86-87: Unused import?

atexit is only used after ~939. ✔️ Nothing to change.


275-278: Epilog examples read well – but reflect new mutual-exclusion flag

The comment line advertises --mcp-use-config … --no-context7, which is correct.
No action needed.

Comment on lines 1 to 8
{
"mcpServers": {
"context7": {
"command": "npx",
"args": ["-y", "@upstash/context7-mcp@latest"]
}
}
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Well-structured configuration for Context7 MCP server integration.

This configuration file properly defines the Context7 MCP server using npx to install and run the latest version of the package. This enables the agent to access up-to-date documentation from thousands of packages as mentioned in the PR description.

Consider the implications of using @latest tag:


🏁 Script executed:

#!/bin/bash
# Description: Check if the context7-mcp package exists and get its version info

echo "Checking if @upstash/context7-mcp package exists on npm registry..."
npm view @upstash/context7-mcp version description

Length of output: 255


Lock Context7 MCP server version for stability

The @upstash/context7-mcp package exists on npm (current latest: v1.0.6). While npx @upstash/context7-mcp@latest always pulls the newest build, it can introduce breaking changes unexpectedly. To ensure reproducible runs, consider pinning to a specific version or a semver range.

• File: examples/context7.json

  • Change
    "@upstash/context7-mcp@latest"
    to
    "@upstash/context7-mcp@1.0.6"
    or
    "@upstash/context7-mcp@^1.0.6"

Adds Task Master to the default MCP config, renames config file and flag, and updates planning prompt to suggest using Task Master tools.
- Integrates Task Master tools via default MCP config.\n- Adds --disable-task-master-planning flag to control planning behavior.\n- Updates Planner agent prompt to conditionally use Task Master workflow.\n- Makes MCP client loading more robust.\n- Addresses coderabbitai feedback from previous PR (race condition, close(), paths, validation).\n- Includes examples/ directory in package data.
- Adds mcp-server-tree-sitter dependency and to default MCP config.\n- Implements automatic project registration with the server on startup.\n- Updates Research agent prompt to encourage using Tree-sitter tools.
@noodleA1 noodleA1 marked this pull request as draft April 23, 2025 22:10
openhands-agent and others added 9 commits April 23, 2025 22:21
- Adds granular MCP disabling via --disable-default-mcp [servers...].\n- Adds warning for missing Task Master API keys.\n- Adds hint about Tree-sitter build dependencies on MCP init error.\n- Implements Task Master state synchronization by passing task_master_id through implementation tool and prompting Planner to call set-status.
- MCP client now tracks successfully initialized servers.\n- Agent prompts only include guidance for active MCP servers.\n- MCP initialization errors are handled more gracefully, disabling only failed servers.\n- Refactors MCP config loading logic in __main__.py.
- Adds GitHub MCP server to default config.\n- Adds Docker prerequisite and GITHUB_TOKEN note to README.\n- Adds check for GITHUB_TOKEN in __main__.py.\n- Updates Planner agent prompt with GitHub tool guidance.
- Creates ra_aid/prompts/mcp_guidance/ directory with .txt files for each server.\n- Modifies planning and research agents to load guidance from these files based on active servers.\n- Updates prompt templates to use a single {mcp_guidance} placeholder.\n- Ensures guidance files are included in package distribution via pyproject.toml.
- Fix JSON syntax in default MCP config.\n- Fix include paths in pyproject.toml.\n- Add missing Python imports.\n- Remove unreachable code in tools/agent.py.\n- Add timeouts to MCP client thread wait/join.\n- Correct grammar in Tree-sitter guidance.
- Add timeouts to MCP client thread wait/join.\n- Add missing type hint import in __main__.py.\n- Refactor tree-sitter registration logic slightly.
feat: Comprehensive MCP Server Integrations
Package version issue
@ariel-frischer
Copy link
Collaborator

Wow, this should be a huge improvement if we can get this running properly. Great work so far. Lmk if any help is needed.

@noodleA1
Copy link
Author
noodleA1 commented Apr 24, 2025

unfortunately, the "mcp use" package works only in python 3.11 so you'd have to create a venv to use this as it is now. I know there's already mcp capabilities in ra-aid. But if this is still something that is liked, maybe its ok to review.

In my forked repo I've added taskmaster mcp to handle the planning for the agent (when taskmaster mcp is activated) as well as a few other mcp servers that have needs and am now updating it to be an interactive loop that expands beyond seeing one task to completion. I also added github mcp, so the agent can use those tools to manage a repo.

But I don't know if that's beyond the scope of what's desired currently

All that to say, any help is welcome

@noodleA1 noodleA1 marked this pull request as ready for review April 24, 2025 00:14
Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
ra_aid/utils/mcp_use_client.py (1)

15-28: Fix docstring formatting issue

The class docstring has a formatting issue where the "Note:" paragraph (lines 22-26) appears to be in the middle of the main description, with line 27 continuing from line 22.

    """Synchronous wrapper around ``mcp_use.MCPClient``.

    ``mcp_use`` is fully async; RA.Aid's tool-pipeline expects plain
    synchronous ``langchain_core.tools.BaseTool`` instances.  This wrapper
    starts a background event-loop, initializes the MCP client and converts
    every server tool to a ``StructuredTool`` via the official
+   ``LangChainAdapter``.
+   
    Note:
        Using MCP servers often requires external dependencies managed by that
        server. For example, using the Context7 server requires ``npx`` (Node.js)
        to be available in the environment to run ``@upstash/context7-mcp``.

-   ``LangChainAdapter``.
    """
README.md (3)

251-253: CLI arguments formatting inconsistency

The formatting of these CLI arguments doesn't match the pattern used for other arguments in the document. The loose punctuation marks (as flagged by static analysis) make the list harder to parse visually.

Consider reformatting these entries to match the style of other CLI arguments in the document:

-    - `--mcp-use-config`: Path to a custom MCP-Use JSON config file. If provided without `--disable-default-mcp`, only this config will be loaded.
-    - `--disable-default-mcp [SERVER ...]`: Disable specific default MCP servers (context7, taskmaster-ai, tree_sitter, github) or all if no names are given. Can be used with `--mcp-use-config` to merge custom config with filtered defaults.
-    - `--disable-task-master-planning`: Force RA.Aid to use its internal planner instead of Task Master tools, even if the Task Master MCP server is active.
+    - `--mcp-use-config`: Path to a custom MCP-Use JSON config file. If provided without `--disable-default-mcp`, only this config will be loaded.
+    - `--disable-default-mcp [SERVER ...]`: Disable specific default MCP servers (context7, taskmaster-ai, tree_sitter, github) or all if no names are given. This can be used with `--mcp-use-config` to merge custom config with filtered defaults.
+    - `--disable-task-master-planning`: Force RA.Aid to use its internal planner instead of Task Master tools, even if the Task Master MCP server is active.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~251-~251: Loose punctuation mark.
Context: .... - --disable-default-mcp [SERVER ...]: Disable specific default MCP servers (c...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~251-~251: To form a complete sentence, be sure to include a subject.
Context: ..., github) or all if no names are given. Can be used with --mcp-use-config to merg...

(MISSING_IT_THERE)


[uncategorized] ~252-~252: Loose punctuation mark.
Context: ...ults. - --disable-task-master-planning: Force RA.Aid to use its internal planne...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~253-~253: Loose punctuation mark.
Context: ... server is active. - --expert-provider: The LLM provider to use for expert know...

(UNLIKELY_OPENING_PUNCTUATION)


157-158: Node.js capitalization issue

There's a minor capitalization issue with "Node.js" as flagged by the static analyzer.

- **Node.js & npm/npx:** Required for the default MCP servers (Context7, Task Master). Install from [nodejs.org](https://nodejs.org/).
+ **Node.js & npm/npx:** Required for the default MCP servers (Context7, Task Master). Install from [Node.js](https://nodejs.org/).
🧰 Tools
🪛 LanguageTool

[uncategorized] ~157-~157: The official spelling of this programming framework is “Node.js”.
Context: ... (Context7, Task Master). Install from nodejs.org. - **C/C++ Bu...

(NODE_JS)


159-162: Indentation inconsistency in list items

The static analyzer flagged indentation inconsistencies in the unordered list items. The OS-specific instructions are indented with 4 spaces instead of the standard 2 spaces for Markdown.

- **C/C++ Build Tools:** Required by the Tree-sitter MCP server (`mcp-server-tree-sitter`) to build language parsers. Installation varies by OS:
-    - **Debian/Ubuntu:** `sudo apt-get update && sudo apt-get install build-essential`
-    - **Fedora:** `sudo dnf groupinstall "Development Tools"`
-    - **macOS:** Install Xcode Command Line Tools: `xcode-select --install`
-    - **Windows:** Install Visual Studio with C++ build tools (select "Desktop development with C++" workload in the installer).
+ **C/C++ Build Tools:** Required by the Tree-sitter MCP server (`mcp-server-tree-sitter`) to build language parsers. Installation varies by OS:
+  - **Debian/Ubuntu:** `sudo apt-get update && sudo apt-get install build-essential`
+  - **Fedora:** `sudo dnf groupinstall "Development Tools"`
+  - **macOS:** Install Xcode Command Line Tools: `xcode-select --install`
+  - **Windows:** Install Visual Studio with C++ build tools (select "Desktop development with C++" workload in the installer).
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

159-159: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


160-160: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


161-161: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


162-162: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

ra_aid/__main__.py (2)

1022-1022: Unnecessary f-string placeholder

There's an unnecessary f-string without placeholders as flagged by the static analyzer.

- logger.info(f"Attempting to initialize MCP-Use client...")
+ logger.info("Attempting to initialize MCP-Use client...")
🧰 Tools
🪛 Ruff (0.8.2)

1022-1022: f-string without any placeholders

Remove extraneous f prefix

(F541)


1045-1053: Nested if statements can be simplified

The static analyzer flagged two instances of nested if statements that can be simplified.

- if task_master_planning_enabled:
-     if not os.getenv("ANTHROPIC_API_KEY"):
-         logger.warning("Task Master planning is enabled, but ANTHROPIC_API_KEY environment variable is not set. Task Master tools requiring it may fail.")
+ if task_master_planning_enabled and not os.getenv("ANTHROPIC_API_KEY"):
+     logger.warning("Task Master planning is enabled, but ANTHROPIC_API_KEY environment variable is not set. Task Master tools requiring it may fail.")

- if "github" in active_mcp_servers:
-      if not os.getenv("GITHUB_TOKEN"):
-           logger.warning("GitHub MCP server is active, but GITHUB_TOKEN environment variable is not set. GitHub tools will likely fail.")
+ if "github" in active_mcp_servers and not os.getenv("GITHUB_TOKEN"):
+     logger.warning("GitHub MCP server is active, but GITHUB_TOKEN environment variable is not set. GitHub tools will likely fail.")
🧰 Tools
🪛 Ruff (0.8.2)

1045-1046: Use a single if statement instead of nested if statements

(SIM102)


1051-1052: Use a single if statement instead of nested if statements

(SIM102)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e076139 and e0fe537.

📒 Files selected for processing (14)
  • README.md (3 hunks)
  • examples/default_mcp_servers.json (1 hunks)
  • pyproject.toml (2 hunks)
  • ra_aid/__main__.py (6 hunks)
  • ra_aid/agents/planning_agent.py (2 hunks)
  • ra_aid/agents/research_agent.py (3 hunks)
  • ra_aid/prompts/mcp_guidance/context7.txt (1 hunks)
  • ra_aid/prompts/mcp_guidance/github.txt (1 hunks)
  • ra_aid/prompts/mcp_guidance/taskmaster-ai.txt (1 hunks)
  • ra_aid/prompts/mcp_guidance/tree_sitter.txt (1 hunks)
  • ra_aid/prompts/planning_prompts.py (1 hunks)
  • ra_aid/prompts/research_prompts.py (1 hunks)
  • ra_aid/tools/agent.py (3 hunks)
  • ra_aid/utils/mcp_use_client.py (1 hunks)
✅ Files skipped from review due to trivial changes (6)
  • ra_aid/prompts/mcp_guidance/github.txt
  • ra_aid/prompts/mcp_guidance/context7.txt
  • ra_aid/prompts/planning_prompts.py
  • ra_aid/prompts/mcp_guidance/tree_sitter.txt
  • ra_aid/prompts/mcp_guidance/taskmaster-ai.txt
  • examples/default_mcp_servers.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • ra_aid/prompts/research_prompts.py
  • pyproject.toml
🧰 Additional context used
🧬 Code Graph Analysis (2)
ra_aid/tools/agent.py (1)
ra_aid/agent_context.py (2)
  • reset_completion_flags (54-58)
  • reset_completion_flags (195-199)
ra_aid/agents/planning_agent.py (1)
ra_aid/database/repositories/config_repository.py (1)
  • get_config_repository (178-194)
🪛 LanguageTool
README.md

[uncategorized] ~157-~157: The official spelling of this programming framework is “Node.js”.
Context: ... (Context7, Task Master). Install from nodejs.org. - **C/C++ Bu...

(NODE_JS)


[uncategorized] ~251-~251: Loose punctuation mark.
Context: .... - --disable-default-mcp [SERVER ...]: Disable specific default MCP servers (c...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~251-~251: To form a complete sentence, be sure to include a subject.
Context: ..., github) or all if no names are given. Can be used with --mcp-use-config to merg...

(MISSING_IT_THERE)


[uncategorized] ~252-~252: Loose punctuation mark.
Context: ...ults. - --disable-task-master-planning: Force RA.Aid to use its internal planne...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~309-~309: Consider an alternative adjective to strengthen your wording.
Context: ... Abstract Syntax Trees (ASTs), enabling deeper understanding of code relationships, sy...

(DEEP_PROFOUND)


[uncategorized] ~315-~315: Loose punctuation mark.
Context: ...able-default-mcp context7 taskmaster-ai: Disable specific default servers. - --...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~316-~316: Loose punctuation mark.
Context: ...s. - --mcp-use-config ./my_config.json: Use only a custom MCP configuration. - ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~317-~317: Loose punctuation mark.
Context: ...tion. - --disable-task-master-planning: Keep Task Master tools available but us...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~319-~319: This wording can make your sentence hard to follow. Try rephrasing for improved clarity.
Context: ...ult MCP server fails to initialize (e.g., due to missing dependencies), it will be autom...

(DUE_TO_BECAUSE)

🪛 markdownlint-cli2 (0.17.2)
README.md

159-159: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


160-160: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


161-161: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


162-162: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

🪛 Ruff (0.8.2)
ra_aid/__main__.py

1022-1022: f-string without any placeholders

Remove extraneous f prefix

(F541)


1045-1046: Use a single if statement instead of nested if statements

(SIM102)


1051-1052: Use a single if statement instead of nested if statements

(SIM102)

🔇 Additional comments (26)
ra_aid/utils/mcp_use_client.py (5)

30-56: LGTM! Proper thread synchronization implemented

The initializer correctly avoids the race condition mentioned in past reviews by using a threading event with timeout to ensure the event loop is running before scheduling coroutines. The error handling is also robust with appropriate logging.


68-98: Excellent improvements to the close() method

The close() method has been significantly improved from past reviews:

  • Added idempotency with the _closed flag
  • Proper checking if the loop is running before scheduling
  • Added timeout handling for session closing
  • Added thread aliveness check after join with appropriate warning

These changes prevent resource leaks and make shutdown more robust.


103-111: LGTM! Proper event loop management

The _run_loop method correctly sets up the event loop, signals when it's ready via _loop_started.set(), and ensures the loop gets closed when finished.


126-148: LGTM! Robust error handling per server

The code properly handles initialization errors on a per-server basis, allowing some servers to fail without affecting others. Clear, detailed logging helps with troubleshooting.


169-202: LGTM! Well-implemented tree-sitter auto-registration

The auto-registration for tree-sitter is carefully implemented with proper error handling and verification at each step. The code correctly uses await for the async tool call.

ra_aid/agents/research_agent.py (3)

19-21: LGTM! Clean import

The added import is properly placed with related imports and uses the conventional alias for importlib.resources.


372-389: LGTM! Well-implemented dynamic MCP guidance loading

This implementation correctly:

  • Retrieves active MCP servers from configuration
  • Skips Task Master guidance in the Research agent (handled separately in Planning agent)
  • Uses proper error handling with appropriate logging levels for different error cases
  • Efficiently concatenates guidance parts into a single string

417-417: LGTM! Properly integrates MCP guidance

The combined MCP guidance is correctly integrated into the research prompt template.

ra_aid/agents/planning_agent.py (3)

19-20: LGTM! Clean import

The added import is properly placed with related imports and uses the conventional alias for importlib.resources.


341-368: LGTM! Well-implemented task master-aware guidance loading

This implementation properly:

  • Handles Task Master guidance conditionally based on a separate flag
  • Processes other servers based on activity status
  • Uses appropriate error handling with different logging levels
  • Has clear, logical organization

The conditional handling of taskmaster-ai is a good design choice that allows for more flexibility.


376-376: LGTM! Properly integrates MCP guidance

The combined MCP guidance is correctly integrated into the planning prompt template.

ra_aid/tools/agent.py (3)

3-3: LGTM! Appropriate import update

The import line is properly updated to include Optional for the new parameter type.


372-384: LGTM! Well-documented new parameter and return type

The function signature and docstring have been properly updated to include the new task_master_id parameter with clear documentation on its purpose and the updated return structure.


466-475: LGTM! Improved return structure

The updated return structure with a clean dictionary is more modular and better supports the MCP integration by preserving the task_master_id for upstream processing.

README.md (3)

153-169: Well-structured documentation of new dependencies

The documentation clearly explains the additional dependencies required for MCP integration, with specific OS installation instructions. This is excellent for user experience.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~157-~157: The official spelling of this programming framework is “Node.js”.
Context: ... (Context7, Task Master). Install from nodejs.org. - **C/C++ Bu...

(NODE_JS)

🪛 markdownlint-cli2 (0.17.2)

159-159: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


160-160: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


161-161: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


162-162: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


172-175: Good practice for API key requirements documentation

Clear documentation of required API keys is essential for users to successfully use the MCP integration features.


303-319: Comprehensive MCP integration documentation

The documentation provides clear explanations of the MCP server capabilities, benefits, and how to manage them through command-line flags. The note about automatic disabling on dependency failures is especially helpful.

🧰 Tools
🪛 LanguageTool

[style] ~309-~309: Consider an alternative adjective to strengthen your wording.
Context: ... Abstract Syntax Trees (ASTs), enabling deeper understanding of code relationships, sy...

(DEEP_PROFOUND)


[uncategorized] ~315-~315: Loose punctuation mark.
Context: ...able-default-mcp context7 taskmaster-ai: Disable specific default servers. - --...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~316-~316: Loose punctuation mark.
Context: ...s. - --mcp-use-config ./my_config.json: Use only a custom MCP configuration. - ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~317-~317: Loose punctuation mark.
Context: ...tion. - --disable-task-master-planning: Keep Task Master tools available but us...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~319-~319: This wording can make your sentence hard to follow. Try rephrasing for improved clarity.
Context: ...ult MCP server fails to initialize (e.g., due to missing dependencies), it will be autom...

(DUE_TO_BECAUSE)

ra_aid/__main__.py (9)

512-528: Well-structured CLI argument additions for MCP integration

The new CLI arguments are well-defined with appropriate help text that aligns with the README documentation. The metavar for SERVER_NAME and default=None are good choices for the implementation.


535-544: Excellent file validation improvement

Adding eager validation for file paths provided via arguments is a significant improvement that will prevent confusing errors later in execution. This addresses issues like the one mentioned in past review comments where paths were only validated when they were used.


934-1011: Robust MCP configuration management logic

The implementation handles multiple configuration scenarios elegantly:

  1. User config only when no defaults are disabled
  2. Filtered defaults when user disables specific servers
  3. Merged configs when both user config and defaults are needed

Error handling is comprehensive with appropriate fallbacks. The comments explaining the different cases make the code more maintainable.


1015-1035: Well-implemented MCP client initialization with cleanup

The code effectively initializes the MCP client and properly registers cleanup with atexit. The error handling ensures the application continues to function even if MCP initialization fails.

🧰 Tools
🪛 Ruff (0.8.2)

1022-1022: f-string without any placeholders

Remove extraneous f prefix

(F541)


1038-1054: API key validation for MCP servers

Good implementation of environment variable checks for required API keys, with appropriate warning messages that explain the potential impact.

🧰 Tools
🪛 Ruff (0.8.2)

1045-1046: Use a single if statement instead of nested if statements

(SIM102)


1051-1052: Use a single if statement instead of nested if statements

(SIM102)


1056-1056: Proper integration with existing systems

The update to the get_custom_tools() call properly integrates the MCP client with the existing tool system, enabling the MCP tools to be made available to the agent.


91-93: Good use of standardized modules

Using importlib.resources for accessing package resources and atexit for resource cleanup follows Python best practices and ensures proper resource management.


5-10: Proper type annotations for improved code quality

The addition of proper type annotations using TYPE_CHECKING ensures type checking without runtime overhead, following good Python development practices.


282-284: Helpful examples in CLI help text

The addition of MCP-related examples in the CLI help text is useful for users to understand how to use the new features, matching the documentation in the README.

Comment on lines 146 to +152
### Prerequisites

- **Python 3.10+**
- **Git**
- **Ripgrep (`rg`)**: Required for efficient code searching. Install via your system package manager (e.g., `apt install ripgrep`, `brew install ripgrep`, `choco install ripgrep`).

- **Docker:** Required if using the default GitHub MCP server integration (which runs in a container). Install from [docker.com](https://www.docker.com/products/docker-desktop/). Ensure the Docker daemon is running.
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Upgraded Python requirement may impact compatibility

The project now requires Python 3.10+ (upgraded from 3.8+). This change should be highlighted prominently to users since it represents a potentially breaking change that could affect existing installations and compatibility.

Consider one of these approaches:

  1. Add a prominent note in the Getting Started section about the version change
  2. Test compatibility with Python 3.8-3.9 to see if you can maintain backward compatibility
  3. Document migration steps for users on older Python versions

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
README.md (1)

7-9: ⚠️ Potential issue

Python version requirements are inconsistent

The badge at the top advertises Python 3.8+, but the “Prerequisites” section
later says Python 3.10+. Please align these two statements (and any
pyproject.toml / setup.cfg classifiers) to avoid user confusion and
installation failures.

Example fix:

-[![Python Versions](https://img.shields.io/badge/python-3.8%2B-blue)](https://www.python.org)
+[![Python Versions](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org)

@@
-**Python 3.10+**
+**Python 3.10+ (required)**

Also applies to: 147-151

🧰 Tools
🪛 markdownlint-cli2 (0.17. F438 2)

9-9: No empty links
null

(MD042, no-empty-links)

♻️ Duplicate comments (1)
README.md (1)

158-159: Spelling: use “Node.js”

The correct capitalization is “Node.js” (per LanguageTool hint).

-**Node.js & npm/npx:**
+**Node.js & npm/npx:**
🧰 Tools
🪛 LanguageTool

[uncategorized] ~158-~158: The official spelling of this programming framework is “Node.js”.
Context: ... (Context7, Task Master). Install from nodejs.org. - **C/C++ Bu...

(NODE_JS)

🧹 Nitpick comments (4)
ra_aid/__main__.py (3)

1151-1171: Guard against missing examples/default_mcp_servers.json in source distributions

importlib.resources.files("ra_aid").joinpath("examples/default_mcp_servers.json")
assumes the file is shipped as package data. If the user installs RA.Aid from a
wheel without package_data, is_file() returns False and you log an error,
but later logic still treats default_config_dict as valid (empty dict) and
proceeds to enable MCP-Use. This silently disables Context7/TaskMaster without
informing the user why.

Consider:

  1. Explicitly setting mcp_enabled = False when defaults are missing and
    --mcp-use-config wasn’t provided.
  2. Emitting a one-shot warning explaining that default MCP servers were skipped
    because the JSON file is absent.

This improves transparency and avoids user confusion.


958-982: Interactive REPL swallows KeyboardInterrupt inside inner loop

run_interactive_mode() has a nested try/except (EOFError, KeyboardInterrupt)
inside the while True, then an outer try/except Exception. As a result,
Ctrl-C only exits the current task but drops the user back to the prompt,
contradicting the help text (“Press Ctrl+C to exit.”).

If the intent is to terminate RA.Aid on Ctrl-C, break the loop or re-raise:

except (EOFError, KeyboardInterrupt):
-    print("\n👋 Goodbye!")
-    sys.exit(0)
+    print("\n👋 Goodbye!")
+    break   # or: raise

Otherwise, update the welcome text to clarify that a double Ctrl-C (or Ctrl-D)
is required.


1231-1248: Simplify nested if statements (ruff SIM102)

The consecutive checks for missing environment variables can be flattened:

-if task_master_planning_enabled:
-    if not os.getenv("ANTHROPIC_API_KEY"):
-        logger.warning("…")
+if task_master_planning_enabled and not os.getenv("ANTHROPIC_API_KEY"):
+    logger.warning("…")

The same pattern applies to the GitHub token block below.

🧰 Tools
🪛 Ruff (0.8.2)

1239-1240: Use a single if statement instead of nested if statements

(SIM102)


1245-1246: Use a single if statement instead of nested if statements

(SIM102)

README.md (1)

158-163: Indentation breaks Markdown list rendering

The four OS-specific commands under “C/C++ Build Tools” are indented with 4
spaces instead of 2, tripping markdownlint (MD007) and rendering as a single
code block rather than list items on GitHub.

-    - **Debian/Ubuntu:** `sudo apt-get update && sudo apt-get install build-essential`
-    - **Fedora:** `sudo dnf groupinstall "Development Tools"`
-    - **macOS:** Install Xcode Command Line Tools: `xcode-select --install`
-    - **Windows:** Install Visual Studio with C++ build tools (select "Desktop development with C++" workload in the installer).
+  - **Debian/Ubuntu:** `sudo apt-get update && sudo apt-get install build-essential`
+  - **Fedora:** `sudo dnf groupinstall "Development Tools"`
+  - **macOS:** Install Xcode Command Line Tools: `xcode-select --install`
+  - **Windows:** Install Visual Studio with C++ build tools (select "Desktop development with C++" workload in the installer).
🧰 Tools
🪛 LanguageTool

[uncategorized] ~158-~158: The official spelling of this programming framework is “Node.js”.
Context: ... (Context7, Task Master). Install from nodejs.org. - **C/C++ Bu...

(NODE_JS)

🪛 markdownlint-cli2 (0.17.2)

160-160: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


161-161: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


162-162: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


163-163: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0fe537 and 8e34540.

📒 Files selected for processing (2)
  • README.md (6 hunks)
  • ra_aid/__main__.py (13 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
ra_aid/__main__.py

1216-1216: f-string without any placeholders

Remove extraneous f prefix

(F541)


1239-1240: Use a single if statement instead of nested if statements

(SIM102)


1245-1246: Use a single if statement instead of nested if statements

(SIM102)

🪛 LanguageTool
README.md

[uncategorized] ~158-~158: The official spelling of this programming framework is “Node.js”.
Context: ... (Context7, Task Master). Install from nodejs.org. - **C/C++ Bu...

(NODE_JS)


[uncategorized] ~247-~247: Loose punctuation mark.
Context: ... Command Line Options - -m, --message: The task or query to be executed (optio...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~259-~259: Loose punctuation mark.
Context: .... - --disable-default-mcp [SERVER ...]: Disable specific default MCP servers (c...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~259-~259: To form a complete sentence, be sure to include a subject.
Context: ..., github) or all if no names are given. Can be used with --mcp-use-config to merg...

(MISSING_IT_THERE)


[uncategorized] ~260-~260: Loose punctuation mark.
Context: ...ults. - --disable-task-master-planning: Force RA.Aid to use its internal planne...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~317-~317: Consider an alternative adjective to strengthen your wording.
Context: ... Abstract Syntax Trees (ASTs), enabling deeper understanding of code relationships, sy...

(DEEP_PROFOUND)


[uncategorized] ~323-~323: Loose punctuation mark.
Context: ...able-default-mcp context7 taskmaster-ai: Disable specific default servers. - --...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~324-~324: Loose punctuation mark.
Context: ...s. - --mcp-use-config ./my_config.json: Use only a custom MCP configuration. - ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~325-~325: Loose punctuation mark.
Context: ...tion. - --disable-task-master-planning: Keep Task Master tools available but us...

(UNLIKELY_OPENING_PUNCTUATION)


[style] ~327-~327: This wording can make your sentence hard to follow. Try rephrasing for improved clarity.
Context: ...ult MCP server fails to initialize (e.g., due to missing dependencies), it will be autom...

(DUE_TO_BECAUSE)

🪛 markdownlint-cli2 (0.17.2)
README.md

160-160: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


161-161: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


162-162: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


163-163: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

Comment on lines 826 to 868
def process_task(args):
"""Process a single task with the given arguments."""
# This function will contain the core task processing logic
# that was previously in main()

# Create config repository for storing runtime configuration
config_repo = get_config_repository()

# Store key arguments in config repository for access by tools
config_repo.set("provider", args.provider)
config_repo.set("model", args.model)
config_repo.set("temperature", args.temperature)
config_repo.set("expert_provider", args.expert_provider)
config_repo.set("expert_model", args.expert_model)
config_repo.set("research_only", args.research_only)

# Safely set web_research and search flags
web_research_enabled = getattr(args, 'web_research', False)
search_enabled = getattr(args, 'search', False)
config_repo.set("web_research_enabled", web_research_enabled)
config_repo.set("search_enabled", search_enabled)

config_repo.set("hil", args.hil)
config_repo.set("test_cmd_timeout", args.test_cmd_timeout)
config_repo.set("max_test_cmd_retries", args.max_test_cmd_retries)

# Initialize MCP-Use integration if enabled
mcp_use_client_instance = None
if hasattr(args, 'mcp_use_config') and args.mcp_use_config:
try:
from ra_aid.utils.mcp_use_client import MCPUseClientSync
logger.info("Attempting to initialize MCP-Use client...")
mcp_use_client_instance = MCPUseClientSync(args.mcp_use_config)
active_mcp_servers = mcp_use_client_instance.get_active_server_names()
logger.info(f"MCP-Use client initialized. Active servers: {active_mcp_servers}")
config_repo.set("mcp_use_enabled", True)
config_repo.set("active_mcp_servers", active_mcp_servers)
except Exception as e:
logger.error(f"MCP-Use client initialization failed: {e}")
logger.warning("MCP-Use integration will be disabled for this run.")
config_repo.set("mcp_use_enabled", False)
config_repo.set("active_mcp_servers", [])

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

process_task() is executed without an active DB/repository context

process_task() calls repository getters (get_config_repository(), get_session_repository(), get_human_input_repository(), …).
When invoked from interactive mode (run_interactive_mode()), it is outside the with DatabaseManager(...): block created in main(), meaning all repository managers have already been closed. This will trigger database-closed exceptions on the second interactive request.

A minimal fix is to wrap process_task() itself in the same context managers you use in main():

def process_task(args):
-    # existing code...
+    from ra_aid.database import DatabaseManager
+    from ra_aid.database.repositories.session_repository import (
+        SessionRepositoryManager,
+    )
+    # … import the other *RepositoryManager classes you need …
+
+    with DatabaseManager(base_dir=args.project_state_dir) as db, \
+         SessionRepositoryManager(db), \
+         KeyFactRepositoryManager(db), \
+         KeySnippetRepositoryManager(db), \
+         HumanInputRepositoryManager(db), \
+         ResearchNoteRepositoryManager(db), \
+         TrajectoryRepositoryManager(db), \
+         WorkLogRepositoryManager(), \
+         ConfigRepositoryManager():
+        # ── all existing process_task logic stays here ──

Alternatively, move the interactive loop entirely inside the original with block and keep repository managers alive for the whole REPL session.
Failing to address this will make the new interactive mode unstable after the first task.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 552 to 561
# Eagerly validate file paths provided via arguments
if parsed_args.msg_file and not os.path.exists(parsed_args.msg_file):
parser.error(f"Message file not found: {parsed_args.msg_file}")
if parsed_args.custom_tools and not os.path.exists(parsed_args.custom_tools):
parser.error(f"Custom tools file not found: {parsed_args.custom_tools}")
if parsed_args.mcp_use_config and not os.path.exists(parsed_args.mcp_use_config):
parser.error(f"MCP-Use config file not found: {parsed_args.mcp_use_config}")
if parsed_args.aider_config and not os.path.exists(parsed_args.aider_config):
parser.error(f"Aider config file not found: {parsed_args.aider_config}")

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use os.path.isfile() for strict path validation

os.path.exists() also returns True for directories.
Because the CLI flags (--msg-file, --custom-tools, --mcp-use-config, --aider-config) are all file arguments, accidentally passing a directory will skip validation and fail later with less helpful errors.

-if parsed_args.msg_file and not os.path.exists(parsed_args.msg_file):
+if parsed_args.msg_file and not os.path.isfile(parsed_args.msg_file):
@@
-if parsed_args.custom_tools and not os.path.exists(parsed_args.custom_tools):
+if parsed_args.custom_tools and not os.path.isfile(parsed_args.custom_tools):
@@
-if parsed_args.mcp_use_config and not os.path.exists(parsed_args.mcp_use_config):
+if parsed_args.mcp_use_config and not os.path.isfile(parsed_args.mcp_use_config):
@@
-if parsed_args.aider_config and not os.path.exists(parsed_args.aider_config):
+if parsed_args.aider_config and not os.path.isfile(parsed_args.aider_config):

This change prevents silent acceptance of invalid directory paths and surfaces a clear, early CLI error.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Eagerly validate file paths provided via arguments
if parsed_args.msg_file and not os.path.exists(parsed_args.msg_file):
parser.error(f"Message file not found: {parsed_args.msg_file}")
if parsed_args.custom_tools and not os.path.exists(parsed_args.custom_tools):
parser.error(f"Custom tools file not found: {parsed_args.custom_tools}")
if parsed_args.mcp_use_config and not os.path.exists(parsed_args.mcp_use_config):
parser.error(f"MCP-Use config file not found: {parsed_args.mcp_use_config}")
if parsed_args.aider_config and not os.path.exists(parsed_args.aider_config):
parser.error(f"Aider config file not found: {parsed_args.aider_config}")
# Eagerly validate file paths provided via arguments
if parsed_args.msg_file and not os.path.isfile(parsed_args.msg_file):
parser.error(f"Message file not found: {parsed_args.msg_file}")
if parsed_args.custom_tools and not os.path.isfile(parsed_args.custom_tools):
parser.error(f"Custom tools file not found: {parsed_args.custom_tools}")
if parsed_args.mcp_use_config and not os.path.isfile(parsed_args.mcp_use_config):
parser.error(f"MCP-Use config file not found: {parsed_args.mcp_use_config}")
if parsed_args.aider_config and not os.path.isfile(parsed_args.aider_config):
parser.error(f"Aider config file not found: {parsed_args.aider_config}")

noodleA1 and others added 22 commits April 23, 2025 18:00
Fix interactive mode issues and add MCP servers display
Ensures MCP servers are correctly initialized and available in interactive mode.
When user selects 'n' for a shell command, prompt for feedback.
fix: Display status panel immediately in interactive mode
fix: Ensure MCP status displays correctly in interactive mode
chore: Add debug logging for MCP server status
Ensures MCP servers are initialized before interactive mode decision.
refactor: Initialize MCP servers before interactive mode check
feat: Add wait time and message for MCP server initialization
chore: Add detailed logging to MCP config loading
fix: Correct path for loading default MCP config file
Using MCP servers often requires external dependencies managed by that
server. For example, using the Context7 server requires ``npx`` (Node.js)
to be available in the environment to run ``@upstash/context7-mcp``.

Copy link
Collaborator
< F438 button class="flash-close js-comment-hide-minimize-form" type="button">

Choose a reason for hiding this comment

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

looks like this docstring got mangled a bit. LangChainAdapter got cut off from the preceding paragraph.

@ai-christianson
Copy link
Owner

@noodleA1 assume I have RA.Aid set up and running, e.g. I have GEMINI_API_KEY set and ra-aid -m is working as normal.

What's the best way to test this?

@ai-christianson
Copy link
Owner

Awesome PR btw --we'll have to get it reviewed but improving MCP support is a great contribution 👍

If it does, use `task-master list` and `task-master show` to understand the existing plan and align with it.
If the user provided a PRD file path, prioritize using `task-master parse-prd <filepath>` to generate the initial task list.
When generating or refining complex steps, consider using `task-master expand --id=<task_id>`.
After a task implementation is successfully completed (i.e., `request_task_implementation` returns `success: true` and a `task_master_id`), you MUST immediately call `task-master set-status --id=<returned_task_master_id> --status=done` to keep the Task Master state synchronized.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Question: If we always need to set status to done on success and we have the id of that task - why don't we automatically call set-status ourselves internally instead of relying on the AI to do it?

@@ -0,0 +1,7 @@

Tree-sitter Tool Guidance:
Use tree-sitter tools (`get_ast`, `get_symbols`, `run_query`, `get_dependencies`) for structural code analysis. These complement text search (`run_shell_command` with `rg`). For example:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Shouldn't we expand on this to explain more details like params or give examples?

get_ast(project="my-project", path="src/main.py", max_depth=5, include_text=True)

Unless directions are given somewhere else as well?

"reason": reason,
"agent_crashed": agent_crashed,
"crash_message": crash_message,
"task_master_id": task_master_id # Pass back the ID
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

So what happens if we don't return back key facts or snippets? Are we not tracking those anymore with this new change for taskmaster implementation?

@ariel-frischer
Copy link
Collaborator

@noodleA1 Have you got this fully integrated and running yet? If so what are your general thoughts of it? Is it running better or worse with these MCP tools?

@noodleA1
Copy link
Author

Still working on it, but took a break from it for something else. I'll likely lean back into it, but was testing plandex as it recently became active again.

I had some pretty big issues with this PR as it stands but looking forward to adjusting it. So far EVERY ai system with sequential thinking, context7, and even firecrawl/brave/sometimes taskmaster has improved dramatically, or at least confidence has risen which is no small thing with these systems

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.

5 participants
0