Skip to content

[錯誤報告] v0.3.0 find_files工具錯誤與search_code_advanced的file_pattern問題 #10

@aimasteracc

Description

@aimasteracc

[錯誤報告] ver 0.3.0 find_files工具錯誤與search_code_advanced的file_pattern問題

概要

使用code-index-mcp時發生以下兩個問題:

  1. find_files工具呼叫時必定發生錯誤
  2. search_code_advanced指定包含"/"的file_pattern時無法取得結果

環境

  • 作業系統:Windows 11
  • Python:3.x
  • code-index-mcp:最新版本(透過uvx執行)
  • 搜尋工具:ripgrep

問題1:find_files工具錯誤

重現步驟

# 透過MCP呼叫find_files
{
  "pattern": "*.py"
}

實際結果

Error executing tool find_files: 'type'

原因分析

server.py_get_all_files()函數(第759-768行)中,對目錄項目嘗試存取不存在的'type'鍵,導致KeyError發生。

問題程式碼

def _get_all_files(directory: Dict, prefix: str = "") -> List[Tuple[str, Dict]]:
    """Recursively get all files from the index."""
    all_files = []
    for name, item in directory.items():
        current_path = os.path.join(prefix, name)
        if item['type'] == 'file':  # ← 此處發生KeyError
            all_files.append((current_path, item))
        elif item['type'] == 'directory':  # ← 此處也發生KeyError
            all_files.extend(_get_all_files(item['children'], current_path))
    return all_files

修正方案

def _get_all_files(directory: Dict, prefix: str = "") -> List[Tuple[str, Dict]]:
    """Recursively get all files from the index."""
    all_files = []
    for name, item in directory.items():
        if isinstance(item, dict):
            # 使用pathlib實現跨平台相容性
            current_path = str(pathlib.Path(prefix) / name).replace('\\', '/')
            if "type" in item and item["type"] == "file":
                all_files.append((current_path, item))
            elif "type" not in item:  # 目錄的情況
                all_files.extend(_get_all_files(item, current_path))
    return all_files

問題2:search_code_advanced的file_pattern問題

重現步驟

# 使用包含路徑分隔符號的file_pattern
{
  "pattern": "def",
  "file_pattern": "src/*.py"
}

實際結果

{"results": {}}

(回傳空結果)

比較:不含路徑分隔符號的情況

{
  "pattern": "def",
  "file_pattern": "*.py"
}

此情況下正常回傳結果。

原因分析

ripgrep的--glob選項無法適當處理包含路徑分隔符號"/"的模式,特別是在Windows系統上更為明顯。

修正方案

ripgrep.py中特別處理包含路徑分隔符號的模式:

# 修正前(72行目)
process = subprocess.run(
    cmd, 
    capture_output=True, 
    text=True, 
    encoding='utf-8',
    errors='replace',
    check=False
)

# 修正後(72行目)
process = subprocess.run(
    cmd, 
    capture_output=True, 
    text=True, 
    encoding='utf-8',
    errors='replace',
    check=False,
    cwd=base_path  # ← 追加1行
)

期待的行為

  1. find_files工具應無錯誤地運作,並回傳符合指定模式的檔案清單
  2. search_code_advanced應能正常處理如"src/*.py"等包含路徑分隔符號的file_pattern

附加資訊

  • 兩個問題都是工具本身的實作問題,與LLM的呼叫方式無關
  • 問題1是必定發生的致命錯誤
  • 問題2是特定模式下才發生的限制

影響

  • 問題1使得find_files工具完全無法使用
  • 問題2限制了搜尋中檔案篩選的靈活性

感謝您對這些問題的關注。

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions