Collection¶
The Collection class is the primary public API for the library. MCP tools, CLI commands, and direct integrations all go through this class.
Quick Start¶
from pathlib import Path
from markdown_vault_mcp import Collection
# Basic read-only collection
collection = Collection(source_dir=Path("/path/to/vault"))
stats = collection.build_index()
print(f"Indexed {stats.documents_indexed} documents")
# Search
results = collection.search("query text", limit=10)
for r in results:
print(f"{r.path}: {r.title} (score: {r.score:.2f})")
# Read a document
note = collection.read("Journal/note.md")
print(note.content)
API Reference¶
Collection(*, source_dir, index_path=None, embeddings_path=None, embedding_provider=None, read_only=True, state_path=None, indexed_frontmatter_fields=None, required_frontmatter=None, chunk_strategy='heading', on_write=None, git_strategy=None, git_pull_interval_s=0, exclude_patterns=None, attachment_extensions=None, max_attachment_size_mb=10.0)
¶
Facade over FTS5 index, vector index, and change tracker.
Instantiate once per collection root. Call :meth:build_index (or let
lazy initialisation handle it) before querying.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_dir
|
Path
|
Root directory of the markdown collection. |
required |
index_path
|
Path | None
|
Path to the SQLite index file. |
None
|
embeddings_path
|
Path | None
|
Base path for the |
None
|
embedding_provider
|
EmbeddingProvider | None
|
Provider used to generate embeddings. Required when embeddings_path is set. |
None
|
read_only
|
bool
|
When |
True
|
state_path
|
Path | None
|
Path to the hash-state JSON file used by
:class: |
None
|
indexed_frontmatter_fields
|
list[str] | None
|
Frontmatter keys whose values are
promoted to the |
None
|
required_frontmatter
|
list[str] | None
|
If provided, documents missing any listed field are excluded from the index entirely. |
None
|
chunk_strategy
|
str | ChunkStrategy
|
|
'heading'
|
on_write
|
WriteCallback | None
|
Optional callback invoked after every successful write
operation. Signature:
|
None
|
git_strategy
|
GitWriteStrategy | None
|
Optional git strategy used for background git tasks (e.g.
periodic fetch + ff-only updates). Started via :meth: |
None
|
git_pull_interval_s
|
int
|
Interval in seconds for periodic pulls. |
0
|
Source code in src/markdown_vault_mcp/collection.py
pause_writes()
¶
Block all write operations until the context exits.
Write operations are queued (blocked on the lock) rather than being rejected. Reads and search remain unblocked at the Python level.
Source code in src/markdown_vault_mcp/collection.py
sync_from_remote_before_index()
¶
One-time git fetch + ff-only update before build_index().
Intended to run during server startup before the initial index build. No reindex is triggered here because build_index() will scan the updated working tree.
Source code in src/markdown_vault_mcp/collection.py
start()
¶
Start background tasks for this Collection (e.g. git pull loop).
Source code in src/markdown_vault_mcp/collection.py
stop()
¶
Stop background tasks (e.g. git pull loop) without closing the collection.
Safe to call multiple times. A no-op if no pull loop was started. The SQLite connection and write callback remain open; only the pull loop thread is signalled to stop.
Source code in src/markdown_vault_mcp/collection.py
build_index(*, force=False)
¶
Scan source_dir and build the FTS index.
If the index already contains documents and force is False,
this is a no-op. force=True drops all existing data and rebuilds
from scratch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
force
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
IndexStats
|
class: |
Source code in src/markdown_vault_mcp/collection.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 | |
search(query, *, limit=10, mode='keyword', filters=None, folder=None)
¶
Search the collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search string. |
required |
limit
|
int
|
Maximum number of results to return. |
10
|
mode
|
Literal['keyword', 'semantic', 'hybrid']
|
|
'keyword'
|
filters
|
dict[str, str] | None
|
Dict of |
None
|
folder
|
str | None
|
If provided, restrict results to documents in this folder (and its sub-folders). |
None
|
Returns:
| Type | Description |
|---|---|
list[SearchResult]
|
List of :class: |
list[SearchResult]
|
relevance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mode is |
Source code in src/markdown_vault_mcp/collection.py
read(path)
¶
Read the full content of a document from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative document path (e.g. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
NoteContent | None
|
class: |
NoteContent | None
|
if the file does not exist. |
Source code in src/markdown_vault_mcp/collection.py
write(path, content, frontmatter=None, if_match=None)
¶
Create or overwrite a document.
Creates intermediate directories as needed. If frontmatter is provided, it is serialised as a YAML header at the top of the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative document path. |
required |
content
|
str
|
Markdown body (excluding frontmatter). |
required |
frontmatter
|
dict | None
|
Optional frontmatter dict serialised as YAML header. |
None
|
if_match
|
str | None
|
Optional etag from a previous :meth: |
None
|
Returns:
| Type | Description |
|---|---|
WriteResult
|
class: |
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the collection is read-only. |
ConcurrentModificationError
|
If if_match is provided and does not match the current file hash (or the file does not exist). |
ValueError
|
If path escapes the source directory. |
Source code in src/markdown_vault_mcp/collection.py
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 | |
edit(path, old_text, new_text, if_match=None)
¶
Patch a section of a document.
Reads the file, verifies old_text exists exactly once in the full file content (including frontmatter), replaces it with new_text, and writes back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative document path. |
required |
old_text
|
str
|
Text to replace (must appear exactly once). |
required |
new_text
|
str
|
Replacement text. |
required |
if_match
|
str | None
|
Optional etag from a previous :meth: |
None
|
Returns:
| Type | Description |
|---|---|
EditResult
|
class: |
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the collection is read-only. |
DocumentNotFoundError
|
If the file does not exist. |
ConcurrentModificationError
|
If if_match is provided and does not match the current file hash. |
EditConflictError
|
If old_text is not found or appears more than once. |
Source code in src/markdown_vault_mcp/collection.py
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 | |
delete(path, if_match=None)
¶
Delete a document or attachment.
Removes the file from disk. For .md documents, also removes all
FTS and embedding index entries. For attachments, only the file is
deleted (no index update).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative document or attachment path. |
required |
if_match
|
str | None
|
Optional etag from a previous :meth: |
None
|
Returns:
| Type | Description |
|---|---|
DeleteResult
|
class: |
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the collection is read-only. |
DocumentNotFoundError
|
If the file does not exist. |
ConcurrentModificationError
|
If if_match is provided and does not match the current file hash. |
ValueError
|
If the path escapes the source directory, or (for non-.md paths) has an extension not in the attachment allowlist. |
Source code in src/markdown_vault_mcp/collection.py
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 | |
rename(old_path, new_path, if_match=None, *, update_links=False)
¶
Rename or move a document or attachment.
Renames the file on disk. For .md documents, also updates FTS
and embedding index entries. For attachments, only the file is moved
(no index update). Creates intermediate directories for new_path
as needed.
When update_links is True and old_path is a .md document,
every document that links to old_path is also updated so its links
point to new_path. Replacement is best-effort: failures are logged
at WARNING but do not prevent the rename from succeeding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_path
|
str
|
Current relative document or attachment path. |
required |
new_path
|
str
|
Target relative document or attachment path. |
required |
if_match
|
str | None
|
Optional etag from a previous :meth: |
None
|
update_links
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
RenameResult
|
class: |
RenameResult
|
updated_links counting source documents successfully updated. |
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the collection is read-only. |
DocumentNotFoundError
|
If old_path does not exist. |
DocumentExistsError
|
If new_path already exists. |
ConcurrentModificationError
|
If if_match is provided and does not match the current hash of old_path. |
ValueError
|
If either path escapes the source directory, or (for non-.md paths) has an extension not in the attachment allowlist. |
Source code in src/markdown_vault_mcp/collection.py
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 | |
list(*, folder=None, pattern=None, include_attachments=False)
¶
List documents (and optionally attachments) in the collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder
|
str | None
|
If provided, only return documents in this folder (and sub-folders). |
None
|
pattern
|
str | None
|
Unix glob matched against the relative path using
:func: |
None
|
include_attachments
|
bool
|
When |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list[NoteInfo | AttachmentInfo]
|
List of :class: |
|
optionally |
list[NoteInfo | AttachmentInfo]
|
class: |
list[NoteInfo | AttachmentInfo]
|
objects. |
Source code in src/markdown_vault_mcp/collection.py
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 | |
list_folders()
¶
Return all distinct folder values across the indexed collection.
Returns:
| Type | Description |
|---|---|
list[str]
|
Sorted list of folder strings ( |
Source code in src/markdown_vault_mcp/collection.py
list_tags(field='tags')
¶
Return all distinct values indexed for a given frontmatter field.
If field was not in indexed_frontmatter_fields, returns [].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
str
|
Frontmatter key to query (default: |
'tags'
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Sorted list of distinct value strings. |
Source code in src/markdown_vault_mcp/collection.py
stats()
¶
Return collection-wide statistics.
Returns:
| Type | Description |
|---|---|
CollectionStats
|
class: |
Source code in src/markdown_vault_mcp/collection.py
reindex()
¶
Incrementally update the index based on file changes.
Uses :class:~markdown_vault_mcp.tracker.ChangeTracker to detect which
files have been added, modified, or deleted since the last scan.
Only changed files are re-parsed and re-indexed.
Thread-safety: the filesystem scan runs without holding _write_lock
(read-only), then the mutation phase acquires the lock to prevent races
with concurrent write/edit/delete/rename operations.
Returns:
| Type | Description |
|---|---|
ReindexResult
|
class: |
ReindexResult
|
applied. |
Source code in src/markdown_vault_mcp/collection.py
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 | |
build_embeddings(*, force=False)
¶
Build the vector index from all chunks currently in the FTS index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
force
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
int
|
Total number of chunks embedded. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/markdown_vault_mcp/collection.py
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 | |
embeddings_status()
¶
Return status information about the vector index.
Returns:
| Type | Description |
|---|---|
dict
|
Dict with keys |
dict
|
|
Source code in src/markdown_vault_mcp/collection.py
get_toc(path)
¶
Return table of contents for a document.
Queries the FTS sections table for headings and prepends the document title as a synthetic H1 entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative path to the document (e.g. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of |
list[dict[str, Any]]
|
position, with the document title prepended as level 1. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no document exists at the given path. |
Source code in src/markdown_vault_mcp/collection.py
read_attachment(path)
¶
Read the binary content of a non-.md attachment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative attachment path (e.g. |
required |
Returns:
| Type | Description |
|---|---|
AttachmentContent
|
class: |
AttachmentContent
|
base64-encoded content and MIME type. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the path escapes the source directory, has an extension not in the allowlist, or the file does not exist. |
ValueError
|
If the file exceeds the configured size limit. |
Source code in src/markdown_vault_mcp/collection.py
write_attachment(path, content, if_match=None)
¶
Create or overwrite a non-.md attachment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative attachment path (e.g. |
required |
content
|
bytes
|
Raw bytes to write. |
required |
if_match
|
str | None
|
Optional etag from a previous :meth: |
None
|
Returns:
| Type | Description |
|---|---|
WriteResult
|
class: |
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the collection is read-only. |
ConcurrentModificationError
|
If if_match is provided and does not match the current file hash. |
ValueError
|
If the path escapes the source directory, has an extension not in the allowlist, or the content exceeds the size limit. |
Source code in src/markdown_vault_mcp/collection.py
close()
¶
Release resources held by the collection.
Flushes deferred embeddings and pending write callbacks, then closes the SQLite connection and git strategy.