⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(agent-tools): add Notion integration with page and comment tools (#181)
Croff566fb7c9616f
diff --git a/packages/agent-tools/package.json b/packages/agent-tools/package.jsonindex 544e5cde..e72fcfcb 100644--- a/packages/agent-tools/package.json+++ b/packages/agent-tools/package.json@@ -8,7 +8,8 @@},"scripts": {"lint": "eslint .",- "typecheck": "tsc --noEmit"+ "typecheck": "tsc --noEmit",+ "test": "bun test"},"dependencies": {"zod": "^4.4.3"diff --git a/packages/agent-tools/src/registry.ts b/packages/agent-tools/src/registry.tsindex 3f855765..d0420f8d 100644--- a/packages/agent-tools/src/registry.ts+++ b/packages/agent-tools/src/registry.ts@@ -11,10 +11,11 @@ import { firecrawl } from './tools/firecrawl';import { telegram } from './tools/telegram';import { threads } from './tools/threads';import { instagram } from './tools/instagram';+import { notion } from './tools/notion';// The registry of tool integrations. Add an integration by creating its folder under// tools/ and listing it here.-export const INTEGRATIONS: Integration[] = [jina, firecrawl, telegram, threads, instagram];+export const INTEGRATIONS: Integration[] = [jina, firecrawl, telegram, threads, instagram, notion];const BY_KEY = new Map(INTEGRATIONS.map((i) => [i.key, i]));diff --git a/packages/agent-tools/src/tools/notion/__tests__/page.test.ts b/packages/agent-tools/src/tools/notion/__tests__/page.test.tsnew file mode 100644index 00000000..2bb88fa0--- /dev/null+++ b/packages/agent-tools/src/tools/notion/__tests__/page.test.ts@@ -0,0 +1,72 @@+import { describe, it, expect } from 'bun:test';+import { fromRichText, pageProperties, pageTitle, titleProperty } from '../page';+import { notionId } from '../client';+import { cut } from '../read-page';++describe('notion page', () => {+ it('renders rich text annotations and links as markdown', () => {+ const items = [+ { plain_text: 'plain ' },+ { plain_text: 'bold', annotations: { bold: true } },+ { plain_text: ' and a ' },+ { plain_text: 'link', href: 'https://example.com' },+ ];+ expect(fromRichText(items)).toBe('plain **bold** and a [link](https://example.com)');+ });++ it('reads the title whatever the property is named', () => {+ const page = {+ properties: {+ Done: { type: 'checkbox', checkbox: true },+ Name: { type: 'title', title: [{ plain_text: 'Roadmap' }] },+ },+ };+ expect(pageTitle(page)).toBe('Roadmap');+ });++ it('writes a title under the id every title property carries', () => {+ expect(titleProperty('Roadmap')).toEqual({+ title: { title: [{ type: 'text', text: { content: 'Roadmap' } }] },+ });+ });++ it('flattens properties to plain values', () => {+ const page = {+ properties: {+ Status: { type: 'status', status: { name: 'In progress' } },+ Tags: { type: 'multi_select', multi_select: [{ name: 'api' }, { name: 'docs' }] },+ Key: { type: 'unique_id', unique_id: { prefix: 'ISAP', number: 306 } },+ Estimate: { type: 'formula', formula: { type: 'number', number: 3 } },+ Owner: { type: 'people', people: [{ name: 'Ann' }] },+ Cover: { type: 'files', files: [] },+ },+ };+ expect(pageProperties(page)).toEqual({+ Status: 'In progress',+ Tags: ['api', 'docs'],+ Key: 'ISAP-306',+ Estimate: 3,+ Owner: ['Ann'],+ Cover: null,+ });+ });++ it('cuts an oversized body at a line break and leaves a short one alone', () => {+ const short = 'line one\nline two';+ expect(cut(short)).toBe(short);++ const long = `${'x'.repeat(59_000)}\n${'y'.repeat(5_000)}`;+ expect(cut(long)).toBe('x'.repeat(59_000));++ const unbroken = 'z'.repeat(70_000);+ expect(cut(unbroken)).toHaveLength(60_000);+ });++ it('takes an id from a page URL, a dashed id, or a bare id', () => {+ const id = '1a2b3c4d5e6f7081920a1b2c3d4e5f60';+ expect(notionId(`https://www.notion.so/Some-Page-${id}`)).toBe(id);+ expect(notionId('1a2b3c4d-5e6f-7081-920a-1b2c3d4e5f60')).toBe(id);+ expect(notionId(id)).toBe(id);+ expect(() => notionId('a page')).toThrow('not a Notion page id or URL');+ });+});diff --git a/packages/agent-tools/src/tools/notion/add-comment.ts b/packages/agent-tools/src/tools/notion/add-comment.tsnew file mode 100644index 00000000..0f936648--- /dev/null+++ b/packages/agent-tools/src/tools/notion/add-comment.ts@@ -0,0 +1,34 @@+import { z } from 'zod';+import type { CustomToolEntry } from '../../types';+import { notionId, notionRequest, notionToken } from './client';++// Comments on a page: a new thread on the page itself, or a reply into an existing+// discussion read with notion_read_comments.+export const notionAddComment: CustomToolEntry = {+ key: 'notion_add_comment',+ label: 'Notion Add Comment',+ scopes: ['Insert comments'],+ description:+ 'Comment on a Notion page. Give a pageId to start a new comment on the page, or a discussionId from notion_read_comments to reply inside that thread. A comment carries inline formatting only: bold, italic, strikethrough, code and links.',+ inputSchema: z.object({+ pageId: z.string().optional().describe('Page to comment on. Starts a new thread.'),+ discussionId: z.string().optional().describe('Thread to reply into.'),+ text: z.string().min(1).describe('The comment text, as markdown.'),+ }),+ execute: async (credential, input) => {+ if (!input.discussionId && !input.pageId) {+ throw new Error('Give either a pageId to start a thread or a discussionId to reply.');+ }+ const token = notionToken(credential);+ const target = input.discussionId+ ? { discussion_id: String(input.discussionId) }+ : { parent: { page_id: notionId(input.pageId) } };+ const comment = await notionRequest(token, 'POST', 'comments', {+ ...target,+ markdown: String(input.text),+ });+ // A token without the read comments capability gets back the id alone, so the+ // thread it just started cannot be replied to in the same run.+ return { id: String(comment.id ?? ''), discussionId: comment.discussion_id ?? null };+ },+};diff --git a/packages/agent-tools/src/tools/notion/client.ts b/packages/agent-tools/src/tools/notion/client.tsnew file mode 100644index 00000000..b8c71d4d--- /dev/null+++ b/packages/agent-tools/src/tools/notion/client.ts@@ -0,0 +1,109 @@+import type { ToolConfig } from '../../types';+import { sleep } from '../time';++// Notion REST API client. Every tool authenticates with the credential's integration+// token and pins the API version these request shapes were written against.+//+// Notion answers a burst from one connection with 429, and an overloaded workspace+// with 529; both carry a Retry-After delay. The client waits and repeats the call, so+// a rate limit slows a run down instead of failing it.++const NOTION_BASE = 'https://api.notion.com/v1';+const NOTION_VERSION = '2026-03-11';+const RETRY_STATUSES = new Set([429, 529]);+const RETRIES = 5;+const FALLBACK_RETRY_MS = 1000;++export interface NotionResponse {+ results?: Record<string, unknown>[];+ code?: string;+ message?: string;+ [key: string]: unknown;+}++export function notionToken(credential: ToolConfig): string {+ const token = credential.token ? String(credential.token) : '';+ if (!token) throw new Error('No Notion token configured.');+ return token;+}++// The bare id of a page or block. A model passes an id with or without dashes, or the+// page URL it was given, so all three are accepted.+export function notionId(raw: unknown, what = 'page'): string {+ const value = String(raw ?? '').trim();+ const match = value.match(/[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}/i);+ if (!match) throw new Error(`"${value}" is not a Notion ${what} id or URL.`);+ return match[0].replace(/-/g, '');+}++// The Notion capability a call needs, derived from the endpoint, so a rejected call+// names the permission to grant on the integration.+function capabilityFor(method: string, path: string): string {+ if (path.startsWith('comments')) return method === 'GET' ? 'Read comments' : 'Insert comments';+ if (method === 'GET' || path.startsWith('search')) return 'Read content';+ if (path === 'pages') return 'Insert content';+ return 'Update content';+}++// Turns a Notion error body into a message the agent can act on: the two failures a+// token runs into (a page nobody shared with it, a capability nobody granted it) name+// what to change in Notion instead of reading as "not found".+function explain(status: number, body: NotionResponse, capability: string): string {+ const detail = body.message ? `: ${body.message}` : '';+ switch (body.code) {+ case 'object_not_found':+ return `Notion cannot see this page. Share it with the integration in Notion (open the page, "..." menu, Connections, add the connection)${detail}`;+ case 'restricted_resource':+ return `The Notion token is missing the "${capability}" capability. Grant it to the integration in Notion, then retry${detail}`;+ case 'unauthorized':+ return `The Notion token is invalid or was revoked${detail}`;+ case 'rate_limited':+ case 'service_overload':+ return `Notion is still throttling this connection after ${RETRIES} retries${detail}`;+ default:+ return `Notion API error (${status})${detail}`;+ }+}++// How long to wait before repeating a throttled call. Notion sends the delay in+// Retry-After (seconds); without it the wait doubles per attempt, with jitter so+// several parallel tool calls do not retry in the same instant.+function retryDelayMs(res: Response, attempt: number): number {+ const header = Number(res.headers.get('retry-after'));+ if (header > 0) return header * 1000;+ return FALLBACK_RETRY_MS * 2 ** attempt * (1 + Math.random());+}++// Calls a Notion endpoint and returns its parsed body. `path` is everything after+// /v1/, query string included.+export async function notionRequest(+ token: string,+ method: 'GET' | 'POST' | 'PATCH' | 'DELETE',+ path: string,+ body?: Record<string, unknown>,+): Promise<NotionResponse> {+ for (let attempt = 0; ; attempt++) {+ const res = await fetch(`${NOTION_BASE}/${path}`, {+ method,+ headers: {+ Authorization: `Bearer ${token}`,+ 'Notion-Version': NOTION_VERSION,+ ...(body ? { 'Content-Type': 'application/json' } : {}),+ },+ body: body ? JSON.stringify(body) : undefined,+ });+ if (RETRY_STATUSES.has(res.status) && attempt < RETRIES) {+ await sleep(retryDelayMs(res, attempt));+ continue;+ }+ const raw = await res.text();+ let parsed: NotionResponse = {};+ try {+ parsed = raw ? (JSON.parse(raw) as NotionResponse) : {};+ } catch {+ /* non-JSON error page */+ }+ if (!res.ok) throw new Error(explain(res.status, parsed, capabilityFor(method, path)));+ return parsed;+ }+}diff --git a/packages/agent-tools/src/tools/notion/create-page.ts b/packages/agent-tools/src/tools/notion/create-page.tsnew file mode 100644index 00000000..25f24a9a--- /dev/null+++ b/packages/agent-tools/src/tools/notion/create-page.ts@@ -0,0 +1,29 @@+import { z } from 'zod';+import type { CustomToolEntry } from '../../types';+import { notionId, notionRequest, notionToken } from './client';+import { titleProperty } from './page';++export const notionCreatePage: CustomToolEntry = {+ key: 'notion_create_page',+ label: 'Notion Create Page',+ scopes: ['Insert content'],+ description:+ 'Create a Notion page under an existing page. The parent page must be shared with the connection. The body is written as markdown: headings, lists, checkboxes, quotes, code blocks, tables, callouts, links and inline formatting.',+ inputSchema: z.object({+ parentPageId: z+ .string()+ .min(1)+ .describe('Id or URL of the page the new page is created under.'),+ title: z.string().min(1).describe('Title of the new page.'),+ markdown: z.string().optional().describe('Page body as markdown.'),+ }),+ execute: async (credential, input) => {+ const token = notionToken(credential);+ const page = await notionRequest(token, 'POST', 'pages', {+ parent: { page_id: notionId(input.parentPageId, 'parent page') },+ properties: titleProperty(String(input.title)),+ ...(input.markdown ? { markdown: String(input.markdown) } : {}),+ });+ return { id: String(page.id ?? ''), url: page.url ?? null, title: String(input.title) };+ },+};diff --git a/packages/agent-tools/src/tools/notion/index.ts b/packages/agent-tools/src/tools/notion/index.tsnew file mode 100644index 00000000..e1af813a--- /dev/null+++ b/packages/agent-tools/src/tools/notion/index.ts@@ -0,0 +1,32 @@+import type { Integration } from '../../types';+import { notionSearch } from './search';+import { notionReadPage } from './read-page';+import { notionCreatePage } from './create-page';+import { notionUpdatePage } from './update-page';+import { notionReadComments } from './read-comments';+import { notionAddComment } from './add-comment';++// Notion: pages an agent can find, read, write and discuss. One credential is one+// Notion integration token, and it reaches only the pages a person shared with it.+export const notion: Integration = {+ key: 'notion',+ label: 'Notion',+ credentialSchema: [+ {+ key: 'token',+ label: 'API token',+ type: 'secret',+ required: true,+ placeholder: 'ntn_...',+ help: 'The token of a Notion integration (app.notion.com/developers/connections); a workspace or a personal one both work. Each page the agent should reach must then be shared with that integration in Notion: open the page, "..." menu, Connections, add it. A page that is not connected stays invisible.',+ },+ ],+ tools: [+ notionSearch,+ notionReadPage,+ notionCreatePage,+ notionUpdatePage,+ notionReadComments,+ notionAddComment,+ ],+};diff --git a/packages/agent-tools/src/tools/notion/page.ts b/packages/agent-tools/src/tools/notion/page.tsnew file mode 100644index 00000000..6484841c--- /dev/null+++ b/packages/agent-tools/src/tools/notion/page.ts@@ -0,0 +1,97 @@+// Reading a page's shell: its title and its properties. The body of a page is+// markdown on both sides of the API, so only the property objects around it need+// flattening here.++interface RichTextItem {+ plain_text?: string;+ href?: string | null;+ annotations?: { bold?: boolean; italic?: boolean; code?: boolean; strikethrough?: boolean };+}++interface NotionProperty {+ type?: string;+ [key: string]: unknown;+}++// Renders a rich text array as markdown. Comments are read this way; page bodies come+// from Notion already as markdown.+export function fromRichText(items: unknown): string {+ if (!Array.isArray(items)) return '';+ return (items as RichTextItem[])+ .map((item) => {+ let text = item.plain_text ?? '';+ if (!text) return '';+ const marks = item.annotations ?? {};+ if (marks.code) text = `\`${text}\``;+ if (marks.bold) text = `**${text}**`;+ if (marks.italic) text = `*${text}*`;+ if (marks.strikethrough) text = `~~${text}~~`;+ if (item.href) text = `[${text}](${item.href})`;+ return text;+ })+ .join('');+}++// The title property of a page, as POST and PATCH /v1/pages take it. "title" is the id+// every title property carries, so this works whatever the property is named.+export function titleProperty(text: string): Record<string, unknown> {+ return { title: { title: [{ type: 'text', text: { content: text } }] } };+}++// The title of a page: the one property Notion types as "title", whatever it is named.+export function pageTitle(page: Record<string, unknown>): string {+ const properties = (page.properties ?? {}) as Record<string, NotionProperty>;+ for (const property of Object.values(properties)) {+ if (property?.type === 'title') return fromRichText(property.title);+ }+ return '';+}++// A page's properties as plain values, so the agent reads names and dates rather than+// Notion's nested property objects.+export function pageProperties(page: Record<string, unknown>): Record<string, unknown> {+ const properties = (page.properties ?? {}) as Record<string, NotionProperty>;+ const out: Record<string, unknown> = {};+ for (const [name, property] of Object.entries(properties)) {+ out[name] = propertyValue(property);+ }+ return out;+}++function propertyValue(property: NotionProperty): unknown {+ const type = String(property.type ?? '');+ const value = property[type];+ switch (type) {+ case 'title':+ case 'rich_text':+ return fromRichText(value);+ case 'number':+ case 'checkbox':+ case 'url':+ case 'email':+ case 'phone_number':+ case 'created_time':+ case 'last_edited_time':+ case 'date':+ return value ?? null;+ case 'select':+ case 'status':+ return (value as { name?: string } | null)?.name ?? null;+ case 'multi_select':+ return ((value ?? []) as { name?: string }[]).map((option) => option.name ?? '');+ case 'people':+ return ((value ?? []) as { name?: string; id?: string }[]).map((p) => p.name ?? p.id ?? '');+ case 'relation':+ return ((value ?? []) as { id?: string }[]).map((r) => r.id ?? '');+ case 'unique_id': {+ const unique = (value ?? {}) as { prefix?: string | null; number?: number };+ return unique.prefix ? `${unique.prefix}-${unique.number}` : (unique.number ?? null);+ }+ case 'formula': {+ const formula = (value ?? {}) as { type?: string } & Record<string, unknown>;+ return formula[formula.type ?? ''] ?? null;+ }+ default:+ return null;+ }+}diff --git a/packages/agent-tools/src/tools/notion/read-comments.ts b/packages/agent-tools/src/tools/notion/read-comments.tsnew file mode 100644index 00000000..bf819c80--- /dev/null+++ b/packages/agent-tools/src/tools/notion/read-comments.ts@@ -0,0 +1,37 @@+import { z } from 'zod';+import type { CustomToolEntry } from '../../types';+import { notionId, notionRequest, notionToken } from './client';+import { fromRichText } from './page';++// Notion returns at most 100 comments in one request, oldest first; a longer thread is+// cut there rather than paged through, so one call stays small.+const MAX_COMMENTS = 100;++// Reads the open comments on a page itself; comments left on its blocks are separate+// threads and are not returned.+export const notionReadComments: CustomToolEntry = {+ key: 'notion_read_comments',+ label: 'Notion Read Comments',+ scopes: ['Read comments'],+ description:+ 'Read the open comments on a Notion page. Each comment carries a discussionId, which notion_add_comment takes to reply in the same thread. Resolved comments are not returned.',+ inputSchema: z.object({+ pageId: z.string().min(1).describe('The page id, or the page URL copied from Notion.'),+ }),+ execute: async (credential, input) => {+ const pageId = notionId(input.pageId);+ const body = await notionRequest(+ notionToken(credential),+ 'GET',+ `comments?block_id=${pageId}&page_size=${MAX_COMMENTS}`,+ );+ const comments = (body.results ?? []).map((comment) => ({+ id: String(comment.id ?? ''),+ discussionId: String(comment.discussion_id ?? ''),+ createdTime: comment.created_time ?? null,+ authorId: (comment.created_by as { id?: string } | undefined)?.id ?? null,+ text: fromRichText(comment.rich_text),+ }));+ return { comments };+ },+};diff --git a/packages/agent-tools/src/tools/notion/read-page.ts b/packages/agent-tools/src/tools/notion/read-page.tsnew file mode 100644index 00000000..ede5bc3f--- /dev/null+++ b/packages/agent-tools/src/tools/notion/read-page.ts@@ -0,0 +1,52 @@+import { z } from 'zod';+import type { CustomToolEntry } from '../../types';+import { notionId, notionRequest, notionToken } from './client';+import { pageProperties, pageTitle } from './page';++// Notion renders a page of up to ~20,000 blocks in one response, far past the ~25k+// tokens a model still reads and searches over reliably. The bound is in characters+// because there is no tokenizer here: Cyrillic markdown runs about 2.5 characters per+// token, so 60,000 stays inside the budget in the worst case and holds a much longer+// page in Latin script. `truncated` says the page went on — whether it was Notion or+// this cap that stopped it.+const MAX_CHARS = 60000;++// Cuts at the last line break before the bound, so the body does not end mid-line.+export function cut(markdown: string): string {+ if (markdown.length <= MAX_CHARS) return markdown;+ const head = markdown.slice(0, MAX_CHARS);+ const lastBreak = head.lastIndexOf('\n');+ return lastBreak > 0 ? head.slice(0, lastBreak) : head;+}++// Reads a page: its properties, and its body as the markdown Notion renders it from+// the whole block tree.+export const notionReadPage: CustomToolEntry = {+ key: 'notion_read_page',+ label: 'Notion Read Page',+ scopes: ['Read content'],+ description:+ 'Read a Notion page: its properties and its full body as markdown, tables, callouts and sub-pages included. The exact text that comes back is what notion_update_page matches against when editing part of the page.',+ inputSchema: z.object({+ pageId: z.string().min(1).describe('The page id, or the page URL copied from Notion.'),+ }),+ execute: async (credential, input) => {+ const token = notionToken(credential);+ const id = notionId(input.pageId);+ const [page, body] = await Promise.all([+ notionRequest(token, 'GET', `pages/${id}`),+ notionRequest(token, 'GET', `pages/${id}/markdown`),+ ]);+ const markdown = String(body.markdown ?? '');+ const content = cut(markdown);+ return {+ id,+ url: page.url ?? null,+ title: pageTitle(page),+ properties: pageProperties(page),+ lastEditedTime: page.last_edited_time ?? null,+ content,+ truncated: body.truncated === true || content.length < markdown.length,+ };+ },+};diff --git a/packages/agent-tools/src/tools/notion/search.ts b/packages/agent-tools/src/tools/notion/search.tsnew file mode 100644index 00000000..0a01aecb--- /dev/null+++ b/packages/agent-tools/src/tools/notion/search.ts@@ -0,0 +1,37 @@+import { z } from 'zod';+import type { CustomToolEntry } from '../../types';+import { notionRequest, notionToken } from './client';+import { pageTitle } from './page';++// Finds pages by title among those shared with the integration.+export const notionSearch: CustomToolEntry = {+ key: 'notion_search',+ label: 'Notion Search',+ scopes: ['Read content'],+ description:+ 'Find Notion pages by name. Only pages shared with the connection are searchable. Returns each match with its page id, which the other Notion tools take. Omit the query to list every page the connection can see.',+ inputSchema: z.object({+ query: z.string().optional().describe('Text to match against page titles.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(50)+ .optional()+ .describe('How many pages to return (default 10).'),+ }),+ execute: async (credential, input) => {+ const body = await notionRequest(notionToken(credential), 'POST', 'search', {+ query: input.query ? String(input.query) : '',+ filter: { property: 'object', value: 'page' },+ page_size: Number(input.limit ?? 10),+ });+ const results = (body.results ?? []).map((page) => ({+ id: String(page.id ?? ''),+ title: pageTitle(page),+ url: page.url ?? null,+ lastEditedTime: page.last_edited_time ?? null,+ }));+ return { results };+ },+};diff --git a/packages/agent-tools/src/tools/notion/update-page.ts b/packages/agent-tools/src/tools/notion/update-page.tsnew file mode 100644index 00000000..add35a28--- /dev/null+++ b/packages/agent-tools/src/tools/notion/update-page.ts@@ -0,0 +1,68 @@+import { z } from 'zod';+import type { CustomToolEntry } from '../../types';+import { notionId, notionRequest, notionToken } from './client';+import { titleProperty } from './page';++// The body of a PATCH /v1/pages/{id}/markdown call for each mode the tool offers.+// "append" uses insert_content, which Notion marks legacy but is the only command+// that adds to a page without sending its whole body back.+function command(mode: string, markdown: string, find: string): Record<string, unknown> {+ switch (mode) {+ case 'replace':+ return { type: 'replace_content', replace_content: { new_str: markdown } };+ case 'edit':+ return {+ type: 'update_content',+ update_content: { content_updates: [{ old_str: find, new_str: markdown }] },+ };+ default:+ return {+ type: 'insert_content',+ insert_content: { content: markdown, position: { type: 'end' } },+ };+ }+}++export const notionUpdatePage: CustomToolEntry = {+ key: 'notion_update_page',+ label: 'Notion Update Page',+ scopes: ['Update content', 'Insert content'],+ description:+ 'Edit a Notion page. Mode "append" adds markdown to the end, "replace" rewrites the whole body, and "edit" swaps one passage for another: `find` is the existing text, copied exactly as notion_read_page returned it, and `markdown` is what replaces it. A title given without markdown only renames the page.',+ inputSchema: z.object({+ pageId: z.string().min(1).describe('The page id, or the page URL copied from Notion.'),+ mode: z+ .enum(['append', 'replace', 'edit'])+ .optional()+ .describe('How the markdown is applied (default "append").'),+ markdown: z.string().optional().describe('The new content as markdown.'),+ find: z+ .string()+ .optional()+ .describe('The exact existing text to replace. Required for mode "edit".'),+ title: z.string().optional().describe('New page title.'),+ }),+ execute: async (credential, input) => {+ const token = notionToken(credential);+ const pageId = notionId(input.pageId);+ const mode = String(input.mode ?? 'append');+ const markdown = input.markdown ? String(input.markdown) : '';++ if (input.title) {+ await notionRequest(token, 'PATCH', `pages/${pageId}`, {+ properties: titleProperty(String(input.title)),+ });+ }++ if (!markdown) {+ if (!input.title) throw new Error('Nothing to update: give markdown, a title, or both.');+ return { id: pageId, renamed: true };+ }++ const find = input.find ? String(input.find) : '';+ if (mode === 'edit' && !find) throw new Error('Mode "edit" needs the text to replace in find.');++ await notionRequest(token, 'PATCH', `pages/${pageId}/markdown`, command(mode, markdown, find));+ return { id: pageId, mode, updated: true };+ },+};