diff --git a/server/mcp/index.ts b/server/mcp/index.ts index dca3319870..2b916a61d8 100644 --- a/server/mcp/index.ts +++ b/server/mcp/index.ts @@ -112,4 +112,4 @@ Base64-encoded images are supported in document content for all formats. When cr Each user can have a personal collection, marked with isPersonal. It is private to that user, cannot be shared as a collection, and cannot be renamed or archived. Use the collectionId "personal" in create_document, move_document or update_document to place a document in it; the collection is created if it does not exist yet. -When asked to create a document that follows a template, use the "list_templates" tool to find a matching template; each result already includes the template body as markdown. To use it unchanged, pass its ID as templateId to "create_document" and the new document is pre-filled from it. To adapt it first, modify the returned body and pass the result as the text parameter to "create_document". Either way no separate fetch is needed.`; +When asked to create a document that follows a template, use the "list_templates" tool to find a matching template. To use it unchanged, pass its ID as templateId to "create_document" and the new document is pre-filled from it. To adapt it first, read its body with the "fetch" tool (resource "template"), modify it, and pass the result as the text parameter to "create_document".`; diff --git a/server/mcp/skills/collection-digest/SKILL.md b/server/mcp/skills/collection-digest/SKILL.md index fb3419290f..b1e807fb14 100644 --- a/server/mcp/skills/collection-digest/SKILL.md +++ b/server/mcp/skills/collection-digest/SKILL.md @@ -30,5 +30,5 @@ All tools named in this skill are tools of the Outline MCP server. - `list_collections` – resolve the collection ID. - `list_documents` – `{ collectionId, includeArchived?, offset, limit }`; each result has `document.updatedAt`, `document.createdAt`, and `document.url`. -- `fetch` – `{ resource: "document", id }` to read the full markdown. +- `fetch` – `{ resource: "document", id, offset? }` to read the markdown. If the metadata has `nextOffset`, call `fetch` again with that `offset` to read the next page. - `list_comments` – `{ collectionId, statusFilter: ["unresolved"] }` to include open discussions. diff --git a/server/mcp/skills/find-and-cite/SKILL.md b/server/mcp/skills/find-and-cite/SKILL.md index ca46bbc6ff..f7ec703ae6 100644 --- a/server/mcp/skills/find-and-cite/SKILL.md +++ b/server/mcp/skills/find-and-cite/SKILL.md @@ -15,7 +15,7 @@ All tools named in this skill are tools of the Outline MCP server. 1. Search with `list_documents` and a short `query` of key terms. Every word in the query must match. To match any of several terms, put “or” between them. To match an exact phrase, put the whole query in double quotes. Run separate searches for different phrasings. 2. Use the `context` snippet in each result to pick the best candidates. Narrow with `collectionId` when the user names a collection. -3. Read the top candidates with `fetch` (`resource: "document"`). The second content block is the full markdown. +3. Read the top candidates with `fetch` (`resource: "document"`). The second content block is the markdown. If the metadata has `nextOffset`, call `fetch` again with that `offset` to read the next page. 4. Answer the question in your own words, then quote the passage that supports it and link to the document `url`. Include the `breadcrumb`, when present, so the user knows where the document sits. 5. When documents disagree, say so, and show the `updatedAt` date of each so the user can judge which is current. @@ -29,5 +29,5 @@ All tools named in this skill are tools of the Outline MCP server. ## Tool reference - `list_documents` – `{ query, collectionId?, includeArchived?, limit }`; results include `document` and, with a `query`, `context`. `breadcrumb` and `shareUrl` are optional. -- `fetch` – `{ resource: "document", id }`; accepts an ID or a document URL. +- `fetch` – `{ resource: "document", id, offset? }`; accepts an ID or a document URL. - `list_collection_documents` – `{ collectionId }` to browse a collection’s structure when search is not enough. diff --git a/server/mcp/skills/meeting-notes/SKILL.md b/server/mcp/skills/meeting-notes/SKILL.md index 77888bc282..704f99521e 100644 --- a/server/mcp/skills/meeting-notes/SKILL.md +++ b/server/mcp/skills/meeting-notes/SKILL.md @@ -14,10 +14,10 @@ All tools named in this skill are tools of the Outline MCP server. ## Quick start 1. Collect the meeting name, date, attendees, and purpose. Ask for anything missing that the template needs. -2. Find a template with `list_templates`. Prefer a template whose title contains “meeting”, “notes”, “agenda”, or “1:1”. Each result includes the template body as markdown. Results are newest first, 25 for each page; use `offset` to see more. +2. Find a template with `list_templates`. Prefer a template whose title contains “meeting”, “notes”, “agenda”, or “1:1”. Results are newest first, 25 for each page; use `offset` to see more. 3. Choose how to use the template: - Unchanged: pass its `id` as `templateId` to `create_document`. - - Adapted: edit the returned `text`, fill in the known fields, and pass the result as `text`. + - Adapted: read the body with `fetch` (`resource: "template"`), fill in the known fields, and pass the result as `text`. 4. Resolve the destination collection with `list_collections`. Use the template’s `collectionId` when it has one. 5. Create the document with `create_document` and share the `url`. 6. After the meeting, add decisions and action items with `update_document`. Use `editMode: "patch"` and set `findText` to the exact markdown of the section to fill, so the rest of the document keeps its formatting. When there is no such section, use `editMode: "append"`. @@ -31,7 +31,8 @@ All tools named in this skill are tools of the Outline MCP server. ## Tool reference -- `list_templates` – `{ collectionId?, offset?, limit? }`; results include `id`, `title`, `collectionId`, `text`. +- `list_templates` – `{ collectionId?, offset?, limit? }`; results include `id`, `title`, `collectionId`. +- `fetch` – `{ resource: "template", id }`; the second content block is the template body as markdown. - `create_document` – `{ title, templateId?, text?, collectionId, publish }`. - `update_document` – `{ id, editMode: "patch", findText, text }` or `editMode: "append"`. - `list_users` – `{ query }` to resolve attendee IDs. diff --git a/server/mcp/tools/fetch.test.ts b/server/mcp/tools/fetch.test.ts index 53d2acd52e..1d2a54691c 100644 --- a/server/mcp/tools/fetch.test.ts +++ b/server/mcp/tools/fetch.test.ts @@ -108,6 +108,8 @@ describe("fetch", () => { expect(metadata.document.id).toEqual(document.id); expect(metadata.document.title).toEqual(document.title); expect(metadata.document.url).toMatch(/^https?:\/\//); + expect(metadata.textLength).toBeUndefined(); + expect(metadata.nextOffset).toBeUndefined(); // Second content is markdown text expect(res!.result!.content![1].text).toContain("Hello"); @@ -253,4 +255,109 @@ describe("fetch", () => { expect(res!.result!.content![1].text).toContain("Body of the template"); }); + + it("pages long document text on line boundaries", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const lines = Array.from({ length: 50 }, (_, i) => `Line ${i}`); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + text: lines.join("\n\n"), + }); + + let offset = 0; + let combined = ""; + let pages = 0; + let textLength = 0; + + do { + const res = await callMcpTool(server, accessToken, "fetch", { + resource: "document", + id: document.id, + offset, + limit: 100, + }); + const metadata = JSON.parse(res!.result!.content![0].text ?? "{}"); + const text = res!.result!.content![1].text ?? ""; + + expect(text.length).toBeLessThanOrEqual(100); + if (metadata.nextOffset !== undefined) { + expect(text.endsWith("\n")).toBe(true); + } + + combined += text; + textLength = metadata.textLength ?? textLength; + offset = metadata.nextOffset; + pages++; + } while (offset !== undefined); + + expect(pages).toBeGreaterThan(1); + expect(combined.length).toEqual(textLength); + expect(combined).toContain("Line 0"); + expect(combined).toContain("Line 49"); + }); + + it("cuts a line longer than the limit", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + text: "a".repeat(250), + }); + + const res = await callMcpTool(server, accessToken, "fetch", { + resource: "document", + id: document.id, + limit: 100, + }); + const metadata = JSON.parse(res!.result!.content![0].text ?? "{}"); + + expect(res!.result!.content![1].text).toEqual("a".repeat(100)); + expect(metadata.nextOffset).toEqual(100); + }); + + it("does not split a surrogate pair between pages", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + text: `${"a".repeat(99)}😀b`, + }); + + const first = await callMcpTool(server, accessToken, "fetch", { + resource: "document", + id: document.id, + limit: 100, + }); + const firstMetadata = JSON.parse(first!.result!.content![0].text ?? "{}"); + + expect(first!.result!.content![1].text).toEqual(`${"a".repeat(99)}😀`); + expect(firstMetadata.nextOffset).toEqual(101); + + const second = await callMcpTool(server, accessToken, "fetch", { + resource: "document", + id: document.id, + offset: 99, + limit: 1, + }); + const secondMetadata = JSON.parse(second!.result!.content![0].text ?? "{}"); + + expect(second!.result!.content![1].text).toEqual("😀"); + expect(secondMetadata.nextOffset).toEqual(101); + }); }); diff --git a/server/mcp/tools/fetch.ts b/server/mcp/tools/fetch.ts index 6f0897e3c9..be6363a8bc 100644 --- a/server/mcp/tools/fetch.ts +++ b/server/mcp/tools/fetch.ts @@ -10,7 +10,9 @@ import { import { authorize, can } from "@server/policies"; import { AuthorizationError } from "@server/errors"; import { presentNavigationNode, presentUser } from "@server/presenters"; +import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; +import { TextHelper } from "@shared/utils/TextHelper"; import { presentCollection } from "./collections"; import { presentDocument } from "./documents"; import { presentTemplate } from "./templates"; @@ -27,6 +29,38 @@ import { const SELF_TOKENS = new Set(["self", "me", "current_user"]); +/** Fits most MCP client result limits, even for CJK text at about one token per character. */ +const DEFAULT_TEXT_LIMIT = 16_000; + +/** + * Returns one page of a long text. The page ends after a line break where + * possible so that a markdown line is not split between pages, and never + * splits a surrogate pair. + * + * @param text - the full text. + * @param range - the UTF-16 index to start from and the maximum number of code points to return. + * @returns the page text, and the next page offset and full text length if more text remains. + */ +function paginateText( + text: string, + { offset, limit }: { offset: number; limit: number } +) { + // A code point is at most two UTF-16 units, so this slice holds a full page. + let page = TextHelper.truncate(text.slice(offset, offset + limit * 2), limit); + if (offset + page.length < text.length) { + const lineEnd = page.lastIndexOf("\n"); + if (lineEnd > 0) { + page = page.slice(0, lineEnd + 1); + } + } + const end = offset + page.length; + + return { + text: page, + ...(end < text.length && { nextOffset: end, textLength: text.length }), + }; +} + /** * Extracts a resource identifier from a value that may be a URL or a plain ID. * When a URL is detected the last non-empty path segment is returned as the @@ -101,7 +135,7 @@ export function fetchTool(server: McpServer, scopes: string[]) { { title: "Fetch", description: - 'Fetches a document, collection, user, attachment, or template by type and ID. When fetching a collection the response includes the full hierarchical document tree. For users, "current_user" can be used as the ID to get the authenticated user. For attachments, the response includes a short-lived signed URL that can be used to download the file contents directly. For templates, the response includes the template body as markdown.', + 'Fetches a document, collection, user, attachment, or template by type and ID. When fetching a collection the response includes the full hierarchical document tree. For users, "current_user" can be used as the ID to get the authenticated user. For attachments, the response includes a short-lived signed URL that can be used to download the file contents directly. For templates, the response includes the template body as markdown. Document and template text is returned in pages: when the response includes nextOffset, call fetch again with offset set to that value to read the next page.', annotations: { destructiveHint: false, idempotentHint: true, @@ -115,9 +149,26 @@ export function fetchTool(server: McpServer, scopes: string[]) { .describe( 'The unique identifier or URL. For users, "current_user" returns the authenticated user.' ), + offset: z.coerce + .number() + .int() + .min(0) + .default(0) + .describe( + "For documents and templates, the character offset to start reading text from. Use nextOffset from the previous response. Defaults to 0." + ), + limit: z.coerce + .number() + .int() + .min(1) + .max(100_000) + .default(DEFAULT_TEXT_LIMIT) + .describe( + `For documents and templates, the maximum number of text characters to return. Defaults to ${DEFAULT_TEXT_LIMIT}, max 100000.` + ), }), }, - withTracing("fetch", async ({ resource, id: rawId }, extra) => { + withTracing("fetch", async ({ resource, id: rawId, ...range }, extra) => { try { const actor = getActorFromContext(extra); const id = extractId(rawId); @@ -142,6 +193,10 @@ export function fetchTool(server: McpServer, scopes: string[]) { getDocumentBreadcrumb(document, actor), getPublicShareUrlForDocument(actor.team, document.id), ]); + const page = paginateText( + typeof text === "string" ? text : "", + range + ); return { content: [ { @@ -150,11 +205,13 @@ export function fetchTool(server: McpServer, scopes: string[]) { document: pathToUrl(actor.team, attributes), ...(breadcrumb !== undefined && { breadcrumb }), ...(shareUrl !== undefined && { shareUrl }), + textLength: page.textLength, + nextOffset: page.nextOffset, }), }, { type: "text" as const, - text: typeof text === "string" ? text : "", + text: page.text, }, ], } satisfies CallToolResult; @@ -235,16 +292,27 @@ export function fetchTool(server: McpServer, scopes: string[]) { authorize(actor, "read", template); - const { text, ...attributes } = await presentTemplate(template); + const page = paginateText( + template.content + ? await DocumentHelper.toMarkdown(template.content, { + includeTitle: false, + }) + : "", + range + ); return { content: [ { type: "text" as const, - text: JSON.stringify(pathToUrl(actor.team, attributes)), + text: JSON.stringify({ + ...pathToUrl(actor.team, presentTemplate(template)), + textLength: page.textLength, + nextOffset: page.nextOffset, + }), }, { type: "text" as const, - text, + text: page.text, }, ], } satisfies CallToolResult; diff --git a/server/mcp/tools/templates.test.ts b/server/mcp/tools/templates.test.ts index 6f91013292..f1e2cdeaf0 100644 --- a/server/mcp/tools/templates.test.ts +++ b/server/mcp/tools/templates.test.ts @@ -40,10 +40,10 @@ describe("list_templates", () => { const match = data.find( (t: { id: string }) => t.id === workspaceTemplate.id - ) as { url: string; collectionId: string | null; text: string }; + ) as { url: string; collectionId: string | null; text?: string }; expect(match.url).toMatch(/^https?:\/\//); expect(match.collectionId).toBeNull(); - expect(match.text).toContain("Body of the workspace template"); + expect(match.text).toBeUndefined(); }); it("filters by collection", async () => { diff --git a/server/mcp/tools/templates.ts b/server/mcp/tools/templates.ts index b0803d9ae8..f30505fa86 100644 --- a/server/mcp/tools/templates.ts +++ b/server/mcp/tools/templates.ts @@ -3,7 +3,6 @@ import type { McpServer } from "@modelcontextprotocol/server"; import { Op } from "sequelize"; import type { WhereOptions } from "sequelize"; import { Collection, Template } from "@server/models"; -import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import { authorize } from "@server/policies"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { @@ -16,25 +15,18 @@ import { } from "../util"; /** - * Presents a template's metadata and rendered markdown body for a tool - * response. Including the body lets a caller list templates and create a - * document from one — verbatim or adapted — without a separate fetch call. + * Presents a template's metadata for a tool response. * * @param template - the template to present. - * @returns the presented template with its body as markdown. + * @returns the presented template metadata. */ -export async function presentTemplate(template: Template) { +export function presentTemplate(template: Template) { return { id: template.id, url: template.path, title: template.title, collectionId: template.collectionId ?? null, updatedAt: template.updatedAt, - text: template.content - ? await DocumentHelper.toMarkdown(template.content, { - includeTitle: false, - }) - : "", }; } @@ -52,7 +44,7 @@ export function templateTools(server: McpServer, scopes: string[]) { { title: "List templates", description: - "Lists document templates the user has access to, including workspace-wide templates and templates within accessible collections. Each result includes the template body as markdown. To create a document from a template unchanged, pass its ID as templateId to create_document. To adapt it first, modify the returned text and pass it as the text parameter to create_document — no separate fetch is needed.", + 'Lists document templates the user has access to, including workspace-wide templates and templates within accessible collections. To create a document from a template unchanged, pass its ID as templateId to create_document. To read or adapt the template body, use fetch with resource "template", then pass the modified text as the text parameter to create_document.', annotations: { destructiveHint: false, idempotentHint: true, @@ -129,12 +121,11 @@ export function templateTools(server: McpServer, scopes: string[]) { limit: effectiveLimit, }); - const presented = await Promise.all( - templates.map(async (template) => - pathToUrl(user.team, await presentTemplate(template)) + return success( + templates.map((template) => + pathToUrl(user.team, presentTemplate(template)) ) ); - return success(presented); } catch (message) { return error(message); }