import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; import { errToString } from "@shared/utils/error"; import env from "@server/env"; import { Collection, Share, type Team, type User } from "@server/models"; import { addTags } from "@server/logging/tracer"; import { traceFunction } from "@server/logging/tracing"; import { can } from "@server/policies"; import { type APIContext, AuthenticationType } from "@server/types"; import type { NavigationNode } from "@shared/types"; interface McpContext { authInfo?: AuthInfo; } /** * Extracts the authenticated user from the MCP request handler extra object. * * @param context - the extra object passed to MCP tool handlers. * @returns the authenticated user. */ export function getActorFromContext(context: McpContext) { return context.authInfo?.extra?.user as User; } /** * Constructs a minimal APIContext from the MCP request context for use with * server commands that require a Koa-style context. * * @param context - the MCP request context. * @returns a partial APIContext suitable for command functions. */ export function buildAPIContext(context: McpContext) { const user = context.authInfo?.extra?.user as User; const token = context.authInfo?.token ?? ""; const ip = context.authInfo?.extra?.ip as string | undefined; const auth = { user, token, type: AuthenticationType.MCP, }; return { state: { auth }, context: { auth, ip }, request: { secure: env.URL.startsWith("https://") }, cookies: { get: () => undefined, set: () => undefined }, } as unknown as APIContext; } /** * Builds a zod schema for an optional string MCP tool input that coerces * empty strings to `undefined`. MCP clients sometimes send `""` for fields * the caller intended to omit. Use this for identifier, query, and similar * fields where `""` is not a meaningful value — keep `z.string().optional()` * for content/text fields where an empty string is a valid input (e.g. * clearing a description). * * @returns a zod schema accepting `string | undefined`, with `""` treated as `undefined`. */ export function optionalString() { return z .string() .optional() .transform((v) => (v === "" ? undefined : v)); } /** The URI of the MCP resource that lists the available named icons. */ export const iconNamesResourceUri = "outline://icons"; /** * Helper function to format successful MCP tool responses. * * Empty arrays return a single `[]` text block so MCP clients that reject * `content: []` can still distinguish zero results from a broken response. * * @param data - the data to include in the response. * @returns a formatted response object for MCP tools. */ export function success(data: T | T[]): CallToolResult { const payload = Array.isArray(data) ? data : [data]; if (payload.length === 0) { return { content: [{ type: "text" as const, text: JSON.stringify([]) }], }; } return { content: payload.map((item) => ({ type: "text" as const, text: JSON.stringify(item), })), }; } /** * Helper function to format error MCP tool responses. * * @param message - the error message or error to include in the response. * @returns a formatted error response object for MCP tools. */ export function error(err: unknown): CallToolResult { const message = errToString(err); return { content: [{ type: "text" as const, text: message }], isError: true, }; } /** * Wraps an MCP tool handler with Datadog tracing. Each invocation creates a * span under the `outline-mcp` service with the tool name as the resource, * and tags it with the acting user and team IDs. * * @param toolName - the name of the MCP tool being traced. * @param handler - the handler function to wrap. * @returns the wrapped handler with tracing enabled. */ /* oxlint-disable @typescript-eslint/no-explicit-any */ export function withTracing any>( toolName: string, handler: F ): F { return traceFunction({ serviceName: "mcp", spanName: "tool", resourceName: toolName, })(function tracedHandler(this: any, ...args: any[]) { const context = args[args.length - 1]; const user = getActorFromContext(context); if (user) { addTags({ "mcp.tool": toolName, "request.userId": user.id, "request.teamId": user.teamId, }); } return handler.apply(this, args); } as F); } /* oxlint-enable @typescript-eslint/no-explicit-any */ /** * Builds a map from document ID to its zero-based index among siblings, * derived from a collection's document structure. * * @param nodes - the top-level navigation nodes from a collection's documentStructure. * @returns a map of document ID to sibling index. */ export function buildSiblingIndexMap( nodes: NavigationNode[] ): Map { const map = new Map(); function walk(children: NavigationNode[]) { children.forEach((node, idx) => { map.set(node.id, idx); walk(node.children); }); } walk(nodes); return map; } /** * Builds a human-readable breadcrumb string showing a document's location. * The path includes only ancestors (collection name plus any parent document * titles) — not the document itself, since callers already have the title. * Documents at the root of a collection get just the collection name. * * @param documentId - the ID of the document to locate. * @param structure - the collection's documentStructure tree, may be null. * @param collectionName - the name of the containing collection. * @returns the breadcrumb string, e.g. "Engineering › Onboarding". */ export function buildBreadcrumb( documentId: string, structure: NavigationNode[] | null | undefined, collectionName: string ): string { const ancestors: string[] = []; if (structure) { const findPath = (nodes: NavigationNode[], chain: string[]): boolean => { for (const node of nodes) { if (node.id === documentId) { ancestors.push(...chain); return true; } if (findPath(node.children, [...chain, node.title])) { return true; } } return false; }; findPath(structure, []); } return [collectionName, ...ancestors].join(" › "); } /** * Builds breadcrumb strings for every document in a collection's structure in * a single traversal. Prefer this over repeated `buildBreadcrumb` calls when * more than one document from the same collection needs a breadcrumb. * * @param structure - the collection's documentStructure tree, may be null. * @param collectionName - the name of the containing collection. * @returns a map from document ID to breadcrumb string. */ function buildBreadcrumbMap( structure: NavigationNode[] | null | undefined, collectionName: string ): Map { const breadcrumbs = new Map(); const walk = (nodes: NavigationNode[], chain: string[]) => { const breadcrumb = [collectionName, ...chain].join(" › "); for (const node of nodes) { breadcrumbs.set(node.id, breadcrumb); if (node.children.length) { walk(node.children, [...chain, node.title]); } } }; if (structure) { walk(structure, []); } return breadcrumbs; } /** * Resolves a breadcrumb string for a document by loading its collection's * cached documentStructure. Returns undefined when the document has no * collection, the collection cannot be loaded, or the user lacks read * access to the collection — the latter prevents leaking collection and * ancestor names to users granted access to a single nested document via * direct membership without wider collection access. * * The document's `collection` association is used when it is already loaded * with the user's memberships, avoiding a second query for it. * * @param document - the document to build a breadcrumb for. * @param user - the user performing the action, used to authorize collection access. * @returns the breadcrumb string, or undefined. */ export async function getDocumentBreadcrumb( document: { id: string; collectionId?: string | null; collection?: Collection | null; }, user: User ): Promise { if (!document.collectionId) { return undefined; } // Both membership associations must be present, as the read policy consults // each of them — an unscoped collection would fail the check incorrectly. const loaded = document.collection?.id === document.collectionId && document.collection.memberships !== undefined && document.collection.groupMemberships !== undefined ? document.collection : null; const collection = loaded ?? (await Collection.findByPk(document.collectionId, { userId: user.id, })); if (!collection || !can(user, "read", collection)) { return undefined; } const structure = await collection.getCachedDocumentStructure(); return buildBreadcrumb(document.id, structure, collection.name); } /** * Resolves breadcrumb strings for a batch of documents in a single pass. * Loads all referenced collections (with the user's memberships) in one * query, filters by collection-level read access, then loads each * collection's cached documentStructure once. * * @param documents - the documents to build breadcrumbs for. * @param user - the user performing the action, used to authorize collection access. * @returns a map from document ID to breadcrumb string. */ export async function getBreadcrumbsForDocuments( documents: { id: string; collectionId?: string | null }[], user: User ): Promise> { const breadcrumbs = new Map(); const collectionIds = [ ...new Set( documents .map((doc) => doc.collectionId) .filter((id): id is string => !!id) ), ]; if (collectionIds.length === 0) { return breadcrumbs; } const collections = await Collection.scope([ "defaultScope", { method: ["withMembership", user.id] }, ]).findAll({ where: { id: collectionIds }, }); // Each collection's structure is resolved once, concurrently, and walked // once — the same collection is typically shared by many of the documents. const readable = collections.filter((collection) => can(user, "read", collection) ); const byCollection = new Map( await Promise.all( readable.map( async (collection) => [ collection.id, { name: collection.name, breadcrumbs: buildBreadcrumbMap( await collection.getCachedDocumentStructure(), collection.name ), }, ] as const ) ) ); for (const doc of documents) { if (!doc.collectionId) { continue; } const collection = byCollection.get(doc.collectionId); if (!collection) { continue; } // A document absent from the structure — a draft, or one added since the // structure was cached — is reported at the collection root. breadcrumbs.set( doc.id, collection.breadcrumbs.get(doc.id) ?? collection.name ); } return breadcrumbs; } /** * Resolves public share URLs for a batch of documents. Only published, * non-revoked shares are considered, so the returned URLs are always publicly * accessible links. * * @param team - the team the documents belong to, used to build absolute URLs. * @param documentIds - a single document ID or an array of document IDs. * @returns a map from document ID to its public share URL. */ export async function getPublicShareUrlsForDocuments( team: Team, documentIds: string | string[] ): Promise> { const shares = await Share.getPublicSharesForDocumentIds( team.id, documentIds ); return toShareUrlMap(team, shares); } /** * Resolves public share URLs for a batch of collections. Only published, * non-revoked shares are considered, so the returned URLs are always publicly * accessible links. * * @param team - the team the collections belong to, used to build absolute URLs. * @param collectionIds - a single collection ID or an array of collection IDs. * @returns a map from collection ID to its public share URL. */ export async function getPublicShareUrlsForCollections( team: Team, collectionIds: string | string[] ): Promise> { const shares = await Share.getPublicSharesForCollectionIds( team.id, collectionIds ); return toShareUrlMap(team, shares); } /** * Resolves the public share URL for a single document. * * @param team - the team the document belongs to, used to build the absolute URL. * @param documentId - the document ID to look up. * @returns the public share URL, or undefined when the document is not publicly shared. */ export async function getPublicShareUrlForDocument( team: Team, documentId: string ): Promise { const map = await getPublicShareUrlsForDocuments(team, documentId); return map.get(documentId); } /** * Resolves the public share URL for a single collection. * * @param team - the team the collection belongs to, used to build the absolute URL. * @param collectionId - the collection ID to look up. * @returns the public share URL, or undefined when the collection is not publicly shared. */ export async function getPublicShareUrlForCollection( team: Team, collectionId: string ): Promise { const map = await getPublicShareUrlsForCollections(team, collectionId); return map.get(collectionId); } /** * Maps public shares to a lookup of resource ID to canonical share URL, keyed * by the share's document or collection ID. The first share wins when more than * one points at the same resource. */ function toShareUrlMap(team: Team, shares: Share[]): Map { const map = new Map(); for (const share of shares) { const key = share.documentId ?? share.collectionId; if (!key || map.has(key)) { continue; } // canonicalUrl reads the team association, which the unscoped query does // not load — supply the already-loaded team. share.team = team; map.set(key, share.canonicalUrl); } return map; } /** * Utility function to construct a URL by joining a team URL with a path segment. * * @param team - the team object containing the base URL. * @param input - an object with attributes keys to be joined with the team URL. * @returns the combined URL string. */ export function pathToUrl(team: Team, input: Record) { const baseUrl = team.url; for (const [key, value] of Object.entries(input)) { if (["url", "path"].includes(key) && typeof value === "string") { // check for existing protocol to avoid double joining if (/^https?:\/\//.test(value)) { input[key] = value; } else { input[key] = new URL(value, baseUrl).href; } } } return input; }