affine-markdown-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-12-01)
4
+
5
+ First release.
6
+
7
+ - 15 tools: `list_workspaces`, `tree`, `search`, `read_doc`, `write_doc`, `create_doc`, `trash_doc`, `create_folder`, `move_doc`, `list_boards`, `read_board`, `add_card`, `update_card`, `move_card`, `delete_card`
8
+ - Docs as Markdown both ways: headings, formatting, links, doc mentions, lists, todos, quotes, code, dividers, tables
9
+ - Keep markers so a rewrite keeps boards, images and other blocks Markdown cannot show
10
+ - Kanban cards by title or id, lanes by name, new select values added on the fly
11
+ - Read only mode (`AFFINE_READ_ONLY=true`)
12
+ - Works with self-hosted AFFiNE up to 0.27.4, refuses newer servers with a clear message
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bandy (bandy.sh)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # affine-markdown-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP server for **self-hosted [AFFiNE](https://affine.pro)**. Lets an AI agent (Claude Code, Claude Desktop, Cursor, any MCP client) work with your AFFiNE workspace like a teammate:
4
+
5
+ - see the **folder tree** like the sidebar
6
+ - **read docs as Markdown** and **write Markdown** back (append or replace)
7
+ - manage **Kanban boards**: add cards, move them between lanes, change fields, delete
8
+ - create docs and folders, move docs, trash and restore
9
+
10
+ It talks to AFFiNE the same way the web app does (Yjs over the sync socket), so changes show up live for everyone who has the doc open.
11
+
12
+ ![A doc and a Kanban board written through the MCP, as AFFiNE shows them](https://raw.githubusercontent.com/Tankonyako/affine-markdown-mcp/main/docs/affine-written-by-mcp.png)
13
+
14
+ *Everything on this page was written by the MCP: the Markdown (heading, bold, italic, todos, table, code) and the card moved to Complete with a new Author value.*
15
+
16
+ <br>
17
+
18
+ ## Tools
19
+
20
+ | Tool | What it does |
21
+ |---|---|
22
+ | `list_workspaces` | workspaces the bot can open |
23
+ | `tree` | folders and docs with ids, like the sidebar |
24
+ | `search` | docs whose title or text has the words, with snippets |
25
+ | `read_doc` | a doc as Markdown |
26
+ | `write_doc` | Markdown into a doc, `append` or `replace` |
27
+ | `create_doc` | new doc from Markdown, optionally in a folder |
28
+ | `trash_doc` | move to trash or restore, nothing is deleted for good |
29
+ | `create_folder` | sidebar folder, at the top or inside another |
30
+ | `move_doc` | put a doc into a folder |
31
+ | `list_boards` | Kanban boards in a doc or the whole workspace, with lanes |
32
+ | `read_board` | cards grouped by lane, with their fields |
33
+ | `add_card` | new card with fields, `{"Status": "In Progress", "Author": "Yurii"}` |
34
+ | `update_card` | change a card title or fields |
35
+ | `move_card` | move a card to another lane |
36
+ | `delete_card` | remove a card |
37
+
38
+ Docs, folders, boards and cards can be named by **id or by title**, so the agent can just say `move_card {"doc": "Sprint", "card": "Fix login", "lane": "Done"}`. A new select value (status, author) is added to the board automatically.
39
+
40
+ Set `AFFINE_READ_ONLY=true` to register only the reading tools.
41
+
42
+ <br>
43
+
44
+ ## Requirements
45
+
46
+ - AFFiNE server **0.20 to 0.27.4**, self-hosted (`GET /info` must say so). 0.27.5 changed the sync join protocol, the server refuses to start against it with a clear message instead of breaking silently
47
+ - Node.js **20.19+** for the npm package (22.18+ to run the sources from a clone)
48
+ - an AFFiNE account for the agent, a separate bot user is best (see below)
49
+
50
+ <br>
51
+
52
+ ## Install
53
+
54
+ Nothing to install by hand, MCP clients start it with `npx`:
55
+
56
+ ```bash
57
+ npx -y affine-markdown-mcp
58
+ ```
59
+
60
+ It reads its settings from environment variables:
61
+
62
+ | Variable | Needed | Meaning |
63
+ |---|---|---|
64
+ | `AFFINE_BASE_URL` | yes | your AFFiNE, `https://affine.example.com` (plain http only for localhost) |
65
+ | `AFFINE_EMAIL` | yes | account the agent signs in as |
66
+ | `AFFINE_PASSWORD` | yes | its password |
67
+ | `AFFINE_WORKSPACE_ID` | no | default workspace, the id from `/workspace/<id>/...`. Without it tools take a workspace name |
68
+ | `AFFINE_READ_ONLY` | no | `true` = only the reading tools |
69
+
70
+ **Bot user (recommended).** Edits then show up as the bot, and your own password stays out of config. On an instance where sign up is closed, an admin can make one with
71
+
72
+ ```bash
73
+ git clone https://github.com/Tankonyako/affine-markdown-mcp && cd affine-markdown-mcp && npm ci
74
+ AFFINE_BASE_URL=https://affine.example.com AFFINE_ADMIN_EMAIL=you@example.com AFFINE_ADMIN_PASSWORD=... \
75
+ node scripts/setup-bot.ts --workspace-name "My workspace" --bot claude@example.com
76
+ ```
77
+
78
+ It creates the user with a random password, invites it into the workspace as a collaborator, makes a separate **"MCP test"** workspace for the integration tests and writes everything into `.env`. The password is only in `.env`.
79
+
80
+ <br>
81
+
82
+ ## Use it from Claude Code
83
+
84
+ ```bash
85
+ claude mcp add affine \
86
+ --env AFFINE_BASE_URL=https://affine.example.com \
87
+ --env AFFINE_EMAIL=claude@example.com \
88
+ --env AFFINE_PASSWORD=... \
89
+ --env AFFINE_WORKSPACE_ID=<workspace id> \
90
+ -- npx -y affine-markdown-mcp
91
+ ```
92
+
93
+ or in a project `.mcp.json` (values come from your environment, nothing secret in the file). Claude Desktop, Cursor and other clients take the same `command` / `args` / `env` block
94
+
95
+ ```json
96
+ {
97
+ "mcpServers": {
98
+ "affine": {
99
+ "command": "npx",
100
+ "args": ["-y", "affine-markdown-mcp"],
101
+ "env": {
102
+ "AFFINE_BASE_URL": "${AFFINE_BASE_URL}",
103
+ "AFFINE_EMAIL": "${AFFINE_EMAIL}",
104
+ "AFFINE_PASSWORD": "${AFFINE_PASSWORD}",
105
+ "AFFINE_WORKSPACE_ID": "${AFFINE_WORKSPACE_ID}"
106
+ }
107
+ }
108
+ }
109
+ }
110
+ ```
111
+
112
+ A line in the project's `CLAUDE.md` helps the agent use it, for example *"Tasks are cards on the board in the AFFiNE doc Sprint, docs are in the AFFiNE folder Engineering. Use the affine tools, start with tree."*
113
+
114
+ <br>
115
+
116
+ ## How Markdown maps to AFFiNE
117
+
118
+ | Markdown | AFFiNE block |
119
+ |---|---|
120
+ | `#` to `######` | heading 1 to 6 |
121
+ | text with `**bold**` `*italic*` `~~strike~~` `` `code` `` `[link](url)` | paragraph with the same formatting |
122
+ | `- item`, `1. item`, nested | bulleted / numbered list, nested |
123
+ | `- [ ] todo`, `- [x] done` | todo list |
124
+ | `> quote` | quote |
125
+ | fenced code with a language | code block |
126
+ | `---` | divider |
127
+ | GFM table | AFFiNE table |
128
+ | `[Title](affine://<docId>)` | link to another doc (`@` mention) |
129
+
130
+ Blocks Markdown cannot show (images, embeds, attachments) are read as a marker `<!-- affine:block <id> affine:image -->`. A **board** is read as a table between `<!-- board:<id> ... -->` and `<!-- /board -->`. When the agent writes the doc back with `replace` and leaves a marker or the board section in place, that block stays exactly as it was (at the new position). Taking a marker out removes the block, so `replace` is marked destructive for the client.
131
+
132
+ <br>
133
+
134
+ ## Development
135
+
136
+ Node 22.18+ runs the TypeScript sources directly (the npm package is plain JS and runs on Node 20.19+).
137
+
138
+ ```bash
139
+ npm ci
140
+ cp .env.example .env # bot login, see above
141
+ node scripts/mcp-check.ts tree '{}' read_board '{"doc":"Sprint"}'
142
+ npm test # unit tests, no network (node:test)
143
+ npm run test:integration # real server against AFFINE_TEST_WORKSPACE_ID, writes and trashes docs there
144
+ npm run typecheck
145
+ npm run lint
146
+ node e2e/run-claude-check.ts # a real Claude Code run in e2e/dummy-project, then checks AFFiNE (uses your Claude login)
147
+ npm pack # builds dist/ and the .tgz that npm would publish
148
+ ```
149
+
150
+ Release: bump `version` in `package.json` and `SERVER_VERSION` in `src/api/mcp-server.ts` (a unit test checks they match), add a `CHANGELOG.md` entry, then either `npm publish` (runs typecheck, lint, tests and the build first) or publish a GitHub release `v<version>`, the `Publish` workflow then publishes with provenance (needs the `NPM_TOKEN` repo secret).
151
+
152
+ Code layout: `src/types` (plain types), `src/domain` (Markdown and board rendering, no I/O), `src/infrastructure/affine` (HTTP session, sync socket, Yjs page/board/folder adapters), `src/application` (use cases, id or title resolution), `src/api/mcp-server.ts` (tools), `src/main.ts` (wiring). Style: `.editorconfig` and `eslint.config.js` (4 spaces, single quotes, Allman braces). Only erasable TypeScript, so Node runs the sources directly.
153
+
154
+ <br>
155
+
156
+ ## Limits
157
+
158
+ - One AFFiNE version range (see Requirements). AFFiNE's sync protocol is internal, not a public API
159
+ - Boards are not created from Markdown, make the board in the editor, then the agent manages its cards
160
+ - `search` reads docs one by one (max 300), fine for team workspaces, slow for huge ones
161
+ - Edgeless (canvas) content is not read, only the document view
162
+
163
+ <br>
164
+
165
+ ## Credits
166
+
167
+ The sync protocol details (join, load, push update, folder and table storage) were learned from [DAWNCR0W/affine-mcp-server](https://github.com/DAWNCR0W/affine-mcp-server) (MIT). This is a separate, smaller implementation focused on Markdown and Kanban.
168
+
169
+ License: MIT
@@ -0,0 +1,204 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { z } from 'zod';
3
+ import { listWorkspaces } from "../application/affine-context.js";
4
+ import { addBoardCard, deleteBoardCard, getBoard, listBoards, moveBoardCard, updateBoardCard, } from "../application/board.use-cases.js";
5
+ import { createDoc, createFolder, moveDoc, readDoc, trashDoc, writeDoc } from "../application/doc.use-cases.js";
6
+ import { searchDocs, treeToText, workspaceTree } from "../application/workspace.use-cases.js";
7
+ import { formatValue } from "../domain/board/board-render.js";
8
+ import { AffineToolError } from "../types/result.types.js";
9
+ export const SERVER_NAME = 'affine-markdown-mcp';
10
+ export const SERVER_VERSION = '0.1.0';
11
+ const INSTRUCTIONS = `AFFiNE workspace: docs as Markdown, a folder tree and Kanban boards.
12
+ - Start with tree to see folders and docs. Docs and folders can be named by id or by title.
13
+ - read_doc gives Markdown. Boards and blocks Markdown cannot show (images, embeds) appear as <!-- board:... --> / <!-- affine:block ... --> markers. Keep those markers when you write the doc back with mode "replace", they keep the board or block in place. Removing a marker removes that block.
14
+ - Change board cards only with the board tools (add_card, update_card, move_card, delete_card). move_card sets the lane field (usually Status). New select values (a new status or author) are added to the board automatically.
15
+ - write_doc mode "append" adds to the end, "replace" rewrites the whole body.`;
16
+ const workspaceArg = z.string().optional().describe('Workspace id or name, leave out for the default workspace');
17
+ const docArg = z.string().describe('Doc id or title');
18
+ const boardArg = z.string().optional().describe('Board block id or board title, leave out when the doc has one board');
19
+ const fieldsArg = z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string()), z.null()]))
20
+ .optional()
21
+ .describe('Field name to value, for example {"Status": "In Progress", "Author": "Yurii"}. null clears a field');
22
+ export function createMcpServer(ctx, options) {
23
+ const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: INSTRUCTIONS });
24
+ const read = { readOnlyHint: true, openWorldHint: false };
25
+ const write = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
26
+ const destructive = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };
27
+ server.registerTool('list_workspaces', {
28
+ description: 'Workspaces the bot user can open, with id, name and role',
29
+ annotations: read,
30
+ }, () => run(async () => json(await listWorkspaces(ctx))));
31
+ server.registerTool('tree', {
32
+ description: 'Folder tree of a workspace with every doc (id and title), like the AFFiNE sidebar',
33
+ inputSchema: { workspace: workspaceArg },
34
+ annotations: read,
35
+ }, ({ workspace }) => run(async () => text(treeToText(await workspaceTree(ctx, workspace)))));
36
+ server.registerTool('search', {
37
+ description: 'Find docs whose title or text contains the words, with short snippets',
38
+ inputSchema: {
39
+ query: z.string().min(1),
40
+ workspace: workspaceArg,
41
+ limit: z.number().int().min(1).max(50).optional().describe('Most hits to return, default 10'),
42
+ },
43
+ annotations: read,
44
+ }, ({ query, workspace, limit }) => run(async () => json(await searchDocs(ctx, workspace, query, limit ?? 10))));
45
+ server.registerTool('read_doc', {
46
+ description: 'A doc as Markdown, with its id and link',
47
+ inputSchema: { doc: docArg, workspace: workspaceArg },
48
+ annotations: read,
49
+ }, ({ doc, workspace }) => run(async () => {
50
+ const result = await readDoc(ctx, workspace, doc);
51
+ return text(`# ${result.title}\n<!-- doc ${result.id} ${result.url} -->\n\n${result.markdown}`);
52
+ }));
53
+ server.registerTool('list_boards', {
54
+ description: 'Kanban boards (database blocks) in one doc or in the whole workspace, with their lanes',
55
+ inputSchema: { doc: docArg.optional(), workspace: workspaceArg },
56
+ annotations: read,
57
+ }, ({ doc, workspace }) => run(async () => json(await listBoards(ctx, workspace, doc))));
58
+ server.registerTool('read_board', {
59
+ description: 'All cards of a board with their fields, plus the fields and lane options',
60
+ inputSchema: { doc: docArg, board: boardArg, workspace: workspaceArg },
61
+ annotations: read,
62
+ }, (args) => run(async () => text(boardText((await getBoard(ctx, target(args))).board))));
63
+ if (options.readOnly) {
64
+ return server;
65
+ }
66
+ server.registerTool('create_doc', {
67
+ description: 'New doc from Markdown, optionally inside a folder',
68
+ inputSchema: {
69
+ title: z.string().min(1),
70
+ markdown: z.string().optional().describe('Body as Markdown, without the title'),
71
+ folder: z.string().optional().describe('Folder id or name'),
72
+ workspace: workspaceArg,
73
+ },
74
+ annotations: write,
75
+ }, ({ title, markdown, folder, workspace }) => run(async () => json(await createDoc(ctx, workspace, title, markdown ?? '', folder))));
76
+ server.registerTool('write_doc', {
77
+ description: 'Write Markdown into a doc. mode "append" adds at the end, "replace" rewrites the body (keep the markers from read_doc to keep boards and images)',
78
+ inputSchema: {
79
+ doc: docArg,
80
+ markdown: z.string(),
81
+ mode: z.enum(['append', 'replace']),
82
+ title: z.string().optional().describe('New title, leave out to keep it'),
83
+ workspace: workspaceArg,
84
+ },
85
+ annotations: destructive,
86
+ }, ({ doc, markdown, mode, title, workspace }) => run(async () => json(await writeDoc(ctx, workspace, doc, markdown, mode, title))));
87
+ server.registerTool('trash_doc', {
88
+ description: 'Move a doc to the AFFiNE trash, or restore it with restore=true. Nothing is deleted for good',
89
+ inputSchema: { doc: docArg, restore: z.boolean().optional(), workspace: workspaceArg },
90
+ annotations: destructive,
91
+ }, ({ doc, restore, workspace }) => run(async () => json(await trashDoc(ctx, workspace, doc, restore === true))));
92
+ server.registerTool('create_folder', {
93
+ description: 'New sidebar folder, at the top or inside another folder',
94
+ inputSchema: { name: z.string().min(1), parent: z.string().optional().describe('Parent folder id or name'), workspace: workspaceArg },
95
+ annotations: write,
96
+ }, ({ name, parent, workspace }) => run(async () => json(await createFolder(ctx, workspace, name, parent))));
97
+ server.registerTool('move_doc', {
98
+ description: 'Put a doc into a folder (moves it out of its current folder)',
99
+ inputSchema: { doc: docArg, folder: z.string().describe('Folder id or name'), workspace: workspaceArg },
100
+ annotations: write,
101
+ }, ({ doc, folder, workspace }) => run(async () => json(await moveDoc(ctx, workspace, doc, folder))));
102
+ server.registerTool('add_card', {
103
+ description: 'Add a card to a board, with optional fields such as Status or Author',
104
+ inputSchema: { doc: docArg, board: boardArg, title: z.string().min(1), fields: fieldsArg, workspace: workspaceArg },
105
+ annotations: write,
106
+ }, (args) => run(async () => {
107
+ const result = await addBoardCard(ctx, target(args), args.title, args.fields ?? {});
108
+ return text(`Added card ${result.cardId}\n\n${boardText(result.board)}`);
109
+ }));
110
+ server.registerTool('update_card', {
111
+ description: 'Change a card title and/or fields',
112
+ inputSchema: {
113
+ doc: docArg,
114
+ board: boardArg,
115
+ card: z.string().describe('Card id or title'),
116
+ title: z.string().optional(),
117
+ fields: fieldsArg,
118
+ workspace: workspaceArg,
119
+ },
120
+ annotations: write,
121
+ }, (args) => run(async () => {
122
+ const result = await updateBoardCard(ctx, target(args), args.card, args.title, args.fields ?? {});
123
+ return text(`Updated card ${result.cardId}\n\n${boardText(result.board)}`);
124
+ }));
125
+ server.registerTool('move_card', {
126
+ description: 'Move a card to another Kanban lane (sets the lane field, usually Status)',
127
+ inputSchema: {
128
+ doc: docArg,
129
+ board: boardArg,
130
+ card: z.string().describe('Card id or title'),
131
+ lane: z.string().describe('Lane name, for example "In Progress"'),
132
+ workspace: workspaceArg,
133
+ },
134
+ annotations: write,
135
+ }, (args) => run(async () => {
136
+ const result = await moveBoardCard(ctx, target(args), args.card, args.lane);
137
+ return text(`Moved card ${result.cardId} to ${result.laneField} = ${args.lane}\n\n${boardText(result.board)}`);
138
+ }));
139
+ server.registerTool('delete_card', {
140
+ description: 'Delete a card from a board',
141
+ inputSchema: { doc: docArg, board: boardArg, card: z.string().describe('Card id or title'), workspace: workspaceArg },
142
+ annotations: destructive,
143
+ }, (args) => run(async () => json(await deleteBoardCard(ctx, target(args), args.card))));
144
+ return server;
145
+ }
146
+ function target(args) {
147
+ const out = { doc: args.doc };
148
+ if (args.board !== undefined) {
149
+ out.board = args.board;
150
+ }
151
+ if (args.workspace !== undefined) {
152
+ out.workspace = args.workspace;
153
+ }
154
+ return out;
155
+ }
156
+ // Cards grouped by lane, easier for an agent to read than the raw table
157
+ export function boardText(board) {
158
+ const fields = board.columns.filter((column) => column.type !== 'title');
159
+ const lines = [
160
+ `Board "${board.title}" (${board.blockId}) in doc ${board.docId}`,
161
+ `Fields: ${fields.map((column) => column.options
162
+ ? `${column.name} [${column.options.map((option) => option.value).join(' | ')}]`
163
+ : `${column.name} (${column.type})`).join(', ') || 'none'}`,
164
+ ];
165
+ const cardLine = (card) => {
166
+ const values = fields
167
+ .filter((column) => column.name !== board.laneField && formatValue(card.fields[column.name]) !== '')
168
+ .map((column) => `${column.name}: ${formatValue(card.fields[column.name])}`);
169
+ return ` - ${card.title} [${card.id}]${values.length > 0 ? ` (${values.join(', ')})` : ''}`;
170
+ };
171
+ if (board.laneField === undefined) {
172
+ lines.push('Cards:', ...board.cards.map(cardLine));
173
+ return lines.join('\n');
174
+ }
175
+ const laneColumn = board.columns.find((column) => column.name === board.laneField);
176
+ const lanes = [...(laneColumn?.options?.map((option) => option.value) ?? [])];
177
+ for (const lane of lanes) {
178
+ const cards = board.cards.filter((card) => card.fields[board.laneField] === lane);
179
+ lines.push(`${lane} (${cards.length}):`, ...cards.map(cardLine));
180
+ }
181
+ const loose = board.cards.filter((card) => !lanes.includes(String(card.fields[board.laneField] ?? '')));
182
+ if (loose.length > 0) {
183
+ lines.push(`No ${board.laneField} (${loose.length}):`, ...loose.map(cardLine));
184
+ }
185
+ return lines.join('\n');
186
+ }
187
+ async function run(work) {
188
+ try {
189
+ return await work();
190
+ }
191
+ catch (error) {
192
+ if (error instanceof AffineToolError) {
193
+ const hint = error.hint ? `\nHint: ${error.hint}` : '';
194
+ return { isError: true, content: [{ type: 'text', text: `${error.errorCode}: ${error.message}${hint}` }] };
195
+ }
196
+ return { isError: true, content: [{ type: 'text', text: `error: ${error instanceof Error ? error.message : String(error)}` }] };
197
+ }
198
+ }
199
+ function text(value) {
200
+ return { content: [{ type: 'text', text: value }] };
201
+ }
202
+ function json(value) {
203
+ return text(JSON.stringify(value, null, 2));
204
+ }
@@ -0,0 +1,59 @@
1
+ import { AffineToolError } from "../types/result.types.js";
2
+ export async function listWorkspaces(ctx) {
3
+ const answer = await ctx.http.graphql('{ workspaces { id role } }');
4
+ const out = [];
5
+ for (const workspace of answer.workspaces) {
6
+ out.push({ id: workspace.id, name: await ctx.store.workspaceName(workspace.id), role: workspace.role });
7
+ }
8
+ return out;
9
+ }
10
+ /*
11
+ * Workspace by id or name. Without one the default from the config is used, and when there
12
+ * is no default but the bot is in only one workspace, that one
13
+ */
14
+ export async function resolveWorkspace(ctx, ref) {
15
+ if (ref === undefined || ref.trim() === '') {
16
+ if (ctx.defaultWorkspaceId !== undefined) {
17
+ return ctx.defaultWorkspaceId;
18
+ }
19
+ const all = await listWorkspaces(ctx);
20
+ if (all.length === 1) {
21
+ return all[0].id;
22
+ }
23
+ throw new AffineToolError('workspace_required', 'Name a workspace, there is no default', `Workspaces: ${all.map((workspace) => `${workspace.name} (${workspace.id})`).join(', ')}`);
24
+ }
25
+ if (/^[0-9a-f-]{36}$/i.test(ref)) {
26
+ return ref;
27
+ }
28
+ const all = await listWorkspaces(ctx);
29
+ const found = all.find((workspace) => workspace.name.toLowerCase() === ref.trim().toLowerCase());
30
+ if (found === undefined) {
31
+ throw new AffineToolError('workspace_not_found', `No workspace "${ref}"`, `Workspaces: ${all.map((workspace) => workspace.name).join(', ')}`);
32
+ }
33
+ return found.id;
34
+ }
35
+ /*
36
+ * Doc by id, exact title (any case) or a title part that matches one doc only.
37
+ * Trashed docs are only found by id
38
+ */
39
+ export async function resolveDoc(ctx, workspaceId, ref) {
40
+ const docs = await ctx.store.listDocs(workspaceId);
41
+ const byId = docs.find((doc) => doc.id === ref);
42
+ if (byId !== undefined) {
43
+ return byId;
44
+ }
45
+ const wanted = ref.trim().toLowerCase();
46
+ const live = docs.filter((doc) => !doc.trash);
47
+ const exact = live.filter((doc) => doc.title.trim().toLowerCase() === wanted);
48
+ const candidates = exact.length > 0 ? exact : live.filter((doc) => doc.title.toLowerCase().includes(wanted));
49
+ if (candidates.length === 1) {
50
+ return candidates[0];
51
+ }
52
+ if (candidates.length === 0) {
53
+ throw new AffineToolError('doc_not_found', `No doc "${ref}"`, 'Use tree or search to find the doc id');
54
+ }
55
+ throw new AffineToolError('doc_ambiguous', `"${ref}" matches ${candidates.length} docs`, `Use one of the ids: ${candidates.map((doc) => `${doc.title || '(untitled)'} = ${doc.id}`).join(', ')}`);
56
+ }
57
+ export function docUrl(ctx, workspaceId, docId) {
58
+ return `${ctx.http.baseUrl}/workspace/${workspaceId}/${docId}`;
59
+ }
@@ -0,0 +1,116 @@
1
+ import { boardLanes, boardToMarkdown } from "../domain/board/board-render.js";
2
+ import { addCard, boardBlockIds, deleteCard, laneFieldOf, readBoard, updateCard } from "../infrastructure/affine/board-doc.js";
3
+ import { AffineToolError } from "../types/result.types.js";
4
+ import { resolveDoc, resolveWorkspace } from "./affine-context.js";
5
+ const BOARD_SCAN_LIMIT = 300;
6
+ export async function listBoards(ctx, workspaceRef, docRef) {
7
+ const workspaceId = await resolveWorkspace(ctx, workspaceRef);
8
+ const docs = docRef === undefined
9
+ ? (await ctx.store.listDocs(workspaceId)).filter((doc) => !doc.trash).slice(0, BOARD_SCAN_LIMIT)
10
+ : [await resolveDoc(ctx, workspaceId, docRef)];
11
+ const out = [];
12
+ for (const meta of docs) {
13
+ out.push(...await boardsInDoc(ctx, workspaceId, meta));
14
+ }
15
+ return out;
16
+ }
17
+ async function boardsInDoc(ctx, workspaceId, meta) {
18
+ const doc = await ctx.sync.loadDoc(workspaceId, meta.id);
19
+ if (doc === null) {
20
+ return [];
21
+ }
22
+ try {
23
+ return boardBlockIds(doc).map((blockId) => {
24
+ const board = readBoard(doc, meta.id, blockId);
25
+ return {
26
+ docId: meta.id,
27
+ docTitle: meta.title,
28
+ blockId,
29
+ title: board.title,
30
+ cards: board.cards.length,
31
+ laneField: board.laneField,
32
+ lanes: boardLanes(board),
33
+ };
34
+ });
35
+ }
36
+ finally {
37
+ doc.destroy();
38
+ }
39
+ }
40
+ async function resolveBoard(ctx, target) {
41
+ const workspaceId = await resolveWorkspace(ctx, target.workspace);
42
+ const meta = await resolveDoc(ctx, workspaceId, target.doc);
43
+ const boards = await boardsInDoc(ctx, workspaceId, meta);
44
+ const wanted = target.board?.trim().toLowerCase();
45
+ const matches = wanted === undefined
46
+ ? boards
47
+ : boards.filter((board) => board.blockId === target.board || board.title.trim().toLowerCase() === wanted);
48
+ if (matches.length === 1) {
49
+ return { workspaceId, docId: meta.id, blockId: matches[0].blockId };
50
+ }
51
+ if (boards.length === 0) {
52
+ throw new AffineToolError('board_not_found', `Doc "${meta.title}" has no board`, 'Use list_boards to find boards');
53
+ }
54
+ throw new AffineToolError(matches.length === 0 ? 'board_not_found' : 'board_ambiguous', matches.length === 0 ? `No board "${target.board}" in "${meta.title}"` : `Doc "${meta.title}" has ${boards.length} boards, name one`, `Boards: ${boards.map((board) => `${board.title || '(untitled)'} = ${board.blockId}`).join(', ')}`);
55
+ }
56
+ export async function getBoard(ctx, target) {
57
+ const resolved = await resolveBoard(ctx, target);
58
+ const doc = await ctx.sync.loadDoc(resolved.workspaceId, resolved.docId);
59
+ if (doc === null) {
60
+ throw new AffineToolError('doc_not_found', `Doc ${resolved.docId} has no content`);
61
+ }
62
+ try {
63
+ const board = readBoard(doc, resolved.docId, resolved.blockId);
64
+ return { board, markdown: boardToMarkdown(board) };
65
+ }
66
+ finally {
67
+ doc.destroy();
68
+ }
69
+ }
70
+ export async function addBoardCard(ctx, target, title, fields) {
71
+ const resolved = await resolveBoard(ctx, target);
72
+ const { result: cardId } = await ctx.sync.change(resolved.workspaceId, resolved.docId, (doc) => addCard(doc, resolved.blockId, title, fields));
73
+ await ctx.store.touchDoc(resolved.workspaceId, resolved.docId, {});
74
+ return { cardId, board: (await getBoard(ctx, target)).board };
75
+ }
76
+ export async function updateBoardCard(ctx, target, cardRef, title, fields) {
77
+ const resolved = await resolveBoard(ctx, target);
78
+ const cardId = await resolveCard(ctx, target, cardRef);
79
+ await ctx.sync.change(resolved.workspaceId, resolved.docId, (doc) => updateCard(doc, resolved.blockId, cardId, title, fields));
80
+ await ctx.store.touchDoc(resolved.workspaceId, resolved.docId, {});
81
+ return { cardId, board: (await getBoard(ctx, target)).board };
82
+ }
83
+ // Moving a card on a Kanban is setting its lane field, Status on most boards
84
+ export async function moveBoardCard(ctx, target, cardRef, lane) {
85
+ const resolved = await resolveBoard(ctx, target);
86
+ const doc = await ctx.sync.loadDoc(resolved.workspaceId, resolved.docId);
87
+ const laneField = doc === null ? undefined : laneFieldOf(doc, resolved.blockId);
88
+ doc?.destroy();
89
+ if (laneField === undefined) {
90
+ throw new AffineToolError('no_lanes', 'This board has no Kanban view grouped by a field', 'Use update_card and set the field by name instead');
91
+ }
92
+ const { cardId, board } = await updateBoardCard(ctx, target, cardRef, undefined, { [laneField]: lane });
93
+ return { cardId, laneField, board };
94
+ }
95
+ export async function deleteBoardCard(ctx, target, cardRef) {
96
+ const resolved = await resolveBoard(ctx, target);
97
+ const cardId = await resolveCard(ctx, target, cardRef);
98
+ await ctx.sync.change(resolved.workspaceId, resolved.docId, (doc) => deleteCard(doc, resolved.blockId, cardId));
99
+ await ctx.store.touchDoc(resolved.workspaceId, resolved.docId, {});
100
+ return { cardId };
101
+ }
102
+ // Card by id, exact title or a title part that fits one card only
103
+ async function resolveCard(ctx, target, ref) {
104
+ const { board } = await getBoard(ctx, target);
105
+ const byId = board.cards.find((card) => card.id === ref);
106
+ if (byId !== undefined) {
107
+ return byId.id;
108
+ }
109
+ const wanted = ref.trim().toLowerCase();
110
+ const exact = board.cards.filter((card) => card.title.trim().toLowerCase() === wanted);
111
+ const matches = exact.length > 0 ? exact : board.cards.filter((card) => card.title.toLowerCase().includes(wanted));
112
+ if (matches.length === 1) {
113
+ return matches[0].id;
114
+ }
115
+ throw new AffineToolError(matches.length === 0 ? 'card_not_found' : 'card_ambiguous', matches.length === 0 ? `No card "${ref}" on "${board.title}"` : `"${ref}" matches ${matches.length} cards`, `Cards: ${(matches.length === 0 ? board.cards : matches).map((card) => `${card.title} = ${card.id}`).join('; ')}`);
116
+ }