upnote-mcp 0.1.0__py3-none-any.whl

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.
upnote_mcp/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Read-only MCP server for local UpNote data (unofficial, not affiliated with UpNote)."""
2
+
3
+ __version__ = "0.1.0"
upnote_mcp/config.py ADDED
@@ -0,0 +1,52 @@
1
+ """Server settings. Configuration only: Tools can never change the DB path or the spaces.
2
+
3
+ Environment variables
4
+ ---------------------
5
+ ``UPNOTE_MCP_DB_PATH``
6
+ Optional. Path to the UpNote SQLite file (``~`` is expanded). Empty or unset means the
7
+ default macOS location of the UpNote desktop app under the current user's home directory.
8
+ ``UPNOTE_MCP_SPACES``
9
+ Optional. Comma-separated space (workspace) names that may be exposed in addition to the
10
+ default space, e.g. ``Work,Reading list``. Each name is trimmed of surrounding whitespace,
11
+ empty entries are ignored, and matching is exact (case-sensitive). Unset or empty means
12
+ only the default space is exposed. A name shared by several spaces, or naming a locked or
13
+ deleted space, never exposes anything.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from collections.abc import Mapping
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+
23
+ ENV_DB_PATH = "UPNOTE_MCP_DB_PATH"
24
+ ENV_SPACES = "UPNOTE_MCP_SPACES"
25
+
26
+ _DEFAULT_RELATIVE = Path(
27
+ "Library/Containers/com.getupnote.desktop/Data/Library/Application Support/UpNote/"
28
+ "upnote.sqlite3"
29
+ )
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Settings:
34
+ db_path: Path
35
+ allowed_spaces: frozenset[str]
36
+
37
+
38
+ def default_db_path() -> Path:
39
+ return Path.home() / _DEFAULT_RELATIVE
40
+
41
+
42
+ def parse_spaces(raw: str | None) -> frozenset[str]:
43
+ if not raw:
44
+ return frozenset()
45
+ return frozenset(name for part in raw.split(",") if (name := part.strip()))
46
+
47
+
48
+ def load_settings(env: Mapping[str, str] | None = None) -> Settings:
49
+ source = os.environ if env is None else env
50
+ raw_path = source.get(ENV_DB_PATH, "").strip()
51
+ db_path = Path(raw_path).expanduser() if raw_path else default_db_path()
52
+ return Settings(db_path=db_path, allowed_spaces=parse_spaces(source.get(ENV_SPACES)))
upnote_mcp/db.py ADDED
@@ -0,0 +1,176 @@
1
+ """Read-only SQLite access: one short read transaction per snapshot.
2
+
3
+ Safety rules (docs/PLAN.md section 3): existing file only, ``mode=ro`` URI with the path
4
+ percent-encoded, ``PRAGMA query_only=ON``, never ``immutable=1``, never create, never write,
5
+ never touch WAL/SHM files ourselves. Errors are sanitized: no path, id or content.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import errno
11
+ import os
12
+ import sqlite3
13
+ import time
14
+ from collections.abc import Iterator
15
+ from contextlib import contextmanager, suppress
16
+ from pathlib import Path
17
+
18
+ from upnote_mcp.records import SourceError
19
+
20
+ DEFAULT_BUSY_TIMEOUT_MS = 1000
21
+ DEFAULT_RETRIES = 2 # extra attempts after the first one, busy errors only
22
+ _RETRY_SLEEP_S = 0.05
23
+
24
+ # Columns the policy and repository read, with the declared types of the real UpNote DDL.
25
+ # Every table's ``id`` must be the PRIMARY KEY: the policy keys decisions by id and the detail
26
+ # queries assume one row per id. Anything else -> schema_unsupported before any read.
27
+ REQUIRED_COLUMNS: dict[str, dict[str, str]] = {
28
+ "notes": {
29
+ "id": "TEXT",
30
+ "title": "TEXT",
31
+ "text": "TEXT",
32
+ "summary": "TEXT",
33
+ "deleted": "INTEGER",
34
+ "trashed": "INTEGER",
35
+ "space": "TEXT",
36
+ "updatedAt": "DOUBLE",
37
+ "createdAt": "DOUBLE",
38
+ "revision": "INTEGER",
39
+ "tagLinks": "TEXT",
40
+ },
41
+ "notebooks": {
42
+ "id": "TEXT",
43
+ "title": "TEXT",
44
+ "deleted": "INTEGER",
45
+ "inactive": "INTEGER",
46
+ "locked": "INTEGER",
47
+ "notes": "TEXT",
48
+ "childNotebooks": "TEXT",
49
+ "parent": "TEXT",
50
+ "space": "TEXT",
51
+ },
52
+ "organizers": {"id": "TEXT", "noteId": "TEXT", "notebookId": "TEXT", "deleted": "INTEGER"},
53
+ "lists": {"id": "TEXT", "deleted": "INTEGER", "content": "TEXT", "space": "TEXT"},
54
+ "workspaces": {"id": "TEXT", "name": "TEXT", "deleted": "INTEGER", "locked": "INTEGER"},
55
+ "tags": {
56
+ "id": "TEXT",
57
+ "title": "TEXT",
58
+ "deleted": "INTEGER",
59
+ "inactive": "INTEGER",
60
+ "space": "TEXT",
61
+ },
62
+ }
63
+
64
+
65
+ _MISSING = SourceError("source_missing", "UpNote database not found")
66
+ _DENIED = SourceError("permission_denied", "Permission denied reading UpNote data")
67
+
68
+
69
+ def _from_os_error(exc: BaseException) -> SourceError:
70
+ """Classify a path-level failure without exposing the OS message or the path."""
71
+ if isinstance(exc, PermissionError) or getattr(exc, "errno", None) in (
72
+ errno.EACCES,
73
+ errno.EPERM,
74
+ ):
75
+ return SourceError(_DENIED.code, str(_DENIED))
76
+ return SourceError(_MISSING.code, str(_MISSING)) # ENOENT/ENOTDIR/ELOOP/ENAMETOOLONG/...
77
+
78
+
79
+ def _readonly_uri(path: Path) -> str:
80
+ # as_uri() percent-encodes '?', '#', '%' and non-ASCII, so a path can't inject URI options
81
+ return f"{path.resolve(strict=True).as_uri()}?mode=ro"
82
+
83
+
84
+ def _check_file(path: Path) -> None:
85
+ try:
86
+ os.stat(path) # noqa: PTH116 - need the raw errno mapping
87
+ if not path.is_file():
88
+ raise SourceError(_MISSING.code, str(_MISSING))
89
+ if not os.access(path, os.R_OK):
90
+ raise SourceError(_DENIED.code, str(_DENIED))
91
+ except (OSError, ValueError, RuntimeError) as exc: # ELOOP, ENAMETOOLONG, NUL byte, ...
92
+ raise _from_os_error(exc) from None
93
+
94
+
95
+ def _map_error(exc: sqlite3.Error, path: Path) -> SourceError:
96
+ msg = str(exc).lower()
97
+ if "locked" in msg or "busy" in msg:
98
+ return SourceError("busy", "UpNote database is busy; try again")
99
+ if isinstance(exc, sqlite3.OperationalError) and "unable to open" in msg:
100
+ try:
101
+ _check_file(path)
102
+ except SourceError as err:
103
+ return err
104
+ return SourceError("permission_denied", "Permission denied reading UpNote data")
105
+ if "not a database" in msg or "malformed" in msg or "corrupt" in msg:
106
+ return SourceError("source_corrupt", "UpNote database is unreadable")
107
+ return SourceError("schema_unsupported", "UpNote database could not be read")
108
+
109
+
110
+ def _check_schema(con: sqlite3.Connection) -> None:
111
+ for table, columns in REQUIRED_COLUMNS.items():
112
+ info = { # name -> (declared type, primary-key position)
113
+ row[1]: (str(row[2]).strip().upper(), row[5])
114
+ for row in con.execute(f"PRAGMA table_info({table})") # noqa: S608 - fixed names
115
+ }
116
+ ok = all(name in info and info[name][0] == typ for name, typ in columns.items())
117
+ # the primary key must be exactly (id): a composite key would allow duplicate ids
118
+ only_id = ok and info["id"][1] == 1 and all(v[1] == 0 for k, v in info.items() if k != "id")
119
+ if not only_id:
120
+ raise SourceError("schema_unsupported", "UpNote database schema is not supported")
121
+
122
+
123
+ def _open_once(path: Path, busy_timeout_ms: int) -> sqlite3.Connection:
124
+ _check_file(path)
125
+ try:
126
+ uri = _readonly_uri(path)
127
+ except (OSError, ValueError, RuntimeError) as exc:
128
+ raise _from_os_error(exc) from None
129
+ con = sqlite3.connect(
130
+ uri,
131
+ uri=True,
132
+ timeout=busy_timeout_ms / 1000,
133
+ isolation_level=None, # we issue BEGIN/ROLLBACK ourselves
134
+ )
135
+ try:
136
+ con.execute(f"PRAGMA busy_timeout={int(busy_timeout_ms)}")
137
+ con.execute("PRAGMA query_only=ON")
138
+ con.execute("BEGIN") # deferred: the snapshot starts at the first read
139
+ _check_schema(con) # first read: pins the WAL snapshot for everything that follows
140
+ except BaseException:
141
+ con.close()
142
+ raise
143
+ return con
144
+
145
+
146
+ @contextmanager
147
+ def read_snapshot(
148
+ path: Path,
149
+ *,
150
+ busy_timeout_ms: int = DEFAULT_BUSY_TIMEOUT_MS,
151
+ retries: int = DEFAULT_RETRIES,
152
+ ) -> Iterator[sqlite3.Connection]:
153
+ """Yield a connection inside one read transaction. Raises ``SourceError`` only."""
154
+ con: sqlite3.Connection | None = None
155
+ for attempt in range(retries + 1):
156
+ try:
157
+ con = _open_once(path, busy_timeout_ms)
158
+ break
159
+ except SourceError as err:
160
+ if err.code != "busy" or attempt == retries:
161
+ raise
162
+ except sqlite3.Error as exc:
163
+ err = _map_error(exc, path)
164
+ if err.code != "busy" or attempt == retries:
165
+ raise err from None
166
+ time.sleep(_RETRY_SLEEP_S * (attempt + 1))
167
+ if con is None: # unreachable: the last attempt either connects or raises
168
+ raise SourceError("busy", "UpNote database is busy; try again")
169
+ try:
170
+ yield con
171
+ except sqlite3.Error as exc:
172
+ raise _map_error(exc, path) from None
173
+ finally:
174
+ with suppress(sqlite3.Error):
175
+ con.execute("ROLLBACK")
176
+ con.close()
upnote_mcp/models.py ADDED
@@ -0,0 +1,83 @@
1
+ """Output DTOs returned by the MCP tools (camelCase on the wire).
2
+
3
+ Every string that comes from a note (title, preview, content, tag/notebook titles) is
4
+ untrusted data, never instructions.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pydantic import BaseModel, ConfigDict
10
+
11
+ CONTENT_FORMAT = "plain"
12
+
13
+
14
+ class _Dto(BaseModel):
15
+ model_config = ConfigDict(frozen=True)
16
+
17
+
18
+ class NoteItem(_Dto):
19
+ id: str
20
+ title: str
21
+ preview: str
22
+ updatedAt: str | None # noqa: N815 - ISO 8601 UTC with milliseconds
23
+ notebookIds: list[str] # noqa: N815
24
+ tags: list[str]
25
+
26
+
27
+ class NotePage(_Dto):
28
+ items: list[NoteItem]
29
+ total: int
30
+ hasMore: bool # noqa: N815
31
+ nextOffset: int | None # noqa: N815
32
+
33
+
34
+ class NoteDetail(_Dto):
35
+ id: str
36
+ title: str
37
+ content: str
38
+ contentFormat: str = CONTENT_FORMAT # noqa: N815
39
+ offset: int
40
+ length: int # code points in ``content``
41
+ totalLength: int # noqa: N815 - code points in the whole text
42
+ hasMore: bool # noqa: N815
43
+ nextOffset: int | None # noqa: N815
44
+ forcedSplit: bool = False # noqa: N815 - chunk ends inside an oversized grapheme
45
+ version: str
46
+ notebookIds: list[str] # noqa: N815
47
+ tags: list[str]
48
+ createdAt: str | None # noqa: N815
49
+ updatedAt: str | None # noqa: N815
50
+
51
+
52
+ class NotebookItem(_Dto):
53
+ id: str
54
+ title: str
55
+ parentId: str | None # noqa: N815
56
+ noteCount: int # noqa: N815
57
+
58
+
59
+ class NotebookList(_Dto):
60
+ items: list[NotebookItem]
61
+ total: int
62
+ truncated: bool
63
+
64
+
65
+ class TagItem(_Dto):
66
+ title: str
67
+ noteCount: int # noqa: N815
68
+
69
+
70
+ class TagList(_Dto):
71
+ items: list[TagItem]
72
+ total: int
73
+ truncated: bool
74
+
75
+
76
+ class SourceStatusOut(_Dto):
77
+ connected: bool
78
+ schemaOk: bool # noqa: N815
79
+ visibleNoteCount: int # noqa: N815
80
+ visibleNotebookCount: int # noqa: N815
81
+ allowedSpaceNames: list[str] # noqa: N815
82
+ checkedAt: str | None # noqa: N815
83
+ note: str
upnote_mcp/policy.py ADDED
@@ -0,0 +1,320 @@
1
+ """Access policy (docs/PLAN.md section 3, SPEC F-07): one visibility decision per snapshot.
2
+
3
+ ``compute_access`` reads every table it needs from ONE read transaction with fixed SQL, then
4
+ decides in memory which notes, notebooks and tags may be exposed. It is fail-closed:
5
+
6
+ * membership = ``lists`` ('notebooks_' rows, deleted=0) U ``organizers`` (deleted=0) U
7
+ ``notebooks.notes``; ``notes.notebookLinks`` and non-'notebooks_' list rows are ignored;
8
+ * any protective evidence from any source hides the note; deleted relations are not
9
+ membership but still count as protection signals / "membership unknown";
10
+ * corrupt membership or protection data raises ``SourceError("source_corrupt")`` (whole source).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import sqlite3
17
+ from collections import Counter
18
+ from dataclasses import dataclass
19
+ from typing import Any
20
+
21
+ from upnote_mcp.records import SourceError
22
+
23
+ LISTS_PREFIX = "notebooks_"
24
+
25
+ _SQL_NOTES = "SELECT id, deleted, trashed, space, tagLinks FROM notes"
26
+ _SQL_NOTEBOOKS = (
27
+ "SELECT id, title, deleted, inactive, locked, notes, childNotebooks, parent, space "
28
+ "FROM notebooks"
29
+ )
30
+ _SQL_ORGANIZERS = "SELECT noteId, notebookId, deleted FROM organizers"
31
+ _SQL_LISTS = "SELECT id, deleted, content, space FROM lists"
32
+ _SQL_WORKSPACES = "SELECT id, name, deleted, locked FROM workspaces"
33
+ _SQL_TAGS = "SELECT title, deleted, inactive, space FROM tags"
34
+
35
+
36
+ def _corrupt() -> SourceError:
37
+ return SourceError("source_corrupt", "UpNote data could not be verified")
38
+
39
+
40
+ def _flag(value: Any) -> bool:
41
+ """Strict 0/1 flag; NULL or any other value means the state is unknown -> corrupt."""
42
+ if type(value) is not int or value not in (0, 1):
43
+ raise _corrupt()
44
+ return value == 1
45
+
46
+
47
+ def valid_id(value: str) -> bool:
48
+ """records.py id contract: 1-128 characters, no C0/C1 control characters or DEL."""
49
+ return 1 <= len(value) <= 128 and not any(
50
+ ord(c) < 0x20 or 0x7F <= ord(c) <= 0x9F for c in value
51
+ )
52
+
53
+
54
+ def _is_zero(value: Any) -> bool:
55
+ return type(value) is int and value == 0
56
+
57
+
58
+ def _opt_str(value: Any) -> str | None:
59
+ if value is not None and not isinstance(value, str):
60
+ raise _corrupt()
61
+ return value
62
+
63
+
64
+ def _req_str(value: Any) -> str:
65
+ if not isinstance(value, str):
66
+ raise _corrupt()
67
+ return value
68
+
69
+
70
+ def _id_list(raw: Any) -> list[str]:
71
+ """JSON array of strings, else corrupt (NULL, '', invalid, non-array, mixed elements)."""
72
+ if not isinstance(raw, str):
73
+ raise _corrupt()
74
+ try:
75
+ value = json.loads(raw)
76
+ except ValueError:
77
+ raise _corrupt() from None
78
+ if not isinstance(value, list) or not all(isinstance(x, str) for x in value):
79
+ raise _corrupt()
80
+ return value
81
+
82
+
83
+ @dataclass(frozen=True, slots=True)
84
+ class NotebookInfo:
85
+ title: str
86
+ parent_id: str | None # only when that parent notebook is visible
87
+
88
+
89
+ @dataclass(frozen=True, slots=True)
90
+ class Access:
91
+ visible_notes: frozenset[str]
92
+ note_notebooks: dict[str, tuple[str, ...]] # visible note -> visible notebooks, sorted
93
+ note_tags: dict[str, tuple[str, ...]] # visible note -> visible tag titles, sorted
94
+ notebooks: dict[str, NotebookInfo] # visible notebooks
95
+ notebook_notes: dict[str, frozenset[str]] # visible notebook -> visible notes
96
+ tag_counts: dict[str, int] # visible tag title (no '#') -> visible notes
97
+
98
+
99
+ @dataclass(slots=True)
100
+ class _Nb:
101
+ title: str
102
+ deleted: bool
103
+ inactive: bool
104
+ locked: bool
105
+ notes: list[str]
106
+ children: list[str] | None
107
+ parent: str | None
108
+ space: str | None
109
+
110
+
111
+ @dataclass(slots=True)
112
+ class _Tag:
113
+ title: str
114
+ live: bool
115
+
116
+
117
+ def _title(value: Any) -> str:
118
+ return value if isinstance(value, str) else ""
119
+
120
+
121
+ def _load_notebooks(con: sqlite3.Connection) -> dict[str, _Nb]:
122
+ out: dict[str, _Nb] = {}
123
+ for nid, title, deleted, inactive, locked, notes, children, parent, space in con.execute(
124
+ _SQL_NOTEBOOKS
125
+ ):
126
+ nb_id = _req_str(nid)
127
+ if inactive is None:
128
+ inactive = 0 # NULL "inactive" is common for active notebooks; other junk is corrupt
129
+ out[nb_id] = _Nb(
130
+ title=_title(title),
131
+ deleted=_flag(deleted),
132
+ inactive=_flag(inactive),
133
+ locked=_flag(locked),
134
+ notes=_id_list(notes),
135
+ children=None if children is None else _id_list(children),
136
+ parent=_opt_str(parent) or None, # '' and NULL are both roots
137
+ space=_opt_str(space),
138
+ )
139
+ return out
140
+
141
+
142
+ def _chain(nb_id: str, nbs: dict[str, _Nb]) -> tuple[list[str], bool]:
143
+ """Notebook then its ancestors via ``parent``; True when the chain is broken
144
+ (missing parent, self-reference or cycle)."""
145
+ seen: list[str] = []
146
+ cur: str | None = nb_id
147
+ while cur is not None:
148
+ if cur in seen or cur not in nbs:
149
+ return seen, True
150
+ seen.append(cur)
151
+ cur = nbs[cur].parent
152
+ return seen, False
153
+
154
+
155
+ def _tag_key(title: str) -> str:
156
+ return title.removeprefix("#").casefold()
157
+
158
+
159
+ def compute_access(con: sqlite3.Connection, allowed_spaces: frozenset[str]) -> Access: # noqa: C901, PLR0912, PLR0915
160
+ # ---- workspaces / spaces --------------------------------------------------------
161
+ workspaces: dict[str, tuple[str | None, bool, bool]] = {}
162
+ for ws_id, name, deleted, locked in con.execute(_SQL_WORKSPACES):
163
+ workspaces[_req_str(ws_id)] = (_opt_str(name), _flag(deleted), _flag(locked))
164
+ name_counts = Counter(n for n, _, _ in workspaces.values() if n is not None)
165
+
166
+ def space_ok(space: str | None) -> bool:
167
+ if space is None:
168
+ return True # default space
169
+ if space == "":
170
+ return False # never the default space and never a workspace id
171
+ ws = workspaces.get(space)
172
+ if ws is None:
173
+ return False # '' or unknown id is never the default space
174
+ name, deleted, locked = ws
175
+ return (
176
+ name is not None
177
+ and not deleted
178
+ and not locked
179
+ and name in allowed_spaces
180
+ and name_counts[name] == 1
181
+ )
182
+
183
+ # ---- notebooks and hierarchy ----------------------------------------------------
184
+ nbs = _load_notebooks(con)
185
+ chains = {nb_id: _chain(nb_id, nbs) for nb_id in nbs}
186
+
187
+ def chain_locked(nb_id: str) -> bool:
188
+ return any(nbs[x].locked for x in chains[nb_id][0])
189
+
190
+ claimed_bad: set[str] = set() # childNotebooks as a protection signal (not an edge)
191
+ for p_id, parent in nbs.items():
192
+ if parent.children is None:
193
+ continue
194
+ locked_claimer = chain_locked(p_id)
195
+ for c_id in parent.children:
196
+ child = nbs.get(c_id)
197
+ if child is None:
198
+ continue
199
+ if locked_claimer or (child.parent is not None and child.parent != p_id):
200
+ claimed_bad.add(c_id)
201
+
202
+ hard: dict[str, bool] = {} # protective / unprovable: hide the notebook and its notes
203
+ soft: dict[str, bool] = {} # deleted/inactive here or above: not a usable membership
204
+
205
+ def space_conflict(x: str) -> bool: # a notebook and its parent live in different spaces
206
+ parent = nbs[x].parent
207
+ return parent in nbs and nbs[parent].space != nbs[x].space
208
+
209
+ for nb_id in nbs:
210
+ members, broken = chains[nb_id]
211
+ hard[nb_id] = broken or any(
212
+ nbs[x].locked or x in claimed_bad or not space_ok(nbs[x].space) or space_conflict(x)
213
+ for x in members
214
+ )
215
+ soft[nb_id] = any(nbs[x].deleted or nbs[x].inactive or not valid_id(x) for x in members)
216
+
217
+ # ---- membership sources (note id -> notebook ids) -------------------------------
218
+ active: dict[str, set[str]] = {}
219
+ removed: dict[str, set[str]] = {} # deleted relations: protection signal only
220
+ lists_space_bad: dict[str, set[str]] = {}
221
+
222
+ def add(target: dict[str, set[str]], note: str, nb: str) -> None:
223
+ target.setdefault(note, set()).add(nb)
224
+
225
+ for nb_id, nb in nbs.items():
226
+ for note in nb.notes:
227
+ add(active, note, nb_id)
228
+ for note_id, nb_id, deleted in con.execute(_SQL_ORGANIZERS):
229
+ add(removed if _flag(deleted) else active, _req_str(note_id), _req_str(nb_id))
230
+ for row_id, deleted, content, space in con.execute(_SQL_LISTS):
231
+ row_id = _req_str(row_id)
232
+ if not row_id.startswith(LISTS_PREFIX):
233
+ continue # activeNotebooks, bookmarkedNotes, templates, ... are not membership
234
+ is_deleted = _flag(deleted)
235
+ nb_id = row_id.removeprefix(LISTS_PREFIX)
236
+ row_space = _opt_str(space)
237
+ members = _id_list(content)
238
+ for note in members:
239
+ add(removed if is_deleted else active, note, nb_id)
240
+ # a row whose space differs from its notebook's (or is '') is a protection signal,
241
+ # deleted rows included
242
+ if row_space == "" or (nb_id in nbs and nbs[nb_id].space != row_space):
243
+ add(lists_space_bad, note, nb_id)
244
+
245
+ # ---- tags -----------------------------------------------------------------------
246
+ tags_by_key: dict[str, list[_Tag]] = {}
247
+ for title, deleted, inactive, space in con.execute(_SQL_TAGS):
248
+ if not isinstance(title, str):
249
+ continue
250
+ # state must be exactly integer 0: NULL/other means unknown -> hide the tag only
251
+ live = _is_zero(deleted) and _is_zero(inactive) and space_ok(_opt_str(space))
252
+ tags_by_key.setdefault(_tag_key(title), []).append(_Tag(title.removeprefix("#"), live))
253
+
254
+ def visible_tag(link: str) -> str | None:
255
+ cands = tags_by_key.get(_tag_key(link))
256
+ if not cands or not all(c.live for c in cands):
257
+ return None # unknown, deleted or inactive (any same-key row is enough to hide)
258
+ titles = sorted({c.title for c in cands})
259
+ return link.removeprefix("#") if link.removeprefix("#") in titles else titles[0]
260
+
261
+ # ---- notes ----------------------------------------------------------------------
262
+ visible: set[str] = set()
263
+ note_notebooks: dict[str, tuple[str, ...]] = {}
264
+ note_tags: dict[str, tuple[str, ...]] = {}
265
+ for note_id, deleted, trashed, space, tag_links in con.execute(_SQL_NOTES):
266
+ note_id = _req_str(note_id)
267
+ if not valid_id(note_id):
268
+ continue # id contract violated: never exposed
269
+ is_deleted, is_trashed, note_space = _flag(deleted), _flag(trashed), _opt_str(space)
270
+ if is_deleted or is_trashed or not space_ok(note_space):
271
+ continue
272
+ acts = active.get(note_id, set())
273
+ gone = removed.get(note_id, set())
274
+ refs = acts | gone
275
+ if any(r not in nbs for r in refs):
276
+ continue # orphan notebook reference: its protection is unprovable
277
+ if note_id in lists_space_bad:
278
+ continue
279
+ if any(hard[r] for r in refs):
280
+ continue
281
+ if any(nbs[r].space != note_space for r in acts):
282
+ continue # note and notebook disagree about the space
283
+ usable = sorted(r for r in acts if not soft[r])
284
+ if refs and not usable:
285
+ continue # only deleted/inactive/removed links: membership unknown, not uncategorized
286
+ visible.add(note_id)
287
+ note_notebooks[note_id] = tuple(usable)
288
+ found: set[str] = set()
289
+ if isinstance(tag_links, str):
290
+ try:
291
+ parsed = json.loads(tag_links)
292
+ except ValueError:
293
+ parsed = []
294
+ for link in parsed if isinstance(parsed, list) else []:
295
+ if isinstance(link, str) and (shown := visible_tag(link)) is not None:
296
+ found.add(shown)
297
+ note_tags[note_id] = tuple(sorted(found))
298
+
299
+ # ---- derived views over the visible set -----------------------------------------
300
+ visible_nbs = {i for i in nbs if not hard[i] and not soft[i]}
301
+ nb_notes: dict[str, set[str]] = {i: set() for i in visible_nbs}
302
+ for note_id, nb_ids in note_notebooks.items():
303
+ for nb_id in nb_ids:
304
+ if nb_id in nb_notes:
305
+ nb_notes[nb_id].add(note_id)
306
+ tag_counts: Counter[str] = Counter()
307
+ for tags in note_tags.values():
308
+ tag_counts.update(tags)
309
+ infos = {
310
+ i: NotebookInfo(nbs[i].title, nbs[i].parent if nbs[i].parent in visible_nbs else None)
311
+ for i in visible_nbs
312
+ }
313
+ return Access(
314
+ visible_notes=frozenset(visible),
315
+ note_notebooks=note_notebooks,
316
+ note_tags=note_tags,
317
+ notebooks=infos,
318
+ notebook_notes={k: frozenset(v) for k, v in nb_notes.items()},
319
+ tag_counts=dict(tag_counts),
320
+ )
upnote_mcp/py.typed ADDED
File without changes