Line-Context File Reading
Implement the agent reading tool, formatting content with line numbers and supporting line range queries.
Why Coding Agents Need Line Context
When language models inspect source code in tools like Claude Code or Codex, plain text is not enough. The model needs precise line references to reason about code blocks, report diagnostic locations, and calculate exact substitutions. For this reason, agent reading tools format content with 1-based line numbers and support slicing via start_line and end_line.
Input and Output Protocol
Your program reads a JSON object from standard input containing the operation and the in-memory workspace:
{
"op": "read_file",
"workspace": {
"hello.py": "print('hello')\nprint('world')\n"
},
"path": "hello.py",
"start_line": 1,
"end_line": 2
}
When successful, write compact JSON to standard output with keys in alphabetical order:
{
"content": "1: print('hello')\n2: print('world')\n",
"status": "ok",
"total_lines": 2
}
The keys are:
content: string containing the requested lines, each prefixed with"{num}: {line}\n". If the file is empty or range has no lines, returns"".status: always"ok"on success.total_lines: integer representing the total line count of the file.
Error Handling
If the path does not exist in workspace, if op is not "read_file", or if standard input is malformed:
- Leave standard output empty.
- Write an error description to standard error containing the word
error. - Exit with status code
1.
Acceptance Criteria
- Formats all lines with 1-based prefixes when boundaries are omitted.
- Correctly filters lines when
start_lineandend_lineare provided. - Gracefully clamps boundaries when
end_lineexceeds total line count. - Rejects missing files and invalid JSON with exit code 1.