Files
outline/server/mcp/tools/collections.ts
T
Tom Moor f8496ea2f7 feat: Personal collections (#14062)
* feat: Personal collections backend

Adds an owner to collections. A personal collection is private, one per user
per team, created lazily through collections.personal, and only its owner can
see or manage it. Admin bypasses in policies, lists, exports, events, webhooks
and file operations exclude the personal collections of other users. Turning
off the PersonalDocs preference makes the collection read-only.

* test: Access matrix for personal collections

Checks that collection and document endpoints, list and search results, MCP
tools, collaboration and websocket rooms agree with the read policy for the
owner, collaborators, members, admins, guests and other teams.

* feat: Personal collection in the sidebar

Adds a Personal sidebar section that renders the personal collection with the
collection document tree, creates the collection on the first new document,
and keeps it out of the Collections section. Adds the workspace setting, the
personal sidebar context, and hides collection sharing and membership UI for
personal collections.

* fix: Drag and drop in shared with me trees

Anchors the reorder drop cursor inside the row, and prefetches documents on
hover so that nested rows that were never opened can be dragged.

* feat: Personal collection owner for collaborators, no collection page

Presents the owner of the personal collection on documents, so that
collaborators see the owner in the share popover. Root rows in the Personal
section show the default document icon. A personal collection has no page:
the scene shows not found, and the breadcrumb, command bar and delete redirect
no longer link to it.

* fix: Personal sidebar indent and breadcrumb items without a link

Children of rows at depth 0 skip a level so that they start beyond the row
icon. Breadcrumb items without a destination, such as the personal and deleted
collection, are shown as plain text.

* test: Reduce personal collection tests to list paths

Endpoints that authorize a single model are already covered by the policy
tests. Keeps the lists and searches, which filter in queries, and the
presenter.

* test: Move personal collection list tests into collections tests

* feat: Create documents in the personal collection by alias

documents.create, documents.import and the MCP create_document tool accept
the collectionId "personal", which refers to the personal collection of the
user and creates it when it does not exist yet.

* refactor: Remove collections.personal route

The sidebar creates its first personal document with the personal
collectionId alias, so documents.create is the only path that creates the
personal collection.

* feat: Personal collection name, starring, templates and default

Personal collections cannot be starred, renamed or hold templates, and the
PersonalDocs preference is on by default. The app shows collections through a
displayName getter, which is the translated "Personal" for a personal
collection.

* fix: Use the same policy for starring and unstarring collections

* fix: No pins or viewer insights for personal documents

* revert: Show personal collection events in the audit log

Admins with audit access should see events in personal collections, even when
they cannot open the documents.

* fix: Load collection owner in share scopes

* fix: Keep personal collections out of workspace exports and webhooks

Workspace exports skip all personal collections, while an explicit export of
a personal collection stays available to its owner. Events in personal
collections, including attachments and documents moved after queueing, are
never delivered to workspace webhooks. Personal collections cannot be
renamed or made public through any path, cannot hold pins, and are not
offered as mentions.

* Change icon to avatar

* fix: Personal documents cannot be unpublished

* feat: Personal collection context for MCP

Collections are presented with an isPersonal flag, the server instructions
explain the personal collection, and move_document and update_document accept
the personal collectionId alias.

* fix: Keep moved personal exports private and remove pins on move

Document exports record the owner of the personal collection they came from,
so they stay private after the document moves. Moving documents into a
personal collection removes their pins, including pins to home.

* fix: Only create the personal collection in MCP when it is used
2026-10-13 07:53:06 -04:00

388 lines
12 KiB
TypeScript

import { z } from "zod";
import { Sequelize, Op, type WhereOptions } from "sequelize";
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { Collection, Team } from "@server/models";
import { buildWhere } from "@server/models/helpers/Filters";
import { sequelize } from "@server/storage/database";
import { authorize } from "@server/policies";
import { presentCollection as presentCollectionBase } from "@server/presenters";
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
import { UrlHelper } from "@shared/utils/UrlHelper";
import { 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: {
idempotentHint: true,
readOnlyHint: true,
},
inputSchema: {
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 collectionIds = await user.collectionIds();
const and: WhereOptions<Collection>[] = [
{ deletedAt: { [Op.eq]: null } },
{ archivedAt: { [Op.eq]: null } },
{ id: collectionIds },
];
if (query) {
and.push(
buildWhere<Collection>({
field: "name",
operator: "contains",
value: query,
})
);
}
const where: WhereOptions<Collection> = {
teamId: user.teamId,
[Op.and]: and,
};
const collections = await Collection.scope({
method: ["withMembership", user.id],
}).findAll({
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 first so exact matches appear at the top of results.
let exactMatch: Collection | null = null;
if (query && UrlHelper.SLUG_URL_REGEX.test(query)) {
exactMatch = await Collection.findByPk(query, {
userId: user.id,
});
if (exactMatch && !collectionIds.includes(exactMatch.id)) {
exactMatch = 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: {
idempotentHint: false,
readOnlyHint: false,
},
inputSchema: {
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."
),
},
},
withTracing("create_collection", async (input, context) => {
try {
const ctx = buildAPIContext(context);
const { user } = ctx.state.auth;
const team = await Team.findByPk(user.teamId, {
rejectOnEmpty: true,
});
authorize(user, "createCollection", team);
const collection = Collection.build({
name: input.name,
description: input.description,
icon: input.icon,
color: input.color,
teamId: user.teamId,
createdById: user.id,
permission: null,
});
await collection.saveWithCtx(ctx);
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: {
idempotentHint: false,
readOnlyHint: false,
},
inputSchema: {
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."
),
},
},
withTracing("update_collection", async (input, context) => {
try {
const ctx = buildAPIContext(context);
const { user } = ctx.state.auth;
const collection = await Collection.findByPk(input.id, {
userId: user.id,
rejectOnEmpty: true,
});
authorize(user, "update", collection);
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);
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: {
idempotentHint: false,
readOnlyHint: false,
},
inputSchema: {
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.state.auth;
await sequelize.transaction(async (transaction) => {
ctx.state.transaction = transaction;
ctx.context.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);
}
}
)
);
}
}