Skip to content

Commit da6f990

Browse files
author
Yoshihiro Takahara
committed
fix: handle out of bounds end line in read_multiple_ranges
When a range end line exceeds the file length, return content up to the end of file instead of raising an error
1 parent d7f00c0 commit da6f990

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/mcp_text_editor/text_editor.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,15 @@ async def read_multiple_ranges(
100100
total_lines = len(lines)
101101
file_content = "".join(lines)
102102
file_hash = self.calculate_hash(file_content)
103-
104103
for range_spec in file_range["ranges"]:
105104
# Adjust line numbers to 0-based index
106105
line_start = max(1, range_spec["start"]) - 1
107106
end_value = range_spec.get("end")
107+
line_end = (
108+
min(total_lines, end_value)
109+
if end_value is not None
110+
else total_lines
111+
)
108112
line_end = (
109113
total_lines
110114
if end_value is None

tests/test_text_editor.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,3 +341,35 @@ async def test_read_multiple_ranges_out_of_bounds_start(editor, test_file):
341341
assert second_range["end_line"] == 6
342342
assert second_range["total_lines"] == 5
343343
assert second_range["content_size"] == 0
344+
345+
346+
@pytest.mark.asyncio
347+
async def test_read_multiple_ranges_out_of_bounds_end(editor, test_file):
348+
"""Test reading ranges where end line exceeds file length."""
349+
ranges = [
350+
{
351+
"file_path": test_file,
352+
"ranges": [
353+
{"start": 1, "end": 1000}, # End way beyond file end
354+
{"start": 2, "end": 6}, # End just beyond file end
355+
],
356+
}
357+
]
358+
359+
result = await editor.read_multiple_ranges(ranges)
360+
361+
# Check first range (end line way beyond file end)
362+
first_range = result[test_file][0]
363+
assert first_range["content"] == "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n"
364+
assert first_range["start_line"] == 1
365+
assert first_range["end_line"] == 5
366+
assert first_range["total_lines"] == 5
367+
assert first_range["content_size"] == len(first_range["content"])
368+
369+
# Check second range (end line just beyond file end)
370+
second_range = result[test_file][1]
371+
assert second_range["content"] == "Line 2\nLine 3\nLine 4\nLine 5\n"
372+
assert second_range["start_line"] == 2
373+
assert second_range["end_line"] == 5
374+
assert second_range["total_lines"] == 5
375+
assert second_range["content_size"] == len(second_range["content"])

0 commit comments

Comments
 (0)