Files
outline/server/mcp/tools/collections.ts
T
Tom Moor 754672e9dc Centralize document access rules for list queries (#14783)
* wip

* Route document list queries through findAllWithCtx

Add findAllWithCtx and countWithCtx on Document and Template, unsafe* methods
for system reads, and a lint rule that bans direct list queries. Remove the
cached membership list, accessibleSql and findByIds in favour of one gate.

* Remove test

* Include drafts when loading starred documents

* Scope the access gate to the user's team, move whereToSql to QueryHelper

* Move collection access to Collection.findAllWithCtx

Collection.accessibleIds keeps the cached id list inside the collection gate, and user.collectionIds() is a shortcut to it. List queries use findAllWithCtx and countWithCtx, system reads use the shared unsafe methods, and the admin listing in collections.list is explicit.

* Check permanentDelete for each document in empty_trash
2026-11-27 15:30:43 -05:00

447 lines
15 KiB
TypeScript

import { difference } from "es-toolkit";
import { z } from "zod";
import { Sequelize, Op, type WhereOptions } from "sequelize";
import type { McpServer } from "@modelcontextprotocol/server";
import { Collection, Team } from "@server/models";
import { buildWhere } from "@server/models/helpers/Filters";
import { sequelize } from "@server/storage/database";
import { authorize, can } from "@server/policies";
import { presentCollection as presentCollectionBase } from "@server/presenters";
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
import { UrlHelper } from "@shared/utils/UrlHelper";
import {
CollectionValidation,
DeprecationValidation,
} from "@shared/validations";
import {
success,
error,
getActorFromContext,
buildAPIContext,
getPublicShareUrlsForCollections,
optionalString,
pathToUrl,
withTracing,
} from "../util";
/**
* Presents a collection for a tool response. Includes a markdown description
* instead of ProseMirror JSON so that MCP consumers (typically AI agents) can
* read it directly.
*
* @param collection - the collection to present.
* @returns the presented collection object.
*/
export async function presentCollection(collection: Collection) {
return {
...(await presentCollectionBase(undefined, collection, {
includeData: false,
includeText: true,
})),
isPersonal: collection.isPersonal,
};
}
/**
* Registers collection-related MCP tools on the given server, filtered by
* the OAuth scopes granted to the current token.
*
* @param server - the MCP server instance to register on.
* @param scopes - the OAuth scopes granted to the access token.
*/
export function collectionTools(server: McpServer, scopes: string[]) {
if (AuthenticationHelper.canAccess("collections.list", scopes)) {
server.registerTool(
"list_collections",
{
title: "List collections",
description:
"Lists all collections the authenticated user has access to. Returns a summary of each collection.",
annotations: {
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
readOnlyHint: true,
},
inputSchema: z.object({
query: optionalString().describe(
"An optional search query to filter collections by name."
),
offset: z.coerce
.number()
.int()
.min(0)
.optional()
.describe("The pagination offset. Defaults to 0."),
limit: z.coerce
.number()
.int()
.min(1)
.max(100)
.optional()
.describe(
"The maximum number of results to return. Defaults to 25, max 100."
),
}),
},
withTracing(
"list_collections",
async ({ query, offset, limit }, extra) => {
try {
const user = getActorFromContext(extra);
const and: WhereOptions<Collection>[] = [
{ deletedAt: { [Op.eq]: null } },
{ archivedAt: { [Op.eq]: null } },
];
if (query) {
and.push(
buildWhere<Collection>({
field: "name",
operator: "contains",
value: query,
})
);
}
const where: WhereOptions<Collection> = {
[Op.and]: and,
};
const [collections, exactMatchCandidate] = await Promise.all([
Collection.findAllWithCtx(buildAPIContext(extra), {
where,
order: [
Sequelize.literal('"collection"."index" collate "C"'),
["updatedAt", "DESC"],
],
offset: offset ?? 0,
limit: limit ?? 25,
}),
// If the query looks like a collection ID or urlId, try direct
// lookup so exact matches appear at the top of results.
query && UrlHelper.SLUG_URL_REGEX.test(query)
? Collection.findByPk(query, { userId: user.id })
: null,
]);
const exactMatch =
exactMatchCandidate &&
can(user, "readDocument", exactMatchCandidate)
? exactMatchCandidate
: null;
const matchedCollections = [
...(exactMatch ? [exactMatch] : []),
...collections.filter((c) => c.id !== exactMatch?.id),
];
const [shareUrls, presented] = await Promise.all([
getPublicShareUrlsForCollections(
user.team,
matchedCollections.map((c) => c.id)
),
Promise.all(
matchedCollections.map(async (collection) => ({
collection,
presented: pathToUrl(
user.team,
await presentCollection(collection)
),
}))
),
]);
const results = presented.map(({ collection, presented }) => {
const shareUrl = shareUrls.get(collection.id);
return {
...presented,
...(shareUrl !== undefined && { shareUrl }),
};
});
return success(results);
} catch (message) {
return error(message);
}
}
)
);
}
if (AuthenticationHelper.canAccess("collections.create", scopes)) {
server.registerTool(
"create_collection",
{
title: "Create collection",
description:
"Creates a new collection. Collections are used to organize documents.",
annotations: {
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
readOnlyHint: false,
},
inputSchema: z.object({
name: z.string().describe("The name of the collection."),
description: z
.string()
.optional()
.describe("A markdown description for the collection."),
icon: optionalString().describe(
"An icon for the collection. May be an emoji or a named icon; read the outline://icons resource for the list of available icon names."
),
color: optionalString().describe(
"The hex color for the collection icon, e.g. #FF0000."
),
ownerIds: z
.array(z.uuid())
.max(CollectionValidation.maxOwners)
.optional()
.describe(
"The IDs of users responsible for the collection, they also own every document in it. Owners must be members or admins of the workspace, use list_users to find user IDs."
),
}),
},
withTracing("create_collection", async (input, context) => {
try {
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
const team = await Team.findByPk(user.teamId, {
rejectOnEmpty: true,
});
authorize(user, "createCollection", team);
const collection = await sequelize.transaction(
async (transaction) => {
ctx.transaction = transaction;
const created = Collection.build({
name: input.name,
description: input.description,
icon: input.icon,
color: input.color,
teamId: user.teamId,
createdById: user.id,
permission: null,
});
await created.saveWithCtx(ctx);
if (input.ownerIds?.length) {
const reloaded = await Collection.findByPk(created.id, {
userId: user.id,
transaction,
rejectOnEmpty: true,
});
authorize(user, "manageOwners", reloaded);
await reloaded.setOwnerIds(ctx, input.ownerIds);
await reloaded.saveWithCtx(ctx);
await reloaded.grantOwnerAccess(ctx, reloaded.ownerIds);
}
return created;
}
);
return success({
success: true,
...pathToUrl(user.team, {
id: collection.id,
name: collection.name,
url: collection.path,
}),
});
} catch (message) {
return error(message);
}
})
);
}
if (AuthenticationHelper.canAccess("collections.update", scopes)) {
server.registerTool(
"update_collection",
{
title: "Update collection",
description:
"Updates an existing collection by its ID. Only the fields provided will be updated.",
annotations: {
destructiveHint: true,
idempotentHint: false,
openWorldHint: false,
readOnlyHint: false,
},
inputSchema: z.object({
id: z
.string()
.describe("The unique identifier of the collection to update."),
name: optionalString().describe("The new name for the collection."),
description: z
.string()
.optional()
.describe("The new markdown description for the collection."),
icon: z
.string()
.nullable()
.optional()
.describe(
"An icon for the collection. Set to null to remove. May be an emoji or a named icon; read the outline://icons resource for the list of available icon names."
),
color: z
.string()
.nullable()
.optional()
.describe(
"The hex color for the collection icon. Set to null to remove."
),
ownerIds: z
.array(z.uuid())
.max(CollectionValidation.maxOwners)
.optional()
.describe(
"The complete list of IDs of users responsible for the collection, replacing any existing owners. Pass an empty array to remove all owners. Owners must be members or admins of the workspace, use list_users to find user IDs."
),
}),
},
withTracing("update_collection", async (input, context) => {
try {
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
return await sequelize.transaction(async (transaction) => {
ctx.transaction = transaction;
const collection = await Collection.findByPk(input.id, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
authorize(user, "update", collection);
if (input.ownerIds) {
authorize(user, "manageOwners", collection);
}
const previousOwnerIds = collection.ownerIds ?? [];
if (input.ownerIds) {
await collection.setOwnerIds(ctx, input.ownerIds);
}
if (input.name !== undefined) {
collection.name = input.name.trim();
}
if (input.description !== undefined) {
collection.description = input.description;
}
if (input.icon !== undefined) {
collection.icon = input.icon;
}
if (input.color !== undefined) {
collection.color = input.color;
}
// A write that changes nothing must fail loud rather than return a
// success the caller would read as a completed write — the request
// either carried no recognized fields or values identical to the
// current collection.
if (!collection.changed()) {
return error(
"The update resulted in no changes to the collection. Ensure at least one field is provided and differs from the current collection."
);
}
await collection.saveWithCtx(ctx);
await collection.grantOwnerAccess(
ctx,
difference(collection.ownerIds ?? [], previousOwnerIds)
);
return success({
success: true,
...pathToUrl(user.team, {
id: collection.id,
name: collection.name,
url: collection.path,
}),
});
});
} catch (message) {
return error(message);
}
})
);
}
if (AuthenticationHelper.canAccess("collections.delete", scopes)) {
server.registerTool(
"delete_collection",
{
title: "Delete collection",
description:
"Deletes a collection by its ID. Non-archived documents within the collection will also be deleted. Set archive to true to archive the collection instead of deleting it.",
annotations: {
destructiveHint: true,
idempotentHint: false,
openWorldHint: false,
readOnlyHint: false,
},
inputSchema: z.object({
id: z
.string()
.describe("The unique identifier of the collection to delete."),
archive: z
.boolean()
.optional()
.describe(
"Set to true to archive the collection instead of deleting it. All documents within the collection will also be archived."
),
reason: z
.string()
.trim()
.max(DeprecationValidation.maxReasonLength)
.nullish()
.describe(
"A plain text reason for archiving or deleting the collection. Omit to keep the existing reason, or use null or an empty string to clear it."
),
}),
},
withTracing(
"delete_collection",
async ({ id, archive, reason }, context) => {
try {
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
await sequelize.transaction(async (transaction) => {
ctx.transaction = transaction;
ctx.transaction = transaction;
const collection = await Collection.findByPk(id, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
authorize(user, archive ? "archive" : "delete", collection);
if (reason !== undefined) {
collection.deprecatedReason = reason || null;
}
if (archive) {
await collection.archiveWithCtx(ctx);
} else {
await collection.destroyWithCtx(ctx);
}
});
return success({ success: true });
} catch (message) {
return error(message);
}
}
)
);
}
}