Files
outline/server/mcp/tools/notifications.ts
T
Tom Moor e23a9566fb feat: Add notification inbox tools to MCP (#14905)
* feat: Add notification inbox tools to MCP

* fix: Mark update_notifications as destructive
2026-12-05 13:29:37 -05:00

233 lines
8.0 KiB
TypeScript

import { z } from "zod";
import { Op, Transaction } from "sequelize";
import type { WhereOptions } from "sequelize";
import type { McpServer } from "@modelcontextprotocol/server";
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
import { NotFoundError } from "@server/errors";
import { Notification } from "@server/models";
import {
buildWhere,
combineFilters,
hasFieldInFilter,
NotificationsFilterListSchema,
} from "@server/models/helpers/Filters";
import type { Team } from "@server/models";
import { authorize } from "@server/policies";
import { sequelize } from "@server/storage/database";
import {
error,
success,
buildAPIContext,
getActorFromContext,
pathToUrl,
withTracing,
} from "../util";
/**
* Registers notification MCP tools on the given server, filtered by the
* OAuth scopes granted to the current token. Together they act as an inbox
* of the mentions, replies and other events that need the user's attention.
*
* @param server - the MCP server instance to register on.
* @param scopes - the OAuth scopes granted to the access token.
*/
export function notificationTools(server: McpServer, scopes: string[]) {
if (AuthenticationHelper.canAccess("notifications.list", scopes)) {
server.registerTool(
"list_notifications",
{
title: "List notifications",
description:
"Lists the current user's notifications, newest first, such as mentions, comment replies, document updates and access requests. Use this as an inbox of work that needs attention, then mark handled notifications with update_notifications.",
annotations: {
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
readOnlyHint: true,
},
inputSchema: z.object({
filters: NotificationsFilterListSchema.optional().describe(
'Filter expressions, combined with AND, in the same shape as the REST API. A condition is {"field", "operator", "value"}, and a group is {"operator": "AND" | "OR", "filters": [...]}. Fields: event, actorId, documentId, collectionId, createdAt, viewedAt, archivedAt. Unread notifications have viewedAt isNull, for example [{"field": "viewedAt", "operator": "isNull"}]. Date fields also accept an ISO 8601 duration such as "-P1D" with gt, gte, lt or lte. Archived notifications are excluded unless a filter references archivedAt.'
),
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_notifications",
async ({ filters, offset, limit }, extra) => {
try {
const user = getActorFromContext(extra);
const filter = combineFilters(filters);
const where: WhereOptions<Notification> & {
[Op.and]: WhereOptions<Notification>[];
} = {
teamId: user.teamId,
userId: user.id,
[Op.and]: [],
};
if (!filter || !hasFieldInFilter(filter, "archivedAt")) {
where[Op.and].push({ archivedAt: { [Op.is]: null } });
}
if (filter) {
where[Op.and].push(buildWhere<Notification>(filter));
}
const notifications = await Notification.findAll({
where,
order: [["createdAt", "DESC"]],
offset: offset ?? 0,
limit: limit ?? 25,
});
return success(
notifications.map((notification) =>
presentNotificationForAgent(user.team, notification)
)
);
} catch (err) {
return error(err);
}
}
)
);
}
if (AuthenticationHelper.canAccess("notifications.update", scopes)) {
server.registerTool(
"update_notifications",
{
title: "Update notifications",
description:
"Marks one or more of the current user's notifications as read or unread, and archived or not archived. Archive a notification once the work it asks for is done.",
annotations: {
destructiveHint: true,
idempotentHint: true,
openWorldHint: false,
readOnlyHint: false,
},
inputSchema: z.object({
ids: z
.array(z.uuid())
.min(1)
.max(100)
.describe("The IDs of the notifications to update."),
read: z
.boolean()
.optional()
.describe("Set to true to mark as read, or false to mark unread."),
archived: z
.boolean()
.optional()
.describe("Set to true to archive, or false to unarchive."),
}),
},
withTracing(
"update_notifications",
async ({ ids, read, archived }, context) => {
try {
if (read === undefined && archived === undefined) {
return error("Provide at least one of read or archived.");
}
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
const uniqueIds = [...new Set(ids)];
await sequelize.transaction(async (transaction) => {
ctx.transaction = transaction;
const notifications = await Notification.findAll({
where: { id: uniqueIds },
lock: {
level: Transaction.LOCK.NO_KEY_UPDATE,
of: Notification,
},
transaction,
});
if (notifications.length !== uniqueIds.length) {
throw NotFoundError("One or more notifications were not found");
}
for (const notification of notifications) {
authorize(user, "update", notification);
// Keep the original timestamps when the state does not change.
if (read !== undefined) {
notification.viewedAt = read
? (notification.viewedAt ?? new Date())
: null;
}
if (archived !== undefined) {
notification.archivedAt = archived
? (notification.archivedAt ?? new Date())
: null;
}
if (notification.changed()) {
await notification.saveWithCtx(ctx);
}
}
});
return success({ success: true, ids: uniqueIds });
} catch (err) {
return error(err);
}
}
)
);
}
}
/**
* Presents a notification with only the fields an agent needs to act on it,
* including the comment as markdown and absolute document URLs.
*
* @param team - the team, used to build absolute URLs.
* @param notification - the notification with its default includes loaded.
* @returns the presented notification.
*/
function presentNotificationForAgent(team: Team, notification: Notification) {
const { actor, document, comment } = notification;
return {
id: notification.id,
event: notification.event,
createdAt: notification.createdAt,
read: !!notification.viewedAt,
archived: !!notification.archivedAt,
actor: actor ? { id: actor.id, name: actor.name } : undefined,
document: document
? pathToUrl(team, {
id: document.id,
title: document.title,
url: document.path,
})
: undefined,
comment: comment
? {
id: comment.id,
parentCommentId: comment.parentCommentId,
text: comment.toMarkdown(),
}
: undefined,
collectionId: notification.collectionId,
accessRequestId: notification.accessRequestId,
accessRequestStatus: notification.accessRequest?.status,
};
}