-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
1739 lines (1510 loc) · 67.5 KB
/
Copy pathserver.py
File metadata and controls
1739 lines (1510 loc) · 67.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""AppFlowy MCP Server.
An MCP server over the AppFlowy Cloud REST API. Exposes workspace/folder/database
reads plus row create + upsert so an AI agent can both see and *finish* work
(e.g. move a Board card by upserting its Status cell).
Transports:
* stdio — run this file directly (local use).
* Streamable HTTP — mounted at /mcp (current MCP standard).
* SSE — mounted at /sse (legacy; kept for existing clients).
Security model (see README/SECURITY):
* AppFlowy Cloud has no scoped API keys — auth is full-account GoTrue login.
Use a DEDICATED bot account invited to only the workspace(s) you expose.
* ALLOWED_WORKSPACE_IDS pins the server to specific workspace(s); every tool
refuses any other id (defence-in-depth on top of account isolation).
* MCP_SECRET_TOKEN gates every HTTP request. Send it as an `Authorization:
Bearer` header (preferred), OR as a `?token=` URL query param ("link method"
— for UIs like Claude's connector dialog that can't set a header). With the
link method the token rides in the URL and can appear in logs, so treat the
whole link like a password.
"""
import base64
import hmac
import json
import os
import secrets
import string
import time
import uuid
from contextlib import asynccontextmanager
from pathlib import Path
import httpx
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, PlainTextResponse, Response
from markdown_it import MarkdownIt
from markdown_it.tree import SyntaxTreeNode
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from mdit_py_plugins.dollarmath import dollarmath_plugin
from pycrdt import Array, Doc, Map, Text
# Load environment variables
env_path = Path(__file__).parent / ".env"
load_dotenv(env_path)
BASE_URL = os.environ.get("APPFLOWY_BASE_URL", "https://beta.appflowy.cloud").rstrip(
"/"
)
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
# Sent to MCP clients as server instructions — teaches the agent AppFlowy's model,
# the tool set, the block schema, and the limits so it builds clean structures.
APPFLOWY_INSTRUCTIONS = """\
AppFlowy MCP — you can READ and BUILD in this AppFlowy workspace.
MODEL: workspace → Spaces → pages. A page is a Document, or a Database shown as a
Grid/Board/Calendar/List/Gallery. A Board's columns are a SingleSelect field;
cards are rows. IMPORTANT: a view_id (from get_workspace_folder) is NOT a
database_id — call list_databases to map a view to its database_id before using
row/field tools.
CREATE (clean JSON — the user should never have to set anything up by hand):
create_page, append_blocks, create_database (grid/board/calendar),
create_database_view, add_database_field, create_database_row,
upsert_database_row, create_space, move_page, duplicate_page, trash_page.
EDIT/DELETE ANY ROW (Tier 2 / collab — works even on UI-created rows):
update_row_cells (change cells on any existing row — e.g. move a Board card by
setting its Status cell to the target option id), delete_row (hard-delete a row).
EDIT SCHEMA: update_database_field (rename a column) and delete_database_field
(drop it) — Tier 2/collab, no REST. add_select_option (returns the new option id —
use THAT as the cell value) and delete_select_option manage SingleSelect/MultiSelect
options. set_group_by(view_id, field_id) sets which field a Board groups its columns
by. rename_page renames a page/database/space; restore_page un-trashes a page.
CONTENT IS MARKDOWN EVERYWHERE. create_page(markdown=...), append_blocks(markdown=...),
and a row/card `document` all take standard Markdown, rendered into real blocks:
#/##/### headings, "- "/"1. " lists (nestable), "- [ ]" checkboxes, "> " quote,
```lang fenced code, "---" divider, images, links, GFM callouts (> [!NOTE]/[!TIP]/
[!WARNING]…), $$ math blocks, and inline **bold**/*italic*/~~strike~~/`code`. Prefer
markdown for any prose or card body. READ any page or card
body back AS Markdown with get_page_markdown(page_id) — the inverse (page view id or row id).
MENTION a page inline with [](mention:<view_id>) — renders as a live link to that page.
For blocks Markdown can't express, pass a page_data JSON block tree instead, e.g.
{"type":"page","children":[
{"type":"heading","data":{"level":1,"delta":[{"insert":"Title"}]}},
{"type":"todo_list","data":{"delta":[{"insert":"task"}],"checked":false}},
{"type":"divider"}]}
Block types: paragraph, heading(data.level 1-6), bulleted_list, numbered_list,
todo_list(data.checked), quote, code(data.language), divider, image(data.url).
Delta attrs: bold, italic, underline, strikethrough, code, color, href.
FIELD TYPES (add_database_field): 0=RichText 1=Number 2=DateTime 3=SingleSelect
4=MultiSelect 5=Checkbox 6=URL 7=Checklist 8=LastEditedTime 9=CreatedTime.
EDIT DOCUMENT BLOCKS (Tier 2 / collab): add_block (any type incl. ADVANCED —
callout, toggle_list, quote, code, heading; pass block-specific `data`),
edit_block_text (both render inline **Markdown**: bold/italic/code/strike/links),
replace_text (find-and-replace by content — NO block id needed), delete_block. page_id may be a document view id OR a database ROW
id — a row id auto-resolves to the card's BODY document, so this is how you add a
checkbox/sub-task to a Board card. Put per-card checklists in the card BODY, never
in a shared column (a column value shows on every card).
BEST PRACTICE: To update a row in place instead of creating a duplicate, upsert with a
stable pre_hash and reuse that pre_hash on later calls. Keep cells for title/status/
metadata and put long content or checklists in a row's BODY document, never in a shared
column (a column value shows on every row).
AVOID: (1) Trusting an immediate re-read — get_database_row_details reads /row/detail,
a materialized view that LAGS the live data by up to minutes; a write can be correct even
when the re-read still shows the old value, so don't conclude it failed. (2) Guessing a
database_id from a folder view_id (use list_databases). (3) Full-overwriting a document —
the edit tools send merging updates; never PUT a whole collab.
LIMITS: in-place edits render inline Markdown (bold/italic/code/strike/links) but not
text color or underline. NOT SUPPORTED YET (roadmap — see KNOWLEDGE.md §9 Coverage):
columns, toggle headings, table of contents, @mentions, link-to-page, web-bookmark,
Drive/iframe embed, file/video/audio upload, List/Gallery/Chart/Feed views, and inline
or linked database views. AI blocks (AI note/summarize/ask) run AppFlowy's own AI and
aren't insertable content. Full guide + coverage matrix: MCP resource appflowy://guide
(also KNOWLEDGE.md in the repo).
"""
# Server logo (three kanban columns on AppFlowy purple). Declared in the MCP
# initialize response and served at /icon.svg. NOTE: Claude.ai currently shows a
# generic globe for all custom connectors regardless — this is for spec
# compliance, other clients, and future support.
ICON_SVG = (
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">'
'<rect width="128" height="128" rx="28" fill="#A34AFD"/>'
'<rect x="30" y="34" width="18" height="60" rx="6" fill="#fff"/>'
'<rect x="55" y="34" width="18" height="42" rx="6" fill="#fff" fill-opacity="0.9"/>'
'<rect x="80" y="34" width="18" height="30" rx="6" fill="#fff" fill-opacity="0.8"/>'
"</svg>"
)
ICON_DATA_URI = (
"data:image/svg+xml;base64," + base64.b64encode(ICON_SVG.encode()).decode()
)
def _csv_env(name: str) -> list[str]:
return [v.strip() for v in os.environ.get(name, "").split(",") if v.strip()]
# DNS-rebinding protection guards against browser-driven attacks on the HTTP
# transports. Enabled by default; set MCP_ALLOWED_HOSTS to your public host
# (e.g. mcp.example.com) when behind a reverse proxy, or MCP_DNS_REBINDING_
# PROTECTION=false as an escape hatch if a proxy setup misreports Host.
_dns_protect = os.environ.get("MCP_DNS_REBINDING_PROTECTION", "true").lower() != "false"
_transport_security = TransportSecuritySettings(
enable_dns_rebinding_protection=_dns_protect,
allowed_hosts=_csv_env("MCP_ALLOWED_HOSTS")
or ["localhost", "127.0.0.1", "localhost:8000", "127.0.0.1:8000"],
allowed_origins=_csv_env("MCP_ALLOWED_ORIGINS")
or ["http://localhost", "http://127.0.0.1"],
)
# streamable_http_path="/" so mounting the app at /mcp yields a clean /mcp/
# endpoint (not the doubled /mcp/mcp you'd get with the default path).
mcp = FastMCP(
"appflowy-mcp",
instructions=APPFLOWY_INSTRUCTIONS,
icons=[{"src": ICON_DATA_URI, "mimeType": "image/svg+xml", "sizes": ["any"]}],
website_url="https://github.com/Rahulk644/appflowy-mcp-server",
transport_security=_transport_security,
streamable_http_path="/",
)
# Full operator guide (KNOWLEDGE.md) exposed as an MCP resource, so an agent can pull
# the deep reference — tools-by-task, recipes, pitfalls, coverage matrix, data model —
# on demand instead of it bloating every tool description (keeps the tool surface lean).
def _agent_guide_md() -> str:
return (Path(__file__).parent / "KNOWLEDGE.md").read_text(encoding="utf-8")
@mcp.resource(
"appflowy://guide",
name="AppFlowy Agent Guide",
description="Operator guide: tools-by-task, recipes, pitfalls, coverage matrix, data model.",
mime_type="text/markdown",
)
def agent_guide() -> str:
return _agent_guide_md()
# Tool behavior hints for MCP clients (advisory — they help an agent choose safe
# operations; they are NOT a security boundary). readOnly = performs no writes;
# destructive = makes an irreversible change; idempotent = repeating with the same
# args reaches the same state; openWorld = calls the external AppFlowy service (always
# true here). Presets are applied per tool via @mcp.tool(annotations=...).
_READ = {
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": True,
}
_CREATE = {
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": False,
"openWorldHint": True,
}
_WRITE = {
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": True,
}
_DESTRUCTIVE = {
"readOnlyHint": False,
"destructiveHint": True,
"idempotentHint": True,
"openWorldHint": True,
}
# ---- Optional OAuth (Google-federated) — active only if GOOGLE_CLIENT_ID set --
OAUTH_ISSUER = os.environ.get("OAUTH_ISSUER", "").rstrip("/")
_oauth_provider = None
if os.environ.get("GOOGLE_CLIENT_ID") and OAUTH_ISSUER:
from google_oauth import GoogleOAuthProvider
_oauth_provider = GoogleOAuthProvider(
issuer=OAUTH_ISSUER,
google_client_id=os.environ["GOOGLE_CLIENT_ID"],
google_client_secret=os.environ.get("GOOGLE_CLIENT_SECRET", ""),
allowed_emails=_csv_env("ALLOWED_EMAILS"),
store_path=os.environ.get("OAUTH_STORE_PATH") or None,
)
# Token management
_access_token = None
_refresh_token = None
_token_expires_at = 0
def _allowed_workspaces() -> set[str] | None:
"""Workspace ids this server may touch, or None if unrestricted."""
ids = _csv_env("ALLOWED_WORKSPACE_IDS")
return set(ids) if ids else None
def _require_workspace(workspace_id: str) -> None:
allowed = _allowed_workspaces()
if allowed is not None and workspace_id not in allowed:
raise ValueError(
f"Workspace '{workspace_id}' is not permitted by this server's "
"ALLOWED_WORKSPACE_IDS policy."
)
def _login() -> None:
global _access_token, _refresh_token, _token_expires_at
email = os.environ.get("APPFLOWY_EMAIL")
password = os.environ.get("APPFLOWY_PASSWORD")
if not email or not password:
raise ValueError("APPFLOWY_EMAIL and APPFLOWY_PASSWORD must be set.")
url = f"{BASE_URL}/gotrue/token?grant_type=password"
data = {"email": email, "password": password}
with httpx.Client() as client:
res = client.post(url, json=data, headers={"User-Agent": USER_AGENT})
res.raise_for_status()
body = res.json()
_access_token = body.get("access_token")
_refresh_token = body.get("refresh_token")
expires_in = body.get("expires_in", 3600)
_token_expires_at = time.time() + expires_in - 60 # 60s buffer
def _refresh() -> None:
global _access_token, _refresh_token, _token_expires_at
if not _refresh_token:
_login()
return
url = f"{BASE_URL}/gotrue/token?grant_type=refresh_token"
data = {"refresh_token": _refresh_token}
with httpx.Client() as client:
res = client.post(url, json=data, headers={"User-Agent": USER_AGENT})
if res.status_code != 200:
_login() # refresh token expired -> re-login
return
body = res.json()
_access_token = body.get("access_token")
if body.get("refresh_token"):
_refresh_token = body.get("refresh_token")
expires_in = body.get("expires_in", 3600)
_token_expires_at = time.time() + expires_in - 60
def get_auth_headers() -> dict:
if not _access_token or time.time() >= _token_expires_at:
try:
_refresh() if _refresh_token else _login()
except Exception:
_login()
return {
"Authorization": f"Bearer {_access_token}",
"User-Agent": USER_AGENT,
"Content-Type": "application/json",
}
# Status-code → what the agent should do about it. Surfaced in tool errors so a
# failed call is self-explanatory instead of a bare stack trace.
_ERROR_HINTS = {
400: "check the ids and the JSON payload shape",
401: "the server's AppFlowy login is invalid or expired",
403: "the account lacks access to this workspace or resource",
404: "verify the id exists — a folder view_id is NOT a database_id (call list_databases)",
409: "the resource already exists or was modified concurrently",
413: "the payload is too large — split it into smaller writes",
429: "rate limited — wait briefly and retry",
}
def _api_call(method: str, path: str, **kwargs) -> httpx.Response:
"""Authenticated AppFlowy API call with actionable errors. `path` is joined to
BASE_URL. Raises RuntimeError with a specific, agent-readable message on failure so a
tool error tells the agent how to fix its call rather than dumping a raw traceback."""
try:
with httpx.Client(timeout=30.0) as client:
res = client.request(
method, f"{BASE_URL}{path}", headers=get_auth_headers(), **kwargs
)
res.raise_for_status()
return res
except httpx.HTTPStatusError as e:
code = e.response.status_code
hint = _ERROR_HINTS.get(code, "unexpected AppFlowy API error")
body = " ".join(e.response.text[:200].split())
raise RuntimeError(f"AppFlowy API {code}: {hint}. Server said: {body}") from e
except httpx.RequestError as e:
raise RuntimeError(
f"AppFlowy API request did not complete ({type(e).__name__}) — retry shortly"
) from e
def _post(path: str, body: dict):
"""POST JSON to the AppFlowy API; return the response's `data` field."""
return _api_call("POST", path, json=body).json().get("data", "")
# ---- Collab / CRDT layer (Tier 2): edit/delete any block or row --------------
# The REST API is create/append-only. For surgical edits we fetch the object's
# yrs collab, mutate it with pycrdt, and POST the *diff* to the merging web-update
# endpoint (never the full-overwrite PUT, which clobbers concurrent edits).
# collab_type: 0=Document, 1=Database, 5=DatabaseRow.
def _collab_doc(workspace_id: str, object_id: str, collab_type: int) -> Doc:
"""Fetch a collab object and load it into a pycrdt Doc."""
res = _api_call(
"GET",
f"/api/workspace/v1/{workspace_id}/collab/{object_id}",
params={"collab_type": collab_type},
)
doc = Doc()
doc.apply_update(bytes(res.json()["data"]["doc_state"]))
return doc
def _collab_web_update(
workspace_id: str, object_id: str, doc: Doc, state_vector: bytes, collab_type: int
) -> None:
"""POST the yrs update diff (changes since state_vector) — the server merges it."""
update = doc.get_update(state_vector)
_api_call(
"POST",
f"/api/workspace/v1/{workspace_id}/collab/{object_id}/web-update",
json={"doc_state": list(update), "collab_type": collab_type},
)
def _nid(n: int = 10) -> str:
"""AppFlowy-style short id for new blocks/text-map keys."""
return "".join(
secrets.choice(string.ascii_letters + string.digits) for _ in range(n)
)
def _row_document_id(row_id: str) -> str:
"""A database row's body document (the card page below the row) is a separate
collab; AppFlowy derives its object id as uuid5(row_uuid, "document_id")."""
return str(uuid.uuid5(uuid.UUID(row_id), "document_id"))
def _open_document(workspace_id: str, page_id: str):
"""Load a document collab for block editing. `page_id` may be the document's own
view id OR a database row id — a row id is transparently resolved to the row's
body document (so agents can edit a Board card's checklist by its row id).
Returns (doc, object_id, document_map); pass object_id back to _collab_web_update."""
doc = _collab_doc(workspace_id, page_id, 0)
root = doc.get("data", type=Map)
if "document" not in root:
page_id = _row_document_id(page_id)
doc = _collab_doc(workspace_id, page_id, 0)
root = doc.get("data", type=Map)
return doc, page_id, root["document"]
def _open_database(workspace_id: str, database_id: str):
"""Load a database collab (type 1); return (doc, root) where root is the DATABASE
map holding 'fields' (field_id -> field) and 'views' (view_id -> view)."""
doc = _collab_doc(workspace_id, database_id, 1)
return doc, doc.get("data", type=Map)["database"]
def _to_yjs(v):
"""Recursively wrap plain JSON into pycrdt shared types for collab insertion."""
if isinstance(v, dict):
return Map({k: _to_yjs(x) for k, x in v.items()})
if isinstance(v, list):
return Array([_to_yjs(x) for x in v])
return v
def _field_types(workspace_id: str, database_id: str) -> dict:
"""Map field_id -> numeric field type. Prefer the DB collab (authoritative, no
lag); a new cell must be tagged with the right type or the write appears to silently
drop. Fall back to the REST fields view (which lags for just-created fields) only if
the collab can't be read."""
try:
_, root = _open_database(workspace_id, database_id)
fields = root["fields"]
return {
fid: int(fields[fid]["ty"]) for fid in fields.keys() if "ty" in fields[fid]
}
except Exception:
return {
f["id"]: int(f.get("field_type_id", 0))
for f in get_database_fields(workspace_id, database_id)
}
# Select fields store their whole SelectTypeOption as a JSON STRING under
# type_option["<field_type>"]["content"] = {"options":[{id,name,color}], "disable_color"}.
# color must be one of these exact names — an invalid value makes AppFlowy's
# deserialize fail and silently drop every option, so we validate strictly.
_SELECT_TYPES = {3, 4} # 3=SingleSelect, 4=MultiSelect
SELECT_COLORS = [
"Purple",
"Pink",
"LightPink",
"Orange",
"Yellow",
"Lime",
"Green",
"Aqua",
"Blue",
"Cream",
"Mint",
"Sky",
"Lilac",
"Pearl",
"Sunset",
"Coral",
"Sapphire",
"Moss",
"Sand",
"Charcoal",
]
def _read_select(field):
"""Parse a select field's options. Returns (type_key, data) where data is
{"options":[{id,name,color}], "disable_color":bool}. Raises if not a select."""
ty = int(field["ty"]) if "ty" in field else -1
if ty not in _SELECT_TYPES:
raise ValueError("field is not a SingleSelect/MultiSelect column")
tk = str(ty)
content = ""
to = field["type_option"] if "type_option" in field else None
if to is not None and tk in to and "content" in to[tk]:
content = to[tk]["content"]
data = json.loads(content) if content else {}
data.setdefault("options", [])
data.setdefault("disable_color", False)
return tk, data
def _write_select(field, tk, data):
"""Serialize the options dict back into type_option[tk]["content"] (a JSON string)."""
if "type_option" not in field:
field["type_option"] = Map()
to = field["type_option"]
if tk not in to:
to[tk] = Map()
to[tk]["content"] = json.dumps(data, separators=(",", ":"))
@mcp.tool(annotations=_READ)
def get_workspaces() -> list:
"""Retrieves your AppFlowy workspaces (filtered to ALLOWED_WORKSPACE_IDS if set)."""
data = _api_call("GET", "/api/workspace").json().get("data", [])
allowed = _allowed_workspaces()
if allowed is not None:
data = [w for w in data if (w.get("workspace_id") or w.get("id")) in allowed]
return data
@mcp.tool(annotations=_READ)
def get_workspace_folder(workspace_id: str, depth: int = 1) -> dict:
"""
Fetches the folder structure (pages and databases) of a workspace.
Useful for finding the database_id to query.
"""
_require_workspace(workspace_id)
path = f"/api/workspace/{workspace_id}/folder"
return _api_call("GET", path, params={"depth": depth}).json().get("data", {})
@mcp.tool(annotations=_READ)
def get_database_fields(workspace_id: str, database_id: str) -> list:
"""Retrieves the fields/columns available in a database."""
_require_workspace(workspace_id)
path = f"/api/workspace/{workspace_id}/database/{database_id}/fields"
return _api_call("GET", path).json().get("data", [])
@mcp.tool(annotations=_READ)
def get_database_row_ids(workspace_id: str, database_id: str) -> list:
"""Retrieves the row IDs in a database."""
_require_workspace(workspace_id)
path = f"/api/workspace/{workspace_id}/database/{database_id}/row"
return _api_call("GET", path).json().get("data", [])
@mcp.tool(annotations=_READ)
def get_database_row_details(
workspace_id: str, database_id: str, row_ids: str, with_doc: bool = False
) -> list:
"""
Retrieves detailed content for specific database rows.
row_ids: comma-separated row UUIDs (e.g. 'uuid1,uuid2').
"""
_require_workspace(workspace_id)
path = f"/api/workspace/{workspace_id}/database/{database_id}/row/detail"
params = {"ids": row_ids}
if with_doc:
params["with_doc"] = "true"
return _api_call("GET", path, params=params).json().get("data", [])
@mcp.tool(annotations=_CREATE)
def create_database_row(workspace_id: str, database_id: str, row_data: str) -> str:
"""
Creates a new row in a database.
row_data: JSON string with keys `cells` (field_id/field_name -> value) and
optional `document` (Markdown). Returns the new row id.
"""
_require_workspace(workspace_id)
try:
data = json.loads(row_data)
except json.JSONDecodeError as exc:
raise ValueError("row_data must be a valid JSON string") from exc
path = f"/api/workspace/{workspace_id}/database/{database_id}/row"
return _api_call("POST", path, json=data).json().get("data", "")
@mcp.tool(annotations=_WRITE)
def upsert_database_row(workspace_id: str, database_id: str, row_data: str) -> str:
"""
Creates or updates (upserts) a row — the idempotent way to write. Use it to
update a row in place (e.g. move a Board card by setting its Status cell) without
creating duplicates on re-runs.
row_data: JSON string with keys:
* pre_hash (str): identifies the row. Reuse an existing row's pre_hash to
UPDATE it (e.g. to set its Status cell and move it between columns);
a new pre_hash creates a new row.
* cells (obj): field_id or field_name -> value.
* document (str, optional): Markdown body.
Returns the created/updated row id.
"""
_require_workspace(workspace_id)
try:
data = json.loads(row_data)
except json.JSONDecodeError as exc:
raise ValueError("row_data must be a valid JSON string") from exc
path = f"/api/workspace/{workspace_id}/database/{database_id}/row"
return _api_call("PUT", path, json=data).json().get("data", "")
@mcp.tool(annotations=_READ)
def list_updated_rows(workspace_id: str, database_id: str, after: str = "") -> list:
"""
Lists rows updated in a database (change feed) — useful for syncing "what
changed" into a pipeline.
after: optional cursor/timestamp forwarded to AppFlowy's /row/updated.
"""
# ponytail: `after` semantics come straight from AppFlowy's /row/updated;
# confirm the exact cursor format against a live workspace before relying on it.
_require_workspace(workspace_id)
path = f"/api/workspace/{workspace_id}/database/{database_id}/row/updated"
params = {"after": after} if after else {}
return _api_call("GET", path, params=params).json().get("data", [])
# ---- Structure & document tools (create/manage pages, databases, blocks) ----
_DB_LAYOUTS = {"grid": 1, "board": 2, "calendar": 3}
@mcp.tool(annotations=_READ)
def list_databases(workspace_id: str) -> list:
"""Lists databases in the workspace with their id and views. Use this to map a
Board/Grid view to its database_id (a folder view_id is NOT the database_id)."""
_require_workspace(workspace_id)
path = f"/api/workspace/{workspace_id}/database"
return _api_call("GET", path).json().get("data", [])
# ---- Markdown → AppFlowy block tree ---------------------------------------
# AppFlowy Cloud converts Markdown → blocks server-side for ROW bodies, but the
# page-view create endpoint only accepts a structured block tree. So we do what
# Notion's MCP does: parse Markdown here (markdown-it, the reference CommonMark
# parser) and emit the block tree create_page / append_blocks feed to AppFlowy —
# one Markdown content interface everywhere. Covers the basic-block palette;
# unknown constructs fall back to a paragraph so text is never silently dropped.
# ponytail: MVP palette — callouts/toggles/columns and tables-as-blocks are
# roadmap (a GFM table degrades to its plaintext for now).
_md_parser = (
MarkdownIt("commonmark").enable(["table", "strikethrough"]).use(dollarmath_plugin)
)
# GFM alert types (> [!NOTE]) <-> AppFlowy callout icons, for round-tripping callouts.
_ALERT_ICONS = {
"note": "📝",
"tip": "💡",
"important": "❗",
"warning": "⚠️",
"caution": "🔥",
}
_ICON_ALERTS = {v: k for k, v in _ALERT_ICONS.items()}
_INLINE_ATTR = {"strong": "bold", "em": "italic", "s": "strikethrough"}
_TASK_PREFIXES = {"[ ] ": False, "[x] ": True, "[X] ": True}
def _delta_op(text: str, attrs: dict) -> dict:
op = {"insert": text}
if attrs:
op["attributes"] = dict(attrs)
return op
def _inline_delta(node) -> list:
"""A markdown-it 'inline' node -> AppFlowy delta (list of insert ops)."""
ops: list = []
def walk(children, attrs):
for c in children:
t = c.type
if t == "text":
if c.content:
ops.append(_delta_op(c.content, attrs))
elif t in ("softbreak", "hardbreak"):
ops.append(_delta_op("\n", attrs))
elif t == "code_inline":
ops.append(_delta_op(c.content, {**attrs, "code": True}))
elif t in _INLINE_ATTR:
walk(c.children, {**attrs, _INLINE_ATTR[t]: True})
elif t == "link":
href = c.attrs.get("href", "")
if href.startswith("mention:"): # [](mention:<page_id>) -> page mention
ops.append(
{
"insert": "$",
"attributes": {
"mention": {"type": "page", "page_id": href[8:]}
},
}
)
else:
walk(c.children, {**attrs, "href": href})
elif t == "image":
alt = c.content or c.attrs.get("alt", "")
if alt:
ops.append(_delta_op(alt, attrs))
elif t == "math_inline":
ops.append(_delta_op(f"${c.content}$", attrs))
elif c.children:
walk(c.children, attrs)
elif c.content:
ops.append(_delta_op(c.content, attrs))
walk(node.children, {})
return ops
def _first_inline(node):
for c in node.children:
if c.type == "inline":
return c
return None
def _delta_of(node) -> list:
inl = _first_inline(node)
return _inline_delta(inl) if inl else []
def _sole_image_url(para_node):
"""If a paragraph is a lone image, return its src (AppFlowy image is a block,
not inline); else None."""
inl = _first_inline(para_node)
if not inl:
return None
imgs = [c for c in inl.children if c.type == "image"]
other = [
c
for c in inl.children
if c.type not in ("image", "softbreak", "hardbreak")
and (c.content or c.children)
]
return imgs[0].attrs.get("src", "") if len(imgs) == 1 and not other else None
def _task_state(delta):
"""If the delta starts with a GFM task marker, return (checked, stripped_delta);
else None."""
if not delta or "attributes" in delta[0]:
return None
lead_ops, lead = 0, ""
for o in delta:
if "attributes" in o:
break
lead += o["insert"]
lead_ops += 1
for pref, checked in _TASK_PREFIXES.items():
if lead.startswith(pref):
remainder = lead[len(pref) :]
rest = delta[lead_ops:]
new = ([{"insert": remainder}] if remainder else []) + [
dict(o) for o in rest
]
return checked, (new or [{"insert": ""}])
return None
def _node_plaintext(node) -> str:
if node.type in ("fence", "code_block"):
return node.content.rstrip("\n")
if not node.children:
return node.content or ""
return "".join(_node_plaintext(c) for c in node.children)
def _drop_first_line(delta) -> list:
"""Remove the first text line (through the first newline) from a delta — strips the
"[!NOTE]" marker line off a GFM alert before the rest becomes the callout body."""
out, dropping = [], True
for op in delta:
if not dropping:
out.append(op)
continue
nl = op["insert"].find("\n")
if nl == -1:
continue # whole op is on the first line -> drop it
dropping = False
rest = op["insert"][nl + 1 :]
if rest:
out.append({**op, "insert": rest})
return out
def _list_item_block(li, list_type):
delta, children = [], []
for c in li.children:
if c.type == "paragraph" and not delta and not children:
delta = _delta_of(c)
else:
children.extend(_block_from_node(c))
task = _task_state(delta)
if task is not None:
block = {"type": "todo_list", "data": {"checked": task[0], "delta": task[1]}}
else:
block = {"type": list_type, "data": {"delta": delta or [{"insert": ""}]}}
if children:
block["children"] = children
return block
def _block_from_node(node) -> list:
"""Map one markdown-it block node -> zero or more AppFlowy blocks."""
t = node.type
if t == "heading":
lvl = min(max(int(node.tag[1:]), 1), 6)
return [{"type": "heading", "data": {"level": lvl, "delta": _delta_of(node)}}]
if t == "paragraph":
url = _sole_image_url(node)
if url:
return [{"type": "image", "data": {"url": url}}]
return [{"type": "paragraph", "data": {"delta": _delta_of(node)}}]
if t == "hr":
return [{"type": "divider", "data": {}}]
if t in ("fence", "code_block"):
lang = (node.info or "").strip().split(" ")[0] if t == "fence" else ""
code = node.content.rstrip("\n")
return [
{"type": "code", "data": {"language": lang, "delta": [{"insert": code}]}}
]
if t == "math_block":
return [{"type": "math_equation", "data": {"formula": node.content.strip()}}]
if t == "blockquote":
parts = [_delta_of(c) for c in node.children if c.type == "paragraph"]
delta = []
for i, p in enumerate(parts):
if i:
delta.append({"insert": "\n"})
delta.extend(p)
# A GFM alert ("> [!NOTE]") becomes an AppFlowy callout; else a plain quote.
lead = delta[0]["insert"] if delta and "attributes" not in delta[0] else ""
marker = lead.split("\n", 1)[0].strip().lower()
for name, icon in _ALERT_ICONS.items():
if marker == f"[!{name}]":
body = _drop_first_line(delta)
return [
{
"type": "callout",
"data": {"icon": icon, "delta": body or [{"insert": ""}]},
}
]
return [{"type": "quote", "data": {"delta": delta or [{"insert": ""}]}}]
if t == "bullet_list":
return [_list_item_block(li, "bulleted_list") for li in node.children]
if t == "ordered_list":
return [_list_item_block(li, "numbered_list") for li in node.children]
text = _node_plaintext(node)
return (
[{"type": "paragraph", "data": {"delta": [{"insert": text}]}}] if text else []
)
def _md_to_blocks(markdown: str) -> list:
"""Parse Markdown into an AppFlowy page block-tree (list of block dicts)."""
tree = SyntaxTreeNode(_md_parser.parse(markdown or ""))
blocks: list = []
for node in tree.children:
blocks.extend(_block_from_node(node))
return blocks
# ---- AppFlowy block tree → Markdown (the inverse of _md_to_blocks) ---------
# Reads a document collab's blocks and renders Markdown, so an agent can pull a
# page or card body back out in the format it writes (symmetric with
# create_page(markdown=...)). Inline styles come from each yjs Text's diff() —
# segments of (text, {bold|italic|strikethrough|code|href}); block-type fields
# (level, checked, language, url) come from the block's `data` JSON.
# Markdown list "family": bullet-style items (- / - [ ]) pack tight together, but a
# switch to/from an ordered (1.) list needs a blank line so it re-parses cleanly.
_LIST_FAMILY = {"bulleted_list": "ul", "todo_list": "ul", "numbered_list": "ol"}
def _inline_md(delta) -> str:
out = []
for text, attrs in delta or []:
a = attrs or {}
mention = a.get("mention")
if mention and mention.get("page_id"): # page mention -> [](mention:<id>)
out.append(f"[](mention:{mention['page_id']})")
continue
if a.get("code"):
seg = f"`{text}`"
else:
seg = text
if a.get("bold"):
seg = f"**{seg}**"
if a.get("italic"):
seg = f"*{seg}*"
if a.get("strikethrough"):
seg = f"~~{seg}~~"
if a.get("href"):
seg = f"[{seg}]({a['href']})"
out.append(seg)
return "".join(out)
def _render_block(bid, blocks, cmap, tmap, depth):
"""Return (lines, is_list_item) for a block and its (indented) children."""
b = blocks[bid]
ty = b["ty"] if "ty" in b else ""
data = json.loads(b["data"]) if ("data" in b and b["data"]) else {}
ext = b["external_id"] if "external_id" in b else None
delta = tmap[ext].diff() if (ext is not None and ext in tmap) else []
pad = " " * depth
if ty == "code":
raw = "".join(t for t, _ in delta)
lines = [f"```{data.get('language', '')}", *raw.split("\n"), "```"]
elif ty == "divider":
lines = ["---"]
elif ty == "image":
lines = [f"})"]
elif ty == "math_equation":
lines = ["$$", data.get("formula", ""), "$$"]
else:
text = _inline_md(delta)
if ty == "heading":
lines = ["#" * int(data.get("level", 1)) + " " + text]
elif ty == "bulleted_list":
lines = [f"{pad}- {text}"]
elif ty == "numbered_list":
lines = [f"{pad}1. {text}"]
elif ty == "todo_list":
box = "x" if data.get("checked") else " "
lines = [f"{pad}- [{box}] {text}"]
elif ty == "quote":
lines = [f"> {text}"]
elif ty == "callout":
alert = _ICON_ALERTS.get(data.get("icon", ""))
head = f"> [!{alert.upper()}]" if alert else "> [!NOTE]"
body = text.split("\n") if text else []
if not alert and data.get("icon") and body:
body[0] = f"{data['icon']} {body[0]}"
lines = [head] + [f"> {ln}" for ln in body]
elif ty == "toggle_list": # a level makes it a toggle-heading; no md toggle
lvl = data.get("level")
lines = ["#" * int(lvl) + " " + text] if lvl else [f"{pad}- {text}"]
else: # paragraph, and any unknown block -> plain text (never dropped)
lines = [text]
ck = b["children"] if "children" in b else None
if ck is not None and ck in cmap:
for c in list(cmap[ck]):
child_lines, _ = _render_block(c, blocks, cmap, tmap, depth + 1)
lines.extend(child_lines)
return lines, _LIST_FAMILY.get(ty)
def _doc_to_markdown(document) -> str:
"""Render a document map ({blocks, meta, page_id}) to Markdown."""
blocks, meta = document["blocks"], document["meta"]
cmap, tmap = meta["children_map"], meta["text_map"]
root = blocks[document["page_id"]]
ck = root["children"] if "children" in root else None
if ck is None or ck not in cmap:
return ""
parts, prev_fam = [], None
for i, c in enumerate(list(cmap[ck])):
lines, fam = _render_block(c, blocks, cmap, tmap, 0)
block_md = "\n".join(lines)
if i == 0:
parts.append(block_md)
else:
parts.append(("\n" if fam and fam == prev_fam else "\n\n") + block_md)
prev_fam = fam
return "".join(parts).strip() + "\n"
# Code / equation blocks hold literal text; everything else renders inline Markdown.
_PLAIN_TEXT_TYS = {"code", "math_equation"}
def _md_inline_to_delta(text: str) -> list:
"""Parse one line of inline Markdown (**bold**, *italic*, `code`, ~~strike~~,
[links](url)) into an AppFlowy delta; literal fallback for non-inline input."""
if not text:
return []
blocks = _md_to_blocks(text)
if len(blocks) == 1 and blocks[0]["type"] == "paragraph":
return blocks[0]["data"]["delta"]
return [{"insert": text}]
def _set_text(text_obj, delta) -> None:
"""Overwrite a yjs Text from a delta: plain content, then inline formatting ranges
(bold/italic/strikethrough/code/href) via Text.format(start, stop)."""
if len(text_obj) > 0:
del text_obj[0 : len(text_obj)]
plain = "".join(op["insert"] for op in delta)
if plain:
text_obj.insert(0, plain)
pos = 0
for op in delta:
n = len(op["insert"])
attrs = op.get("attributes")
if attrs and n:
text_obj.format(pos, pos + n, attrs)
pos += n
@mcp.tool(annotations=_CREATE)
def create_page(