Return only the file text an agent needs to keep token usage low
You will change your MCP file tools to return only the requested span, which keeps token use down and keeps secrets out of tool responses.
Whole-file responses
- read_file returns the entire file
- Secrets can end up in tool output
- Silent truncation hides what was left out
Narrow responses
- Tools take a path and line range
- Search returns matching spans only
- Truncation marker reports what remains
Why it matters
Tool output goes straight into the agent's context, so an oversized response costs tokens on every step that follows. The same surface can also leak secrets. pi-mcp-adapter stored OAuth tokens in plaintext JSON files that any process running as the same user could read (issue 180 (opens external site)). Keep credentials and whole-file dumps out of what your tools return.
Steps
- Give file-reading tools explicit inputs for a path and a line range, and let the agent request only the span it needs.
- Use a small default window when no range is given, and state that default in the tool's parameter description.
- Add a search tool that returns matching line numbers with a few lines of context, so the agent can read the relevant span instead of the whole file.
- Return a short notice for binary, generated, or skipped files instead of their contents.
- Mark truncated responses clearly and report the total size, so the agent knows more content exists and can ask for it.
- Keep secrets out of tool output and out of config files. For mcporter, set
oauthClientSecretEnvto the name of an environment variable that holds the client secret, rather than writing the secret into the config (issue 132 (opens external site)). - Measure the characters returned per call against a large real repository before you ship.
Common mistakes
- Returning the full file and expecting the agent to ignore the rest. The tokens are already spent.
- Truncating silently, so the agent assumes it saw everything.
- Echoing tokens, headers, or raw API responses back into tool output.
- Writing credentials to plain files in a directory other processes can read.
Checklist
0 of 8 done