Skip to content

Commit 278c0dc

Browse files
authored
fix: return truncated content when token limit exceeded in MCP search_code (#604)
When search results exceed maxTokens limit, now returns partial truncated content instead of discarding the file completely. Changes: - Calculate remaining token budget before breaking - Truncate file content to fit within remaining tokens (if > 100 tokens left) - Append truncation marker to indicate content was cut off - Still add truncation message at end of all results Benefits: - Users get partial data instead of nothing - Better debugging and analysis experience - More useful for AI-powered code analysis tasks - Consistent with expected behavior when limits are reached Example: If file would use 10K tokens but only 2K remain, return first ~8K chars of content + truncation marker instead of dropping it. Signed-off-by: Wayne Sun <gsun@redhat.com>
1 parent 6f64d5b commit 278c0dc

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

packages/mcp/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Fixed
11+
- Fixed issue where search results exceeding token limits would be completely discarded instead of returning truncated content. [#604](https://github.com/sourcebot-dev/sourcebot/pull/604)
12+
1013
## [1.0.7] - 2025-10-28
1114
- Updated API client to match the latest Sourcebot release. [#555](https://github.com/sourcebot-dev/sourcebot/pull/555)
1215

packages/mcp/src/index.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,22 @@ server.tool(
123123
const tokens = text.length / 4;
124124

125125
if ((totalTokens + tokens) > maxTokens) {
126+
// Calculate remaining token budget
127+
const remainingTokens = maxTokens - totalTokens;
128+
129+
if (remainingTokens > 100) { // Only truncate if meaningful space left
130+
// Truncate text to fit remaining tokens (tokens ≈ chars/4)
131+
const maxLength = Math.floor(remainingTokens * 4);
132+
const truncatedText = text.substring(0, maxLength) + "\n\n...[content truncated due to token limit]";
133+
134+
content.push({
135+
type: "text",
136+
text: truncatedText,
137+
});
138+
139+
totalTokens += remainingTokens;
140+
}
141+
126142
isResponseTruncated = true;
127143
break;
128144
}

0 commit comments

Comments
 (0)