Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 68 additions & 13 deletions server/transport/code_lean.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from __future__ import annotations

import json
import re
from collections import Counter, defaultdict
from io import StringIO
from typing import Any, NamedTuple
Expand All @@ -27,6 +28,8 @@

from server.code.api.models_common import _safe_path
from server.code.api.models_read import CODE_READ_MAX_RANGES, CodeReadRangeInput
from server.code.api.models_symbol import EDIT_CONTEXT_MAX_NAMES, CodeEditContextInput
from server.code.app.symbol.resolve import _parse_location
from server.code.domain.extract.py_notebooks import is_notebook_path
from server.code.domain.symbol_documentation import description_repeats_body

Expand Down Expand Up @@ -236,15 +239,33 @@ def _lean_grep(out: dict[str, Any]) -> None:
out["related"] = lean_code("code.grep", related)


def _grep_read_continuation(
_PYTHON_DECLARATION = re.compile(r"^(?:async\s+)?def\s+([^\W\d]\w*)\s*[\[(]")


def _python_declaration_at_hit(hit: dict[str, Any], path: str) -> bool:
definition = _PYTHON_DECLARATION.match(str(hit.get("text") or "").lstrip())
return bool(
path.endswith((".py", ".pyi"))
and definition
and definition[1] == str(hit["scope"]).rsplit("::", 1)[-1]
)


def _grep_continuation(
out: dict[str, Any],
arguments: dict[str, Any],
followups: frozenset[str],
) -> None:
"""Give excerpt callers a batch of source ranges they can read next."""
"""Give excerpt callers a batch of declarations they can retrieve next."""
contexts = out.get("contexts") or []
if arguments.get("include_body") is not False or not contexts or out.get("definitions"):
if (
arguments.get("include_body") is not False
or "loom_code_read" not in followups
or not contexts
or out.get("definitions")
):
return
selections: dict[tuple[str, int, int], CodeReadRangeInput] = {}
selections: dict[tuple[str, int, int], tuple[CodeReadRangeInput, bool]] = {}
for hit in out.get("matches") or []:
if not isinstance(hit, dict):
continue
Expand All @@ -269,15 +290,43 @@ def _grep_read_continuation(
continue
if not _safe_path(span.path) or "\0" in span.path or is_notebook_path(span.path):
continue
selections.setdefault((span.path, span.start_line, end), span)
selections.setdefault(
(span.path, span.start_line, end), (span, _python_declaration_at_hit(hit, span.path))
)
if len(selections) == CODE_READ_MAX_RANGES:
break
if selections:
params = {
"ranges": [span.model_dump() for span in selections.values()],
**{key: arguments[key] for key in ("org", "namespace") if arguments.get(key)},
if not selections:
return
options = {key: arguments[key] for key in ("org", "namespace") if arguments.get(key)}
options.update(
{
key: arguments[key]
for key in ("include_lessons", "lesson_namespaces")
if key in arguments
}
out["next"] = "For the full source, call loom_code_read with " + json.dumps(params)
)
spans = [span for span, _ in selections.values()]
if (
"loom_code_edit_context" in followups
and len(spans) <= EDIT_CONTEXT_MAX_NAMES
and all(declaration for _, declaration in selections.values())
):
names = [f"{span.path}:{span.start_line}" for span in spans]
if all(
_parse_location(name) == (span.path, span.start_line)
for name, span in zip(names, spans, strict=True)
):
try:
CodeEditContextInput(names=names)
except ValidationError:
pass
else:
out["edit_context_next"] = {
"tool": "loom_code_edit_context",
"arguments": {"names": names, **options},
}
params = {"ranges": [span.model_dump() for span in spans], **options}
out["next"] = "For the full source, call loom_code_read with " + json.dumps(params)


class _GrepBody(NamedTuple):
Expand Down Expand Up @@ -591,7 +640,13 @@ def _share_edit_test_source(out: dict[str, Any]) -> dict[str, Any]:
)


def lean_code(op_name: str, payload: Any, arguments: dict[str, Any] | None = None) -> Any:
def lean_code(
op_name: str,
payload: Any,
arguments: dict[str, Any] | None = None,
*,
followups: frozenset[str] = frozenset(),
) -> Any:
"""The MCP shape of a code.* result (see module docstring)."""
if not isinstance(payload, dict) or op_name not in LEAN_CODE_OPS:
return payload
Expand All @@ -612,8 +667,8 @@ def lean_code(op_name: str, payload: Any, arguments: dict[str, Any] | None = Non
fn = _PER_OP.get(op_name)
if fn is not None:
fn(out)
if op_name == "code.grep" and arguments is not None:
_grep_read_continuation(out, arguments)
if op_name == "code.grep" and arguments is not None and followups:
_grep_continuation(out, arguments, followups)
if op_name == "code.edit_context" and out.get("edit_targets") and out.get("definitions"):
out = _share_edit_test_source(out)
_hoist_defaults(out)
Expand Down
11 changes: 5 additions & 6 deletions server/transport/lean_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,11 @@ def mcp_op_result(
from server.transport.code_lean import lean_code
from server.transport.mcp_tools import listed_tool_names

offer_read = (
op_name == "code.grep"
and (arguments or {}).get("include_body") is False
and "loom_code_read" in listed_tool_names(toolset)
)
out = lean_code(op_name, out, arguments if offer_read else None)
followups: frozenset[str] = frozenset()
if op_name == "code.grep" and (arguments or {}).get("include_body") is False:
candidates = {"loom_code_read", "loom_code_edit_context"}
followups = frozenset(candidates.intersection(listed_tool_names(toolset)))
out = lean_code(op_name, out, arguments, followups=followups)
out = _with_ignored_args(op_name, out, arguments)
if hint is not None and isinstance(out, dict):
if hint[1] not in str(out.get("rendered") or ""):
Expand Down
4 changes: 2 additions & 2 deletions server/transport/mcp_descriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2168,8 +2168,8 @@ def revision_policy(update: str) -> str:
"`uses_brief: true` summarizes callers. Check freshness and source elision."
),
"code.grep": (
"Batch exact code and test literals with path_globs. Matches include bodies by default. "
"For source excerpts, set `include_body: false` and `context_lines`. "
"Batch exact code and test literals with path_globs. Keep default bodies for edits. "
"For excerpts, set `include_body: false` and `context_lines`. "
"Use mode=files for paths only and regex=true for RE2.\n\n"
"Scope with `path_prefix` or `path_globs`. "
"For locations, set `include_body: false`, `context_lines: 0`. "
Expand Down
81 changes: 73 additions & 8 deletions tests/unit/test_lean_code_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from typing import Any

import server.transport.lean_results as lr
from server.settings import settings
from server.transport.code_lean import lean_code


Expand Down Expand Up @@ -397,10 +398,11 @@ def test_edit_context_keeps_source_when_shared_row_would_exceed_an_original_row(
assert result["definitions"][1]["examples"] == [short]


def test_grep_excerpts_offer_a_batch_for_unread_declarations() -> None:
def test_grep_excerpts_offer_a_batch_for_unread_declarations(monkeypatch) -> None:
long = {
"path": "src/a.py",
"line": 5,
"text": "def first(value):",
"scope": "first",
"scope_start_line": 5,
"scope_end_line": 16,
Expand All @@ -414,30 +416,93 @@ def test_grep_excerpts_offer_a_batch_for_unread_declarations() -> None:
}
unusual = ["src/plugins v2/routes.py", "scripts/bootstrap", "docs/overview.md"]
more = [{**long, "path": path} for path in (*unusual, "examples/demo.IPYNB", "a" * 1025)]
async_def = {**long, "path": "src/support.py", "text": "async def first(value):"}
payload = {
"matches": [long, {**long, "line": 7}, long, short, *more],
"matches": [long, {**long, "line": 7}, long, short, async_def, *more],
"contexts": [
{"path": "src/a.py", "start_line": 4, "end_line": 8, "text": "partial"},
{"path": "src/b.py", "start_line": 1, "end_line": 4, "text": "complete"},
],
}
arguments = {"include_body": False, "org": "secondary", "namespace": "repo"}
result = lr.mcp_op_result("code.grep", payload, arguments, None, toolset="coding")
options = {
"org": "secondary",
"namespace": "repo",
"include_lessons": False,
"lesson_namespaces": ["history"],
}
arguments = {"include_body": False, **options}
edit_payload = {
**payload,
"matches": [hit for hit in payload["matches"] if hit["path"] not in unusual],
}
result = lr.mcp_op_result("code.grep", edit_payload, arguments, None, toolset="coding")
edit_step = result.pop("edit_context_next")
assert edit_step == {
"tool": "loom_code_edit_context",
"arguments": {"names": ["src/a.py:5", "src/support.py:5"], **options},
}
suggestion = result.pop("next")
label, _, params = suggestion.partition(" with ")
assert label == "For the full source, call loom_code_read"
assert json.loads(params) == {
"ranges": [
{"path": path, "start_line": 5, "end_line": 16} for path in ("src/a.py", *unusual)
{"path": path, "start_line": 5, "end_line": 16}
for path in ("src/a.py", "src/support.py")
],
"org": "secondary",
"namespace": "repo",
**options,
}
with_read = lr.mcp_op_result("code.grep", payload, arguments, None, toolset="coding")
assert "edit_context_next" not in with_read
label, _, params = with_read.pop("next").partition(" with ")
assert label == "For the full source, call loom_code_read"
assert json.loads(params) == {
"ranges": [
{"path": path, "start_line": 5, "end_line": 16}
for path in ("src/a.py", "src/support.py", *unusual)
],
**options,
}
assert result == lr.mcp_op_result("code.grep", payload, {"include_body": True}, None)
assert with_read == lr.mcp_op_result("code.grep", payload, arguments, None, toolset="all")
assert result == lr.mcp_op_result("code.grep", edit_payload, {"include_body": True}, None)
assert "next" not in lr.mcp_op_result(
"code.grep", {**payload, "contexts": []}, arguments, None, toolset="coding"
)
assert "next" not in lr.mcp_op_result("code.grep", payload, arguments, None, toolset="core")
monkeypatch.setattr(settings, "mcp_toolset", "coding")
for toolset in (None, "Coding", "coding+tracker"):
assert lr.mcp_op_result("code.grep", edit_payload, arguments, None, toolset=toolset) == {
**result,
"edit_context_next": edit_step,
"next": suggestion,
}


def test_grep_keeps_exact_ranges_for_decorators_and_batches_that_exceed_named_lookup() -> None:
declaration = {
"path": "src/a.py",
"line": 1,
"text": "def worker():",
"scope": "worker",
"scope_start_line": 1,
"scope_end_line": 12,
}
for matches in (
[{**declaration, "text": "@marker"}],
[{**declaration, "path": f"src/module{index}.py"} for index in range(9)],
):
payload = {
"matches": matches,
"contexts": [{"path": "src/a.py", "start_line": 1, "end_line": 2, "text": "partial"}],
}
result = lr.mcp_op_result(
"code.grep", payload, {"include_body": False}, None, toolset="coding"
)
assert "edit_context_next" not in result
label, _, params = result["next"].partition(" with ")
assert label == "For the full source, call loom_code_read"
assert json.loads(params) == {
"ranges": [{"path": hit["path"], "start_line": 1, "end_line": 12} for hit in matches]
}


def test_related_grep_keeps_source_and_compacts_it_like_exact_hits() -> None:
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/test_mcp_coding_toolset.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,10 +410,10 @@ def test_coding_profiles_load_source_tools_upfront(monkeypatch, profile) -> None
schema = edit["inputSchema"]
assert "name" not in schema.get("required", [])
assert {"name", "names", "clues"} <= schema["properties"].keys()
assert "Batch exact definitions with `names`" in edit["description"]
assert "Batch exact `names` or declaration `clues`" in edit["description"]
assert edit["annotations"]["readOnlyHint"]
grep = next(tool for tool in tools if tool["name"] == "loom_code_grep")
assert "Matches include bodies by default" in grep["description"]
assert "Keep default bodies for edits" in grep["description"]
assert {"include_body", "context_lines"} <= grep["inputSchema"]["properties"].keys()
if profile != "compact":
assert "loom_code_edit_context for a known definition" in grep["description"]
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/test_mcp_listing_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,11 +399,11 @@ def test_the_compact_profile_keeps_the_tool_names():
def test_compact_coding_grep_advertises_full_definitions_and_batch_scope():
compact = {t["name"]: t for t in _listing("coding", True, "compact")}
description = compact["loom_code_grep"]["description"]
assert "Matches include bodies by default" in description
assert "Keep default bodies for edits" in description
assert "Batch exact code and test literals with path_globs" in description
assert "mode=files for paths only" in description
assert "regex=true for RE2" in description
assert "For source excerpts" in description
assert "For excerpts" in description
assert "`include_body: false`" in description and "`context_lines`" in description

full = {t["name"]: t for t in _listing("coding", True, "full")}
Expand Down
Loading