MCPcopy Create free account
hub / github.com/adcontextprotocol/adcp / trimConversationHistory

Function trimConversationHistory

server/src/utils/token-limiter.ts:172–263  ·  view source on GitHub ↗
(
  messages: MessageTurn[],
  tokenLimit: number
)

Source from the content-addressed store, hash-verified

170 * @returns Trimmed messages and metadata
171 */
172export function trimConversationHistory(
173 messages: MessageTurn[],
174 tokenLimit: number
175): TrimResult {
176 if (messages.length === 0) {
177 return {
178 messages: [],
179 estimatedTokens: 0,
180 messagesRemoved: 0,
181 wasTrimmed: false,
182 };
183 }
184
185 const originalCount = messages.length;
186
187 // Estimate tokens for each message, including tool call content
188 const messagesWithTokens = messages.map(msg => {
189 let tokens = estimateTokens(msg.content);
190 if (msg.toolCalls) {
191 for (const tc of msg.toolCalls) {
192 tokens += estimateTokens(tc.name);
193 tokens += estimateTokens(tc.result);
194 if (tc.input) tokens += estimateTokens(JSON.stringify(tc.input));
195 }
196 }
197 return { message: msg, tokens };
198 });
199
200 // Start from the end (most recent) and work backwards
201 let totalTokens = 0;
202 const includedMessages: MessageTurn[] = [];
203
204 // Always try to include the most recent message (current user turn)
205 // Work backwards from the end
206 for (let i = messagesWithTokens.length - 1; i >= 0; i--) {
207 const { message, tokens } = messagesWithTokens[i];
208
209 if (totalTokens + tokens <= tokenLimit) {
210 // Fits within limit - add to front (to maintain order)
211 includedMessages.unshift(message);
212 totalTokens += tokens;
213 } else if (includedMessages.length === 0) {
214 // Even the most recent message doesn't fit - truncate it
215 const availableChars = Math.floor(tokenLimit * 3.5);
216 const truncateAt = Math.max(0, availableChars - 100);
217 const truncatedContent = message.content.substring(0, truncateAt) +
218 '\n\n[Message truncated due to length]';
219
220 logger.warn(
221 {
222 originalTokens: tokens,
223 truncatedTo: estimateTokens(truncatedContent),
224 tokenLimit,
225 },
226 'Token limiter: Truncated single message that exceeded limit'
227 );
228
229 includedMessages.unshift({

Callers 2

Calls 2

estimateTokensFunction · 0.85
warnMethod · 0.80

Tested by

no test coverage detected