diff --git a/.changeset/mcp-section-links.md b/.changeset/mcp-section-links.md new file mode 100644 index 000000000..09f828501 --- /dev/null +++ b/.changeset/mcp-section-links.md @@ -0,0 +1,5 @@ +--- +"gitbook": patch +--- + +Point MCP `searchDocumentation` results to the matching section, and let `getPage` return one section from a `#anchor` URL, or the outline of a very long page. diff --git a/packages/gitbook/src/lib/mcp/pageSections.test.ts b/packages/gitbook/src/lib/mcp/pageSections.test.ts new file mode 100644 index 000000000..1a44ab734 --- /dev/null +++ b/packages/gitbook/src/lib/mcp/pageSections.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'bun:test'; + +import type { JSONDocument } from '@gitbook/api'; + +import { MAX_PAGE_MARKDOWN_LENGTH, getPageMarkdownForMcp } from './pageSections'; + +const PAGE_URL = 'https://docs.example.com/reference/tools'; + +const DOCUMENT = { + object: 'document', + data: {}, + nodes: [ + heading('heading-1', 'searchworkflows', 'search_workflows'), + heading('heading-2', 'parameters', 'Parameters'), + heading('heading-1', 'getworkflow', 'get_workflow'), + heading('heading-2', 'parameters-1', 'Parameters'), + ], +} as unknown as JSONDocument; + +const MARKDOWN = [ + '# Tools reference', + '## search\\_workflows ', + 'Searches workflows.', + '### Parameters', + 'limit: the maximum number of results.', + '## get\\_workflow', + 'Gets one workflow.', + '### Parameters', + 'workflowId: the ID of the workflow.', +].join('\n\n'); + +describe('getPageMarkdownForMcp', () => { + it('returns the section of the anchor, among headings with the same text', async () => { + const markdown = await getPageMarkdownForMcp({ + markdown: MARKDOWN, + url: `${PAGE_URL}#parameters-1`, + getDocument: async () => DOCUMENT, + }); + + expect(markdown).toContain('workflowId'); + expect(markdown).not.toContain('limit'); + expect(markdown).not.toContain('Gets one workflow'); + }); + + it('keeps the subsections of the anchor and stops at the next heading as high', async () => { + const markdown = await getPageMarkdownForMcp({ + markdown: MARKDOWN, + url: `${PAGE_URL}#searchworkflows`, + getDocument: async () => DOCUMENT, + }); + + expect(markdown).toContain('limit'); + expect(markdown).not.toContain('get\\_workflow'); + }); + + it('returns a short page whole without reading its document', async () => { + let documentRead = false; + const markdown = await getPageMarkdownForMcp({ + markdown: MARKDOWN, + url: PAGE_URL, + getDocument: async () => { + documentRead = true; + return DOCUMENT; + }, + }); + + expect(markdown).toBe(MARKDOWN); + expect(documentRead).toBe(false); + }); + + it('returns the page when the anchor matches no heading', async () => { + const markdown = await getPageMarkdownForMcp({ + markdown: MARKDOWN, + url: `${PAGE_URL}#unknown`, + getDocument: async () => DOCUMENT, + }); + + expect(markdown).toBe(MARKDOWN); + }); + + it('returns the outline and start of a page too long to return whole', async () => { + const longMarkdown = `${MARKDOWN}\n\n${'x'.repeat(MAX_PAGE_MARKDOWN_LENGTH)}`; + + const markdown = await getPageMarkdownForMcp({ + markdown: longMarkdown, + url: PAGE_URL, + getDocument: async () => DOCUMENT, + }); + + expect(markdown.length).toBeLessThan(MAX_PAGE_MARKDOWN_LENGTH); + expect(markdown).toContain(`- [search_workflows](${PAGE_URL}#searchworkflows)`); + expect(markdown).toContain(` - [Parameters](${PAGE_URL}#parameters-1)`); + expect(markdown).toContain('Searches workflows.'); + }); +}); + +function heading(type: 'heading-1' | 'heading-2', id: string, text: string) { + return { + object: 'block', + type, + key: id, + meta: { id }, + data: {}, + nodes: [ + { object: 'text', key: `${id}-text`, leaves: [{ object: 'leaf', text, marks: [] }] }, + ], + }; +} diff --git a/packages/gitbook/src/lib/mcp/pageSections.ts b/packages/gitbook/src/lib/mcp/pageSections.ts new file mode 100644 index 000000000..172399ebb --- /dev/null +++ b/packages/gitbook/src/lib/mcp/pageSections.ts @@ -0,0 +1,169 @@ +import type { Heading, RootContent } from 'mdast'; +import { fromMarkdown } from 'mdast-util-from-markdown'; +import { gfmFromMarkdown } from 'mdast-util-gfm'; +import { gfm } from 'micromark-extension-gfm'; +import { visit } from 'unist-util-visit'; + +import type { + DocumentBlock, + DocumentFragment, + DocumentInline, + DocumentText, + JSONDocument, +} from '@gitbook/api'; + +import { getNodeText } from '@/lib/document'; +import { toPageMarkdown } from '@/lib/markdownPage'; + +/** MCP clients cap the size of a tool result, so a longer page is returned as its outline. */ +export const MAX_PAGE_MARKDOWN_LENGTH = 50_000; + +const LONG_PAGE_START_LENGTH = 20_000; +const OUTLINE_MAX_LEVEL = 2; +const HEADING_LEVELS: Record = { 'heading-1': 1, 'heading-2': 2, 'heading-3': 3 }; + +type DocumentNode = DocumentBlock | DocumentFragment | DocumentInline | DocumentText; + +/** A heading of a page and the anchor its section is linked with. */ +export type PageHeading = { id: string; text: string; level: number }; + +/** What `getPage` returns: the anchor's section, the outline of a too-long page, or the page. */ +export async function getPageMarkdownForMcp({ + markdown, + url, + getDocument, +}: { + markdown: string; + url: string; + getDocument: () => Promise; +}): Promise { + const pageURL = new URL(url); + const anchor = decodeURIComponent(pageURL.hash.slice(1)); + pageURL.hash = ''; + + if (!anchor && markdown.length <= MAX_PAGE_MARKDOWN_LENGTH) { + return markdown; + } + + const document = await getDocument(); + const headings = document ? getPageHeadings(document) : []; + const section = anchor ? getMarkdownSection({ markdown, headings, anchor }) : undefined; + if (section) { + return section; + } + + return markdown.length > MAX_PAGE_MARKDOWN_LENGTH + ? getLongPageMarkdown({ markdown, headings, pageURL: pageURL.toString() }) + : markdown; +} + +/** The headings of a document that have an anchor, in order, including nested ones. */ +export function getPageHeadings(document: JSONDocument): PageHeading[] { + const headings: PageHeading[] = []; + collectHeadings(document.nodes, headings); + return headings; +} + +/** The section under the anchor's heading, found by text and rank: markdown may lack anchors. */ +export function getMarkdownSection({ + markdown, + headings, + anchor, +}: { + markdown: string; + headings: PageHeading[]; + anchor: string; +}): string | undefined { + const targetIndex = headings.findIndex((heading) => heading.id === anchor); + const target = headings[targetIndex]; + if (!target) { + return undefined; + } + const rank = headings + .slice(0, targetIndex) + .filter((heading) => heading.text === target.text).length; + + const nodes = fromMarkdown(markdown, { + extensions: [gfm()], + mdastExtensions: [gfmFromMarkdown()], + }).children; + + // Depth 1 is the page title; the document's headings start at depth 2. + const matches = nodes.flatMap((node, index) => + node.type === 'heading' && node.depth > 1 && getHeadingText(node) === target.text + ? [index] + : [] + ); + const start = matches[rank]; + if (start === undefined) { + return undefined; + } + + const depth = (nodes[start] as Heading).depth; + const end = nodes.findIndex( + (node, index) => index > start && node.type === 'heading' && node.depth <= depth + ); + return toPageMarkdown({ + type: 'root', + children: nodes.slice(start, end === -1 ? undefined : end), + }); +} + +function getLongPageMarkdown({ + markdown, + headings, + pageURL, +}: { + markdown: string; + headings: PageHeading[]; + pageURL: string; +}): string { + const outline = headings + .filter((heading) => heading.level <= OUTLINE_MAX_LEVEL) + .map( + (heading) => + `${' '.repeat(heading.level - 1)}- [${heading.text}](${pageURL}#${heading.id})` + ); + + return [ + `This page is ${markdown.length} characters long, too long to return whole. Below are its outline and its first ${LONG_PAGE_START_LENGTH} characters. To read a section, call getPage with the section's link from the outline.`, + '## Outline', + outline.join('\n'), + '## Start of the page', + markdown.slice(0, LONG_PAGE_START_LENGTH), + ].join('\n\n'); +} + +function collectHeadings(nodes: readonly DocumentNode[], headings: PageHeading[]) { + for (const node of nodes) { + if (node.object === 'text') { + continue; + } + + const level = node.object === 'block' ? HEADING_LEVELS[node.type] : undefined; + if (node.object === 'block' && level) { + const id = 'meta' in node && node.meta && 'id' in node.meta ? node.meta.id : undefined; + if (id) { + headings.push({ id, text: getNodeText(node).trim(), level }); + } + continue; + } + + if ('nodes' in node) { + collectHeadings(node.nodes, headings); + } + if ('fragments' in node && node.fragments) { + collectHeadings(node.fragments, headings); + } + } +} + +function getHeadingText(heading: Heading): string { + let text = ''; + visit(heading, (node: RootContent) => { + if (node.type === 'text' || node.type === 'inlineCode') { + text += node.value; + } + }); + return text.trim(); +} diff --git a/packages/gitbook/src/lib/mcp/tools.ts b/packages/gitbook/src/lib/mcp/tools.ts index 72487fa5f..7abe2bb39 100644 --- a/packages/gitbook/src/lib/mcp/tools.ts +++ b/packages/gitbook/src/lib/mcp/tools.ts @@ -5,11 +5,13 @@ import { z } from 'zod'; import { AgentFeedbackSource, + RevisionPageType, SiteInsightsDisplayContext, type SiteSpace, type SiteStructure, } from '@gitbook/api'; +import { getPageMarkdownForMcp } from './pageSections'; import type { SearchSiteContentScope } from '@/components/Search/search-types'; import { resolveSitePageFromURL } from '@/components/SitePage/fetch'; import { isAIEnabled } from '@/components/utils/isAIChatEnabled'; @@ -22,8 +24,8 @@ import { import { submitAgentFeedback } from '@/lib/agentFeedback/server'; import { renderAskSourcesMarkdown, streamSiteAskAnswer } from '@/lib/ask'; import { getAskVisitorAgent } from '@/lib/ask-visitor'; -import type { GitBookSiteContext } from '@/lib/context'; -import { getExposableError, throwIfDataError } from '@/lib/data'; +import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/context'; +import { getExposableError, getPageDocument, throwIfDataError } from '@/lib/data'; import { getLogger } from '@/lib/logger'; import { fromPageMarkdown, getMarkdownForPageInSpace, toPageMarkdown } from '@/lib/markdownPage'; import { joinPathWithBaseURL } from '@/lib/paths'; @@ -69,11 +71,12 @@ export function createSiteMcpTools( const examplePageURL = siteUrl ? joinPathWithBaseURL(siteUrl, 'getting-started') : undefined; const endpointLanguage = normalizeLanguage(context.siteSpace.space.language); const siteLanguages = getSiteSpaceLanguages(listAllSiteSpaces(context.structure)); + const aiEnabled = isAIEnabled(context.customization.ai.mode); const tools: SiteMcpTool[] = [ defineTool({ name: 'searchDocumentation', - description: `Search across the documentation to find relevant information, code examples, API references, and guides. Use this tool when you need to answer questions about ${site.title}, find specific documentation, understand how features work, or locate implementation details. The search returns contextual content with titles and direct links to the documentation pages.`, + description: `Search across the documentation to find relevant information, code examples, API references, and guides. Use this tool when you need to answer questions about ${site.title}, find specific documentation, understand how features work, or locate implementation details. It is a keyword search: query with the words the documentation would use, such as a feature, setting, option, function or error message, rather than a full question. Each result links to its best-matching section; pass that link to \`getPage\` to read the section.${aiEnabled ? ' To get a direct answer to a question in natural language, use `askQuestion`.' : ''}`, inputSchema: { query: z.string(), ...languageArgument(siteLanguages, endpointLanguage), @@ -147,24 +150,30 @@ export function createSiteMcpTools( } return result.pages.map((pageResult) => { - const pageURL = linker.toAbsoluteURL( - linker.toLinkForContent( - joinPathWithBaseURL(spaceURL, pageResult.path) - ) - ); - // The search API returns sections ordered highest-score-first, so // the first section with a body is the best-scoring preview. - const body = (pageResult.sections ?? []).find( + const section = (pageResult.sections ?? []).find( (section) => section.body - )?.body; + ); + // A page-level match comes with an arbitrary section: link the page. + const matchedSection = + section?.resultType !== 'page' ? section : undefined; + const url = linker.toAbsoluteURL( + linker.toLinkForContent( + joinPathWithBaseURL( + spaceURL, + matchedSection?.path ?? pageResult.path + ) + ) + ); return { type: 'text', text: [ `Title: ${pageResult.title}`, - `Link: ${pageURL}`, - body ? `Content: ${body}` : '', + matchedSection?.title ? `Section: ${matchedSection.title}` : '', + `Link: ${url}`, + section ? `Content: ${section.body}` : '', ] .filter(Boolean) .join('\n'), @@ -177,7 +186,7 @@ export function createSiteMcpTools( defineTool({ name: 'getPage', - description: `Fetch the full markdown content of a specific documentation page from ${site.title}. Use this when you have a page URL and want to read its content. Accepts full URLs (e.g. ${examplePageURL}). Since \`searchDocumentation\` returns partial content, use \`getPage\` to retrieve the complete page when you need more details. The content includes links you can follow to navigate to related pages.`, + description: `Fetch the full markdown content of a specific documentation page from ${site.title}. Use this when you have a page URL and want to read its content. Accepts full URLs (e.g. ${examplePageURL}). Since \`searchDocumentation\` returns partial content, use \`getPage\` to retrieve the complete page when you need more details. A URL with a #anchor, like the section links \`searchDocumentation\` returns, returns only that section. A very long page returns its outline, with a link to each section, and its start. The content includes links you can follow to navigate to related pages.`, inputSchema: { url: z .string() @@ -213,11 +222,18 @@ export function createSiteMcpTools( }; } - const markdown = await getMarkdownForPageInSpace( - context, - resolved.siteSpace, - resolved.page - ); + const { page, siteSpace } = resolved; + const markdown = await getPageMarkdownForMcp({ + markdown: await getMarkdownForPageInSpace(context, siteSpace, page), + url, + getDocument: async () => + page.type === RevisionPageType.Document + ? getPageDocument( + await fetchSiteContextForSiteSpace(context, siteSpace), + page + ) + : null, + }); trackMcpEvent({ organizationId: context.organizationId, @@ -250,7 +266,7 @@ export function createSiteMcpTools( // Only expose the answer tool when the site has AI enabled, since it relies on // the same AI search backend that powers the site's "ask a question" experience. - if (isAIEnabled(context.customization.ai.mode)) { + if (aiEnabled) { tools.push( defineTool({ name: 'askQuestion',