mirror of
https://github.com/outline/outline.git
synced 2026-11-27 16:08:58 +03:00
* feat: Filter DSL for collections.list Adds the structured `filters` expression language to collections.list, matching documents.list and documents.search. Supported fields are name, createdAt, updatedAt, archivedAt, createdById and permission, each validated against its column type at the input layer. Deprecates the ad-hoc `query` and `statusFilter` params, which now translate into filter leaves so that one code path serves both shapes, and returns a 400 when a caller combines them with `filters`. Note that `query` matching is no longer accent-insensitive, as the unaccent comparison is replaced by the shared iLike conversion. * fix: Make filter expressions assignable to a JSON request body Filters are sent as a JSON body, but `FilterCondition` and `FilterGroup` were interfaces, which TypeScript does not give an implicit index signature, and `FilterValue` admitted a `Date` that JSON cannot carry. Both stores worked around this by asserting the request body to JSONObject, which suppressed checking of every other field as well. Declare the two shapes as type aliases and drop `Date` from the value union so a filter type-checks against the request body directly, and remove the assertions from the collection and document stores. * feat: Restrict filter fields to a set of accepted values Add an optional `values` set to a filter field definition, checked against scalar and array values at the input layer so that an unsupported value returns a 400 rather than an empty result or, for a field backed by a Postgres enum, a database error. A field with a fixed value set is matched exactly, so pattern operators are rejected for it in the same way as for non-text columns. Apply it to `permission` on collections.list. * refactor: Build the list_collections name filter with the filter DSL The MCP tool carried its own copy of the unaccent name comparison that collections.list used before it moved to the DSL. Build the clause with buildWhere instead, so both paths match names the same way, and drop the replacements plumbing it needed.
369 lines
12 KiB
TypeScript
369 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 {
|
|
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 function presentCollection(collection: Collection) {
|
|
return presentCollectionBase(undefined, collection, {
|
|
includeData: false,
|
|
includeText: true,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 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."
|
|
),
|
|
},
|
|
},
|
|
withTracing("delete_collection", async ({ id, archive }, 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,
|
|
});
|
|
|
|
if (archive) {
|
|
authorize(user, "archive", collection);
|
|
await collection.archiveWithCtx(ctx);
|
|
} else {
|
|
authorize(user, "delete", collection);
|
|
await collection.destroyWithCtx(ctx);
|
|
}
|
|
});
|
|
|
|
return success({ success: true });
|
|
} catch (message) {
|
|
return error(message);
|
|
}
|
|
})
|
|
);
|
|
}
|
|
}
|