Files
outline/server/mcp/tools/documents.ts
T
Tom MoorandClaude 767758a1a8 feat: Document and collection owners (#14437)
* feat: Add document owners

Documents can now have owners, stored as an array of user IDs. Owners
must be active members or admins, and changing them requires the
existing manage users permission on the document, gated behind a new
DocumentOwners plan entitlement that is included in every plan.

- ownerIds accepted by documents.create and documents.update and
  returned by the document presenter
- ownerIds filter field (eq/in) for documents.list and documents.search
- ownerIds on the MCP create_document and update_document tools, and an
  ownerId filter on list_documents
- Owners section in the document Insights dialog to add and remove owners
- Owner filter on the search page
- In-app and email notification when a user is made an owner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFdSZ39ZGPf31jyGcYz

* feat: Give document owners responsibility for their documents

- Access requests are routed to owners that can manage the document
  before falling back to document, collection and workspace admins
- Owners are subscribed to a document when they are added, respecting
  a previous unsubscribe
- Owners that can edit a document can also manage its access, owners
  and archive it; ownership never grants access on its own
- Owners are shown in the document byline, list items and search
  results, and document hover previews

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFdSZ39ZGPf31jyGcYz

* feat: Manage document owners from the share panel

- Owner is a role in the share panel permission menu and invite picker for
  individual users, adding an owner gives them the manage permission
- Lowering an owner's permission or removing their access removes the
  ownership
- Owners are sorted to the top of the member list
- Owners added through the API or MCP are given the manage permission
- Owners do not also receive the "added to document" notification
- Only added owners are validated, so suspended owners can still be removed
- Deleted users are removed from document owners
- Removes the owners section from Insights

* fix: Address review feedback on document owners

- Authorize owner changes before assigning owners on create
- Lock the document when adding an owner so concurrent invitations are kept
- Enforce the owner limit on every path
- Run MCP document updates in a transaction
- Broadcast owner removals to connected clients

* feat: Add collection owners

- Collections can have owners, who also own every document in the
  collection, shown first in document bylines
- Owner is a role in the collection share panel and invite picker for
  individual users, adding an owner gives them the manage permission
- Lowering an owner's permission or removing their access removes the
  ownership
- ownerIds on collections.create, collections.update and the MCP
  collection tools
- The document owner filter includes documents in owned collections
- Access requests go to document and collection owners together
- Collection owners are subscribed to the collection and notified when
  they are added
- Deleted users are removed from collection owners
- Renames the personal collection policy helper to
  isPersonalCollectionOwner

* feat: Show profile cards on owner names, hide inherited owners in collection lists

* fix: Allow adding yourself as a collection owner, include collection owners in MCP exact match

* fix: Correct singular owner translations

* feat: Allow users to make themselves a document owner

- The share panel suggests the current user when they can manage owners,
  and only offers the Owner permission for them
- documents.add_user accepts the actor's own ID when changing ownership,
  without changing their own access
- An owner's own row offers "Remove as owner", which keeps their access
- Hides the duplicate "You have full access" row when the current user is
  listed as a member

* fix: Restore singular owner translations

* fix: Limit owners to 5, use no key update locks when adding owners

* refactor: Move owner logic into Document and Collection model methods

- addOwner, removeOwner, grantOwnerAccess and setOwnerIds on both models,
  locking the row so concurrent owner changes are kept
- Owner events are created by an update hook from the change in ownerIds
- The manageOwners check runs at the route level when ownerIds is sent
- Removes the documentOwners and collectionOwners command modules
- Removes duplicate owner tests

* fix: Owner selection and membership edge cases

- Remove document owners from the legacy plan
- Selecting yourself in the share picker only suggests other users that can
  be owners, and you are not suggested next to groups or guests
- Users that make themselves an owner through the API get the manage
  permission, so they are listed in the share panel

* perf: Scope the collection owner filter subquery to the team

* chore: Drop redundant teamId UUID check

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-25 19:21:26 -05:00

1024 lines
39 KiB
TypeScript

import { z } from "zod";
import { PersonalCollectionId } from "@shared/constants";
import type { McpServer, CallToolResult } from "@modelcontextprotocol/server";
import documentCreator, {
authorizeDocumentCreate,
authorizeDocumentPublish,
} from "@server/commands/documentCreator";
import documentMover from "@server/commands/documentMover";
import { resolvePersonalCollectionId } from "@server/commands/personalCollectionLoader";
import documentRestorer from "@server/commands/documentRestorer";
import documentUpdater from "@server/commands/documentUpdater";
import { Collection, Document, SearchQuery, Template } from "@server/models";
import { SearchQuerySource } from "@server/models/SearchQuery";
import { combineFilters } from "@server/models/helpers/Filters";
import DocumentImportTask from "@server/queues/tasks/DocumentImportTask";
import { sequelize } from "@server/storage/database";
import { authorize, can } from "@server/policies";
import {
presentDocument as presentDocumentBase,
presentNavigationNode,
} from "@server/presenters";
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
import { UrlHelper } from "@shared/utils/UrlHelper";
import { DeprecationValidation, DocumentValidation } from "@shared/validations";
import {
error,
success,
buildAPIContext,
buildSiblingIndexMap,
getActorFromContext,
getBreadcrumbsForDocuments,
getDocumentBreadcrumb,
getPublicShareUrlForDocument,
getPublicShareUrlsForDocuments,
optionalString,
pathToUrl,
withTracing,
} from "../util";
import { ValidationError } from "@server/errors";
import { TextEditMode } from "@shared/types";
import type { Filter } from "@shared/helpers/FilterHelper";
import SearchProviderManager from "@server/utils/SearchProviderManager";
/**
* Presents a document for a tool response. Adds MCP-specific fields
* on top of the standard document presenter.
*
* @param document - the document to present.
* @param options - optional presenter options
* @returns the presented document object.
*/
export function presentDocument(
document: Document,
options: {
includeData?: boolean;
includeText?: boolean;
includeUpdatedAt?: boolean;
includeCommentCount?: boolean;
} = {}
) {
return presentDocumentBase(undefined, document, options);
}
/**
* Registers document-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 documentTools(server: McpServer, scopes: string[]) {
if (AuthenticationHelper.canAccess("documents.list", scopes)) {
server.registerTool(
"list_documents",
{
title: "Search documents",
description:
"Searches documents the user has access to. Performs full-text search across document content when a query is provided, or lists recent documents when no query is given. Archived documents are excluded unless includeArchived is set. Optionally filter by collection. To retrieve the full contents or hierarchy of a specific collection, use list_collection_documents instead.",
annotations: {
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
readOnlyHint: true,
},
inputSchema: z.object({
query: optionalString().describe(
"A search query to find documents by content or title. When omitted, returns recent documents."
),
collectionId: optionalString().describe(
"A collection ID to filter documents by."
),
ownerId: optionalString().describe(
"A user ID to filter documents by, only documents owned by this user are returned."
),
includeArchived: z
.boolean()
.optional()
.describe(
"Whether to include archived documents in the results. Defaults to false, as archived documents are usually outdated."
),
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_documents",
async ({ query, includeArchived, offset, limit, ...input }, extra) => {
try {
const user = getActorFromContext(extra);
const effectiveOffset = offset ?? 0;
const effectiveLimit = limit ?? 25;
let indexMap: Map<string, number> | undefined;
// The input may be a urlId, so the id of the loaded model is used.
let collectionId: string | undefined;
if (input.collectionId) {
const collection = await Collection.findByPk(input.collectionId, {
userId: user.id,
includeDocumentStructure: true,
});
authorize(user, "readDocument", collection);
collectionId = collection.id;
if (collection.documentStructure) {
indexMap = buildSiblingIndexMap(collection.documentStructure);
}
}
if (query) {
const searchProvider = SearchProviderManager.getProvider();
const searchStartedAt = Date.now();
const searchFilters: Filter[] = [];
if (!includeArchived) {
searchFilters.push({
field: "archivedAt",
operator: "isNull",
});
}
if (collectionId) {
searchFilters.push({
field: "collectionId",
operator: "eq",
value: collectionId,
});
}
if (input.ownerId) {
searchFilters.push({
field: "ownerIds",
operator: "eq",
value: input.ownerId,
});
}
const [{ results, total }, exactMatchCandidate] =
await Promise.all([
searchProvider.searchForUser(user, {
query,
filter: combineFilters(searchFilters),
offset: effectiveOffset,
limit: effectiveLimit,
}),
// If the query looks like a document ID or urlId, try direct
// lookup so exact matches appear at the top of results.
UrlHelper.SLUG_URL_REGEX.test(query)
? Document.findByPk(query, { userId: user.id })
: null,
]);
const duration = Date.now() - searchStartedAt;
const exactMatch =
exactMatchCandidate &&
can(user, "read", exactMatchCandidate) &&
(!collectionId ||
exactMatchCandidate.collectionId === collectionId) &&
(!input.ownerId ||
exactMatchCandidate.ownerIds?.includes(input.ownerId) ||
exactMatchCandidate.collection?.ownerIds?.includes(
input.ownerId
))
? exactMatchCandidate
: null;
const filteredResults = results.filter(
(result) => result.document.id !== exactMatch?.id
);
const matchedDocuments = [
...(exactMatch ? [exactMatch] : []),
...filteredResults.map((r) => r.document),
];
const [breadcrumbs, shareUrls] = await Promise.all([
getBreadcrumbsForDocuments(matchedDocuments, user),
getPublicShareUrlsForDocuments(
user.team,
matchedDocuments.map((doc) => doc.id)
),
// Only record the first page of results to avoid duplicate
// records as the client pages through results.
effectiveOffset === 0
? SearchQuery.record({
userId: user.id,
teamId: user.teamId,
source: SearchQuerySource.MCP,
query,
results: total,
duration,
})
: undefined,
]);
const presented = await Promise.all(
filteredResults.map(async (result) => {
const doc = pathToUrl(
user.team,
await presentDocument(result.document, {
includeData: false,
includeText: false,
})
);
const breadcrumb = breadcrumbs.get(result.document.id);
const shareUrl = shareUrls.get(result.document.id);
const siblingIndex = indexMap?.get(result.document.id);
return {
document: doc,
...(breadcrumb !== undefined && { breadcrumb }),
...(shareUrl !== undefined && { shareUrl }),
context: result.context,
...(siblingIndex !== undefined && {
index: siblingIndex,
}),
};
})
);
if (exactMatch) {
const doc = pathToUrl(
user.team,
await presentDocument(exactMatch, {
includeData: false,
includeText: false,
})
);
const breadcrumb = breadcrumbs.get(exactMatch.id);
const shareUrl = shareUrls.get(exactMatch.id);
const siblingIndex = indexMap?.get(exactMatch.id);
presented.unshift({
document: doc,
...(breadcrumb !== undefined && { breadcrumb }),
...(shareUrl !== undefined && { shareUrl }),
context: undefined,
...(siblingIndex !== undefined && { index: siblingIndex }),
});
}
return success(presented);
}
// List recent documents via the search provider (with no query) so
// access control matches the search path exactly.
const searchProvider = SearchProviderManager.getProvider();
const filters: Filter[] = [
{ field: "publishedAt", operator: "isNotNull" },
];
if (!includeArchived) {
filters.push({ field: "archivedAt", operator: "isNull" });
}
if (collectionId) {
filters.push({
field: "collectionId",
operator: "eq",
value: collectionId,
});
}
if (input.ownerId) {
filters.push({
field: "ownerIds",
operator: "eq",
value: input.ownerId,
});
}
const { results } = await searchProvider.searchForUser(user, {
filter: { operator: "AND", filters },
offset: effectiveOffset,
limit: effectiveLimit,
});
const documents = results.map((result) => result.document);
const [breadcrumbs, shareUrls] = await Promise.all([
getBreadcrumbsForDocuments(documents, user),
getPublicShareUrlsForDocuments(
user.team,
documents.map((document) => document.id)
),
]);
const presented = await Promise.all(
documents.map(async (document) => {
const doc = pathToUrl(
user.team,
await presentDocument(document, {
includeData: false,
includeText: false,
})
);
const breadcrumb = breadcrumbs.get(document.id);
const shareUrl = shareUrls.get(document.id);
const siblingIndex = indexMap?.get(document.id);
return {
document: doc,
...(breadcrumb !== undefined && { breadcrumb }),
...(shareUrl !== undefined && { shareUrl }),
...(siblingIndex !== undefined && { index: siblingIndex }),
};
})
);
return success(presented);
} catch (message) {
return error(message);
}
}
)
);
}
if (AuthenticationHelper.canAccess("collections.documents", scopes)) {
server.registerTool(
"list_collection_documents",
{
title: "List all documents in a collection",
description:
"Returns the complete hierarchical tree of published documents in a collection, including nested sub-documents. Use this to enumerate every document in a collection or to understand parent/child relationships. Drafts and archived documents are not included.",
annotations: {
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
readOnlyHint: true,
},
inputSchema: z.object({
collectionId: z
.string()
.describe(
"The ID of the collection whose document tree to return."
),
}),
},
withTracing(
"list_collection_documents",
async ({ collectionId }, extra) => {
try {
const user = getActorFromContext(extra);
const collection = await Collection.findByPk(collectionId, {
userId: user.id,
rejectOnEmpty: true,
});
authorize(user, "readDocument", collection);
const documentStructure =
await collection.getCachedDocumentStructure();
const tree = (documentStructure ?? []).map((node) =>
presentNavigationNode(user.team, node)
);
return success(tree);
} catch (message) {
return error(message);
}
}
)
);
}
if (AuthenticationHelper.canAccess("documents.create", scopes)) {
server.registerTool(
"create_document",
{
title: "Create document",
description: `Creates a new document from markdown or HTML content. Requires a collectionId to place the document in a collection, or parentDocumentId to nest it under an existing document. Use the collectionId "${PersonalCollectionId}" to place the document in the user's personal collection, which only they can see and which is created if it does not exist yet. Pass a templateId (from list_templates) to pre-fill the document from a template; the template's content is used unless text is also provided.`,
annotations: {
destructiveHint: false,
idempotentHint: false,
// HTML imports download remote images and videos.
openWorldHint: true,
readOnlyHint: false,
},
inputSchema: z.object({
title: optionalString().describe(
"The title of the document. Defaults to the template's title when a templateId is provided."
),
text: z
.string()
.optional()
.describe(
'The content of the document. Interpreted as markdown unless format is set to "html".'
),
format: z
.enum(["markdown", "html"])
.optional()
.describe(
'The format of the text content. Defaults to "markdown"; use "html" for rich HTML input.'
),
sourceFileName: optionalString().describe(
'The name of the file the content was read from, e.g. "notes.md". Recorded on the document and shown to users as the file it was imported from, so only set it when the content genuinely came from a file. Also used as the title when the content has no heading and no title is given.'
),
collectionId: optionalString().describe(
`The collection to place the document in, or "${PersonalCollectionId}" for the user's personal collection.`
),
parentDocumentId: optionalString().describe(
"The parent document ID to nest this document under."
),
templateId: optionalString().describe(
"The ID of a template to pre-fill the new document from. The template's title, content, icon, and color are used unless overridden by the corresponding parameters."
),
icon: optionalString().describe(
"An icon for the document. 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 document icon, e.g. #FF0000."
),
publish: z
.boolean()
.optional()
.describe(
"Whether to publish the document. Defaults to true. Set to false to create as a draft."
),
fullWidth: z
.boolean()
.optional()
.describe(
"Whether the document should occupy full width of the screen. Defaults to false. Do not set this to true for HTML input unless the user explicitly asks for a full-width document layout."
),
ownerIds: z
.array(z.uuid())
.max(DocumentValidation.maxOwners)
.optional()
.describe(
"The IDs of users responsible for the document. Owners must be members or admins of the workspace, use list_users to find user IDs."
),
}),
},
withTracing("create_document", async (input, context) => {
try {
const { collectionId, parentDocumentId, templateId } = input;
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
const { collection, parentDocument } = await authorizeDocumentCreate(
ctx,
{ collectionId, parentDocumentId }
);
let template: Template | null | undefined;
if (templateId) {
template = await Template.findByPk(templateId, {
userId: user.id,
});
authorize(user, "read", template);
}
// Parsing HTML loads a full DOM, which would block the event loop for
// every other request, so hand it to a worker instead.
const document =
input.format === "html"
? await DocumentImportTask.scheduleAndWait({
content: input.text ?? "",
sourceMetadata: {
fileName: input.sourceFileName ?? "document.html",
mimeType: "text/html",
},
attributes: {
title: input.title,
icon: input.icon,
color: input.color,
fullWidth: input.fullWidth,
ownerIds: input.ownerIds,
},
userId: user.id,
publish: input.publish !== false,
collectionId: collection?.id,
parentDocumentId: parentDocument?.id,
authType: ctx.auth.type,
ip: ctx.ip,
})
: await sequelize.transaction(async (transaction) => {
ctx.transaction = transaction;
ctx.transaction = transaction;
return documentCreator(ctx, {
title: input.title,
text: input.text,
icon: input.icon,
color: input.color,
parentDocumentId: parentDocument?.id,
publish: input.publish !== false,
collectionId: collection?.id,
template,
fullWidth: input.fullWidth,
ownerIds: input.ownerIds,
sourceMetadata: input.sourceFileName
? {
fileName: input.sourceFileName,
mimeType: "text/markdown",
}
: undefined,
});
});
const breadcrumb = await getDocumentBreadcrumb(document, user);
return success({
success: true,
...pathToUrl(user.team, {
id: document.id,
title: document.title,
url: document.url,
}),
...(breadcrumb !== undefined && { breadcrumb }),
});
} catch (message) {
return error(message);
}
})
);
}
if (AuthenticationHelper.canAccess("documents.move", scopes)) {
server.registerTool(
"move_document",
{
title: "Move document",
description:
"Moves a document to a different location or reorders it within its current parent. Provide a collectionId to move to the root of a collection, a parentDocumentId to nest under another document, and/or an index to control position among siblings.",
annotations: {
destructiveHint: true,
idempotentHint: false,
openWorldHint: false,
readOnlyHint: false,
},
inputSchema: z.object({
id: z
.string()
.describe("The unique identifier of the document to move."),
collectionId: optionalString().describe(
`The destination collection ID, or "${PersonalCollectionId}" for the user's personal collection. Required if parentDocumentId is not provided.`
),
parentDocumentId: optionalString().describe(
"The ID of the document to nest this document under. The document will be moved to the parent's collection."
),
index: z
.number()
.int()
.min(0)
.optional()
.describe(
"The zero-based position to insert the document among its siblings. Use this to reorder documents within the same collection and parent. Omit to place at the end."
),
}),
},
withTracing("move_document", async (input, context) => {
try {
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
const document = await sequelize.transaction(async (transaction) => {
ctx.transaction = transaction;
ctx.transaction = transaction;
const document = await Document.findByPk(input.id, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
authorize(user, "move", document);
// A parent decides the collection, so the personal collection is
// only resolved, and created, when there is no parent.
let collectionId = input.parentDocumentId
? input.collectionId
: await resolvePersonalCollectionId(ctx, input.collectionId);
// The inputs may be urlIds, so the ids of the loaded models are used.
let parentDocumentId: string | null = null;
if (input.parentDocumentId) {
const parent = await Document.findByPk(input.parentDocumentId, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
if (parent.id === document.id) {
throw ValidationError("Cannot nest a document inside itself");
}
authorize(user, "update", parent);
collectionId = parent.collectionId!;
parentDocumentId = parent.id;
if (!parent.publishedAt) {
throw ValidationError("Cannot move document inside a draft");
}
} else if (!collectionId) {
throw ValidationError(
"Either collectionId or parentDocumentId is required"
);
} else {
const collection = await Collection.findByPk(collectionId, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
authorize(user, "updateDocument", collection);
collectionId = collection.id;
}
await documentMover(ctx, {
document,
collectionId: collectionId ?? null,
parentDocumentId,
index: input.index,
});
return document;
});
// Resolved after commit so the breadcrumb reflects the new location.
const breadcrumb = await getDocumentBreadcrumb(document, user);
return success({
success: true,
...pathToUrl(user.team, {
id: document.id,
title: document.title,
url: document.url,
}),
...(breadcrumb !== undefined && { breadcrumb }),
});
} catch (message) {
return error(message);
}
})
);
}
if (AuthenticationHelper.canAccess("documents.update", scopes)) {
server.registerTool(
"update_document",
{
title: "Update document",
description:
'Updates an existing document by its ID. Only the fields provided will be updated. IMPORTANT: When editing an existing document\'s content, always prefer editMode "patch" with findText and text — this surgically replaces only the matched section and preserves all rich formatting (highlights, comments, table widths, etc) in the rest of the document. Using "replace" will overwrite the entire document and lose any formatting that cannot be represented in markdown.',
annotations: {
destructiveHint: true,
idempotentHint: false,
openWorldHint: false,
readOnlyHint: false,
},
inputSchema: z.object({
id: z
.string()
.describe("The unique identifier of the document to update."),
title: optionalString().describe("The new title for the document."),
text: z
.string()
.optional()
.describe(
'The markdown content to apply. In "replace" mode this becomes the entire document. In "append"/"prepend" mode it is added to the end/beginning. In "patch" mode this is the replacement text for the matched findText.'
),
editMode: z
.enum(TextEditMode)
.optional()
.describe(
'How to apply the text update. "replace" (default) replaces the entire document content. "append" adds text to the end. "prepend" adds text to the beginning. "patch" finds the exact markdown specified in findText and replaces only that portion, preserving the rest of the document including any rich formatting that cannot be represented in markdown.'
),
findText: optionalString().describe(
'Required when editMode is "patch". The exact markdown substring to find in the document. This should be copied verbatim from the document\'s existing markdown content. The first occurrence will be replaced with the text parameter. Can span multiple blocks (paragraphs, headings, etc).'
),
collectionId: optionalString().describe(
`The collection ID to publish a draft to, or "${PersonalCollectionId}" for the user's personal collection. Required when publishing a draft that has no collection.`
),
icon: z
.string()
.nullable()
.optional()
.describe(
"An icon for the document. 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 document icon. Set to null to remove."
),
publish: z
.boolean()
.optional()
.describe(
"Set to true to publish a draft document, or false to convert a published document back to a draft."
),
fullWidth: z
.boolean()
.optional()
.describe(
"Whether the document should occupy full width of the screen."
),
ownerIds: z
.array(z.uuid())
.max(DocumentValidation.maxOwners)
.optional()
.describe(
"The complete list of IDs of users responsible for the document, 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_document", async (input, context) => {
try {
if (
(input.editMode === undefined ||
input.editMode === TextEditMode.Replace) &&
input.findText
) {
throw ValidationError(
'findText cannot be used with replace editMode. Use editMode "patch" instead.'
);
}
if (
(input.editMode === TextEditMode.Append ||
input.editMode === TextEditMode.Prepend) &&
!input.text
) {
throw ValidationError(
"text is required when using append, prepend, or editMode"
);
}
if (input.editMode === TextEditMode.Patch) {
if (input.text === undefined) {
throw ValidationError(
"text is required when using patch editMode"
);
}
if (!input.findText) {
throw ValidationError(
"findText is required when using patch editMode"
);
}
}
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
// Returns null when the update persisted nothing.
const updated = await sequelize.transaction(async (transaction) => {
ctx.transaction = transaction;
ctx.transaction = transaction;
const document = await Document.findByPk(input.id, {
userId: user.id,
includeState: true,
rejectOnEmpty: true,
transaction,
});
if (input.publish === false) {
authorize(user, "unpublish", document);
return document.unpublishWithCtx(ctx, {
detach: false,
});
}
authorize(user, "update", document);
if (input.ownerIds) {
authorize(user, "manageOwners", document);
}
// The collection is only used when publishing a draft that has
// none, so the personal collection is only created in that case.
let collectionId =
input.collectionId === PersonalCollectionId
? input.publish && !document.collectionId
? await resolvePersonalCollectionId(ctx, input.collectionId)
: undefined
: input.collectionId;
if (input.publish) {
// The input may be a urlId, so the id of the loaded model is used.
const collection = await authorizeDocumentPublish(
ctx,
document,
collectionId
);
collectionId = collection?.id;
}
const { revisionCount } = document;
const result = await documentUpdater(ctx, {
document,
...input,
collectionId,
});
// Every save increments revisionCount, so an unchanged count means
// nothing was persisted. 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
// document.
return result.revisionCount === revisionCount ? null : result;
});
if (!updated) {
return error(
"The update resulted in no changes to the document. Ensure at least one field is provided and differs from the current document."
);
}
// A patch only rewrites part of the document, so the resulting
// content is echoed back for the caller to verify what was applied.
// Other modes have nothing to report beyond the write succeeding.
if (input.editMode !== TextEditMode.Patch) {
const breadcrumb = await getDocumentBreadcrumb(updated, user);
return success({
success: true,
...pathToUrl(user.team, {
id: updated.id,
title: updated.title,
url: updated.url,
}),
...(breadcrumb !== undefined && { breadcrumb }),
});
}
const [{ text, ...attributes }, breadcrumb, shareUrl] =
await Promise.all([
presentDocument(updated, {
includeData: false,
includeText: true,
includeUpdatedAt: true,
}),
getDocumentBreadcrumb(updated, user),
getPublicShareUrlForDocument(user.team, updated.id),
]);
return {
content: [
{
type: "text" as const,
text: JSON.stringify({
document: pathToUrl(user.team, attributes),
...(breadcrumb !== undefined && { breadcrumb }),
...(shareUrl !== undefined && { shareUrl }),
}),
},
{
type: "text" as const,
text: typeof text === "string" ? text : "",
},
],
} satisfies CallToolResult;
} catch (message) {
return error(message);
}
})
);
}
if (AuthenticationHelper.canAccess("documents.delete", scopes)) {
server.registerTool(
"delete_document",
{
title: "Delete document",
description:
"Deletes a document by its ID. The document is moved to the trash and can be restored later. Set archive to true to archive the document 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 document to delete."),
archive: z
.boolean()
.optional()
.describe(
"Set to true to archive the document instead of deleting it. Archived documents remain searchable in the archive view."
),
reason: z
.string()
.trim()
.max(DeprecationValidation.maxReasonLength)
.nullish()
.describe(
"A plain text reason for archiving or deleting the document. Omit to keep the existing reason, or use null or an empty string to clear it."
),
}),
},
withTracing(
"delete_document",
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 document = await Document.findByPk(id, {
userId: user.id,
rejectOnEmpty: true,
transaction,
});
authorize(user, archive ? "archive" : "delete", document);
if (reason !== undefined) {
document.deprecatedReason = reason || null;
}
if (archive) {
await document.archiveWithCtx(ctx);
} else {
await document.destroyWithCtx(ctx);
}
});
return success({ success: true });
} catch (message) {
return error(message);
}
}
)
);
}
if (AuthenticationHelper.canAccess("documents.restore", scopes)) {
server.registerTool(
"restore_document",
{
title: "Restore document",
description:
"Restores an archived or trashed document, making it active again. Optionally provide a collectionId to restore the document into a different collection; otherwise it returns to its original collection.",
annotations: {
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
readOnlyHint: false,
},
inputSchema: z.object({
id: z
.string()
.describe("The unique identifier of the document to restore."),
collectionId: optionalString().describe(
"The collection to restore the document into. Defaults to its original collection."
),
}),
},
withTracing("restore_document", async ({ id, collectionId }, context) => {
try {
const ctx = buildAPIContext(context);
const { user } = ctx.auth;
const document = await sequelize.transaction(async (transaction) => {
ctx.transaction = transaction;
ctx.transaction = transaction;
const document = await Document.findByPk(id, {
userId: user.id,
paranoid: false,
transaction,
});
authorize(user, "read", document);
if (!document.deletedAt && !document.archivedAt) {
throw ValidationError("Document is not archived or trashed");
}
await documentRestorer(ctx, { document, collectionId });
return document;
});
// Resolved after commit so the breadcrumb reflects the new location.
const breadcrumb = await getDocumentBreadcrumb(document, user);
return success({
success: true,
...pathToUrl(user.team, {
id: document.id,
title: document.title,
url: document.url,
}),
...(breadcrumb !== undefined && { breadcrumb }),
});
} catch (message) {
return error(message);
}
})
);
}
}