Reduce oversized searchDocumentation MCP responses (#4352)

This commit is contained in:
Nolann B.
2026-07-01 18:00:02 +02:00
committed by GitHub
parent 7e55cd5e4c
commit 6146f8e183
4 changed files with 22 additions and 7 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Reduce the size of `searchDocumentation` MCP responses by returning only the best-matching section per page instead of concatenating every section body.
@@ -5,6 +5,7 @@ import { getExposableError, throwIfDataError } from '@/lib/data';
import { getMarkdownForPageInSpace } from '@/lib/markdownPage';
import { resolvePagePath } from '@/lib/pages';
import { joinPathWithBaseURL } from '@/lib/paths';
import { getBestScoredResult } from '@/lib/search';
import { findSiteSpaceBy, findSiteSpaceByUrl } from '@/lib/sites';
import { trackServerInsightsEvents } from '@/lib/tracking';
import { waitUntil } from '@/lib/waitUntil';
@@ -128,9 +129,9 @@ export async function handleMcpRequest(
)
);
const body = pageResult.sections
?.map((section) => section.body)
.join('\n');
const body = getBestScoredResult(
(pageResult.sections ?? []).filter((section) => section.body)
)?.body;
return {
type: 'text',
@@ -8,6 +8,7 @@ import { throwIfDataError } from '@/lib/data';
import { toEmbeddableLinkForPublishedContent } from '@/lib/embeddable-linker';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { joinPathWithBaseURL } from '@/lib/paths';
import { getBestScoredResult } from '@/lib/search';
import { getServerActionBaseContext } from '@/lib/server-actions';
import { findSiteSpaceBy, getLocalizedTitle } from '@/lib/sites';
import type {
@@ -187,10 +188,7 @@ function transformSitePageResult(args: {
}) ?? [];
// Find the best-scoring section to use as a body preview on the page result.
const bestSection = pageSections.reduce<ComputedSectionResult | undefined>(
(best, section) => (!best || section.score > best.score ? section : best),
undefined
);
const bestSection = getBestScoredResult(pageSections);
if (bestSection) {
page.bestSection = {
href: bestSection.href,
+11
View File
@@ -0,0 +1,11 @@
/**
* Return the highest-scoring item in the list, or undefined when empty.
*/
export function getBestScoredResult<T extends { score: number }>(
items: readonly T[]
): T | undefined {
return items.reduce<T | undefined>(
(best, item) => (best === undefined || item.score > best.score ? item : best),
undefined
);
}