mirror of
https://github.com/outline/outline.git
synced 2026-11-21 21:44:30 +03:00
* perf: Use FOR NO KEY UPDATE where locked rows are only updated Rows that other tables reference by foreign key are now locked with FOR NO KEY UPDATE when the transaction only updates or soft-deletes them, so concurrent inserts that reference the row are not blocked. * test: Collaborative save does not wait for foreign key inserts
406 lines
13 KiB
TypeScript
406 lines
13 KiB
TypeScript
import { v4 as uuidv4 } from "uuid";
|
|
import { z } from "zod";
|
|
import { Transaction } from "sequelize";
|
|
import { sequelize } from "@server/storage/database";
|
|
import type { McpServer } from "@modelcontextprotocol/server";
|
|
import { CommentStatusFilter } from "@shared/types";
|
|
import { commentParser } from "@server/editor";
|
|
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
|
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
|
|
import { Comment, Collection, Document } from "@server/models";
|
|
import { authorize } from "@server/policies";
|
|
import { presentComment } from "@server/presenters";
|
|
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
|
|
import {
|
|
error,
|
|
success,
|
|
buildAPIContext,
|
|
getActorFromContext,
|
|
optionalString,
|
|
withTracing,
|
|
} from "../util";
|
|
import { ValidationError } from "@server/errors";
|
|
|
|
/**
|
|
* Presents a comment with a markdown rendering of its content so that
|
|
* MCP consumers (typically AI agents) can read it without parsing
|
|
* ProseMirror JSON, which is omitted from the response.
|
|
*
|
|
* @param comment - the comment model instance.
|
|
* @returns the presented comment with a markdown `text` field.
|
|
*/
|
|
function presentCommentWithText(comment: Comment) {
|
|
const { data: _data, ...presented } = presentComment(comment, {
|
|
includeAnchorText: true,
|
|
});
|
|
return {
|
|
...presented,
|
|
text: comment.toMarkdown(),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Registers comment-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 tools on.
|
|
* @param scopes - the OAuth scopes granted to the access token.
|
|
*/
|
|
export function commentTools(server: McpServer, scopes: string[]) {
|
|
if (AuthenticationHelper.canAccess("comments.list", scopes)) {
|
|
server.registerTool(
|
|
"list_comments",
|
|
{
|
|
title: "List comments",
|
|
description:
|
|
"Lists comments the user has access to. Requires at least one of documentId or collectionId. Optionally filter by parent comment or resolution status.",
|
|
annotations: {
|
|
destructiveHint: false,
|
|
idempotentHint: true,
|
|
openWorldHint: false,
|
|
readOnlyHint: true,
|
|
},
|
|
inputSchema: z.object({
|
|
documentId: optionalString().describe(
|
|
"The document ID to list comments for."
|
|
),
|
|
collectionId: optionalString().describe(
|
|
"The collection ID to list comments for."
|
|
),
|
|
parentCommentId: optionalString().describe(
|
|
"A parent comment ID to list only the replies in that thread."
|
|
),
|
|
statusFilter: z
|
|
.array(z.enum(CommentStatusFilter))
|
|
.optional()
|
|
.describe(
|
|
"Filter by resolution status: resolved, unresolved, or both."
|
|
),
|
|
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_comments",
|
|
async (
|
|
{
|
|
documentId,
|
|
collectionId,
|
|
parentCommentId,
|
|
statusFilter,
|
|
offset,
|
|
limit,
|
|
},
|
|
extra
|
|
) => {
|
|
try {
|
|
const user = getActorFromContext(extra);
|
|
authorize(user, "listComments", user.team);
|
|
|
|
let document: Document | null = null;
|
|
|
|
// The input may be a urlId, so the id of the loaded model is used.
|
|
let resolvedCollectionId: string | undefined;
|
|
|
|
if (documentId) {
|
|
document = await Document.findByPk(documentId, {
|
|
userId: user.id,
|
|
});
|
|
authorize(user, "read", document);
|
|
} else if (collectionId) {
|
|
const collection = await Collection.findByPk(collectionId, {
|
|
userId: user.id,
|
|
});
|
|
authorize(user, "read", collection);
|
|
resolvedCollectionId = collection.id;
|
|
}
|
|
|
|
const { comments } = await Comment.findAllForUser(user, {
|
|
document,
|
|
collectionId: resolvedCollectionId,
|
|
parentCommentId,
|
|
statusFilter,
|
|
includeDocuments: true,
|
|
offset: offset ?? 0,
|
|
limit: limit ?? 25,
|
|
});
|
|
|
|
return success(
|
|
comments.map((comment) => presentCommentWithText(comment))
|
|
);
|
|
} catch (err) {
|
|
return error(err);
|
|
}
|
|
}
|
|
)
|
|
);
|
|
}
|
|
|
|
if (AuthenticationHelper.canAccess("comments.create", scopes)) {
|
|
server.registerTool(
|
|
"create_comment",
|
|
{
|
|
title: "Create comment",
|
|
description:
|
|
"Creates a new comment on a document. Provide the comment content as markdown text. Optionally nest it as a reply under an existing comment.",
|
|
annotations: {
|
|
destructiveHint: false,
|
|
idempotentHint: false,
|
|
openWorldHint: false,
|
|
readOnlyHint: false,
|
|
},
|
|
inputSchema: z.object({
|
|
documentId: z.string().describe("The document ID to comment on."),
|
|
text: z
|
|
.string()
|
|
.describe("The markdown text content of the comment."),
|
|
parentCommentId: optionalString().describe(
|
|
"The ID of a top-level comment to reply to, replies cannot be nested. Omit for a top-level comment."
|
|
),
|
|
anchorText: optionalString().describe(
|
|
"A plain text substring of the document to anchor this comment to as an inline comment. The first occurrence is used unless anchorPrefix or anchorSuffix is provided, omit for a general document comment."
|
|
),
|
|
anchorPrefix: optionalString().describe(
|
|
"Only provide this if anchorText appears more than once in the document and you need to target a specific occurrence. Plain text that immediately precedes anchorText."
|
|
),
|
|
anchorSuffix: optionalString().describe(
|
|
"Only provide this if anchorText appears more than once in the document and you need to target a specific occurrence. Plain text that immediately follows anchorText."
|
|
),
|
|
}),
|
|
},
|
|
withTracing(
|
|
"create_comment",
|
|
async (
|
|
{
|
|
documentId,
|
|
text,
|
|
parentCommentId,
|
|
anchorText,
|
|
anchorPrefix,
|
|
anchorSuffix,
|
|
},
|
|
context
|
|
) => {
|
|
try {
|
|
const ctx = buildAPIContext(context);
|
|
const { user } = ctx.state.auth;
|
|
|
|
const data = commentParser.parse(text).toJSON();
|
|
const commentId = uuidv4();
|
|
|
|
const comment = await sequelize.transaction(async (transaction) => {
|
|
ctx.state.transaction = transaction;
|
|
ctx.context.transaction = transaction;
|
|
|
|
let document = await Document.findByPk(documentId, {
|
|
userId: user.id,
|
|
transaction,
|
|
});
|
|
authorize(user, "comment", document);
|
|
|
|
if (anchorText) {
|
|
// Acquire the row lock on the document directly when
|
|
// anchoring so a concurrent comment-mark application can't
|
|
// overwrite our state update.
|
|
await Document.unscoped().findOne({
|
|
where: { id: document.id },
|
|
attributes: ["id"],
|
|
transaction,
|
|
lock: Transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
|
|
// Reload under the lock, with the state needed for the mark.
|
|
document = await Document.findByPk(document.id, {
|
|
userId: user.id,
|
|
includeState: true,
|
|
transaction,
|
|
rejectOnEmpty: true,
|
|
});
|
|
|
|
const updated = ProsemirrorHelper.applyCommentMarkByText({
|
|
docState: DocumentHelper.toState(document),
|
|
anchorText,
|
|
commentId,
|
|
userId: user.id,
|
|
prefix: anchorPrefix,
|
|
suffix: anchorSuffix,
|
|
});
|
|
|
|
if (!updated) {
|
|
throw ValidationError(
|
|
"Could not anchor comment to the provided text in the document"
|
|
);
|
|
}
|
|
|
|
await document.updateWithCtx(ctx, {
|
|
state: updated.state,
|
|
content: updated.content,
|
|
});
|
|
}
|
|
|
|
return Comment.createWithCtx(ctx, {
|
|
id: commentId,
|
|
data,
|
|
createdById: user.id,
|
|
documentId: document.id,
|
|
parentCommentId,
|
|
});
|
|
});
|
|
|
|
return success({
|
|
success: true,
|
|
id: comment.id,
|
|
documentId: comment.documentId,
|
|
});
|
|
} catch (err) {
|
|
return error(err);
|
|
}
|
|
}
|
|
)
|
|
);
|
|
}
|
|
|
|
if (AuthenticationHelper.canAccess("comments.update", scopes)) {
|
|
server.registerTool(
|
|
"update_comment",
|
|
{
|
|
title: "Update comment",
|
|
description:
|
|
"Updates an existing comment by its ID. Can update the text content, resolve or unresolve the comment thread, or both. Only top-level comments (not replies) can be resolved or unresolved.",
|
|
annotations: {
|
|
destructiveHint: true,
|
|
idempotentHint: false,
|
|
openWorldHint: false,
|
|
readOnlyHint: false,
|
|
},
|
|
inputSchema: z.object({
|
|
id: z
|
|
.string()
|
|
.describe("The unique identifier of the comment to update."),
|
|
text: z
|
|
.string()
|
|
.optional()
|
|
.describe("The new markdown text content of the comment."),
|
|
status: z
|
|
.enum(["resolved", "unresolved"])
|
|
.optional()
|
|
.describe(
|
|
"Set to 'resolved' to resolve or 'unresolved' to unresolve a top-level comment thread."
|
|
),
|
|
}),
|
|
},
|
|
withTracing("update_comment", async ({ id, text, status }, context) => {
|
|
try {
|
|
const ctx = buildAPIContext(context);
|
|
const { user } = ctx.state.auth;
|
|
|
|
const comment = await Comment.findByPk(id, {
|
|
rejectOnEmpty: true,
|
|
});
|
|
const document = await Document.findByPk(comment.documentId, {
|
|
userId: user.id,
|
|
});
|
|
|
|
authorize(user, "read", comment);
|
|
authorize(user, "read", document);
|
|
|
|
if (text !== undefined) {
|
|
authorize(user, "update", comment);
|
|
authorize(user, "comment", document);
|
|
|
|
const data = commentParser.parse(text).toJSON();
|
|
comment.data = data;
|
|
}
|
|
|
|
if (status === "resolved") {
|
|
authorize(user, "resolve", comment);
|
|
authorize(user, "update", document);
|
|
comment.resolve(user);
|
|
} else if (status === "unresolved") {
|
|
authorize(user, "unresolve", comment);
|
|
authorize(user, "update", document);
|
|
comment.unresolve();
|
|
}
|
|
|
|
// 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 text identical to the
|
|
// current comment.
|
|
if (!comment.changed()) {
|
|
return error(
|
|
"The update resulted in no changes to the comment. Ensure at least one field is provided and differs from the current comment."
|
|
);
|
|
}
|
|
|
|
await comment.saveWithCtx(ctx, status ? { silent: true } : undefined);
|
|
|
|
return success({
|
|
success: true,
|
|
id: comment.id,
|
|
documentId: comment.documentId,
|
|
});
|
|
} catch (err) {
|
|
return error(err);
|
|
}
|
|
})
|
|
);
|
|
}
|
|
|
|
if (AuthenticationHelper.canAccess("comments.delete", scopes)) {
|
|
server.registerTool(
|
|
"delete_comment",
|
|
{
|
|
title: "Delete comment",
|
|
description:
|
|
"Deletes a comment by its ID. The user must be the comment author or a team admin.",
|
|
annotations: {
|
|
destructiveHint: true,
|
|
idempotentHint: false,
|
|
openWorldHint: false,
|
|
readOnlyHint: false,
|
|
},
|
|
inputSchema: z.object({
|
|
id: z
|
|
.string()
|
|
.describe("The unique identifier of the comment to delete."),
|
|
}),
|
|
},
|
|
withTracing("delete_comment", async ({ id }, context) => {
|
|
try {
|
|
const ctx = buildAPIContext(context);
|
|
const { user } = ctx.state.auth;
|
|
|
|
const comment = await Comment.findByPk(id, {
|
|
rejectOnEmpty: true,
|
|
});
|
|
const document = await Document.findByPk(comment.documentId, {
|
|
userId: user.id,
|
|
});
|
|
|
|
authorize(user, "delete", comment);
|
|
authorize(user, "comment", document);
|
|
|
|
await comment.destroyWithCtx(ctx);
|
|
|
|
return success({ success: true });
|
|
} catch (err) {
|
|
return error(err);
|
|
}
|
|
})
|
|
);
|
|
}
|
|
}
|