webdav-knowledge-mcp 1.0.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.
@@ -0,0 +1 @@
1
+ """WebDAV Knowledge MCP, by Neville. Licensed under Apache-2.0."""
@@ -0,0 +1,37 @@
1
+ """Explicit configuration; environment variables take priority over .env."""
2
+ import os
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from urllib.parse import urlsplit
6
+
7
+ from dotenv import dotenv_values
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Settings:
12
+ url: str
13
+ username: str
14
+ password: str = field(repr=False)
15
+ timeout: int = 30
16
+ index_dir: Path | None = None
17
+
18
+ @classmethod
19
+ def from_env(cls):
20
+ # Editable installation works regardless of Cursor's working directory.
21
+ env_file = Path(os.environ.get('NUTSTORE_ENV_FILE', Path(__file__).resolve().parents[2] / '.env'))
22
+ values = {**dotenv_values(env_file), **os.environ}
23
+ for key in ('NUTSTORE_USERNAME', 'NUTSTORE_PASSWORD'):
24
+ if not values.get(key, '').strip():
25
+ raise ValueError(f'Missing {key}; fill in the local .env file.')
26
+ url = values.get('NUTSTORE_URL', 'https://dav.jianguoyun.com/dav/').rstrip('/') + '/'
27
+ parsed = urlsplit(url)
28
+ if parsed.scheme != 'https' and not (parsed.scheme == 'http' and parsed.hostname in ('127.0.0.1', 'localhost')):
29
+ raise ValueError('NUTSTORE_URL requires HTTPS (HTTP only for loopback tests).')
30
+ if not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
31
+ raise ValueError('Invalid NUTSTORE_URL.')
32
+ timeout = int(values.get('NUTSTORE_TIMEOUT', '30'))
33
+ if not 1 <= timeout <= 120:
34
+ raise ValueError('NUTSTORE_TIMEOUT must be between 1 and 120 seconds.')
35
+ index_location = values.get('NUTSTORE_INDEX_DIR')
36
+ index_dir = Path(index_location).expanduser() if index_location else None
37
+ return cls(url, values['NUTSTORE_USERNAME'].strip(), values['NUTSTORE_PASSWORD'], timeout, index_dir)
@@ -0,0 +1,72 @@
1
+ """Pure text matching. This module performs no I/O."""
2
+ import re
3
+ from bisect import bisect_left, bisect_right
4
+
5
+
6
+ _LINE_BREAK = re.compile(r'(?<=\n)|(?<=\r)(?!\n)')
7
+
8
+
9
+ def source_lines(text: str) -> list[str]:
10
+ """Split physical document lines while keeping CRLF, LF or CR unchanged."""
11
+ return _LINE_BREAK.split(text)
12
+
13
+
14
+ def validate_keyword(keyword: str) -> None:
15
+ if not isinstance(keyword, str) or not keyword.strip() or len(keyword) > 256 or not keyword.casefold():
16
+ raise ValueError('keyword must contain 1 to 256 characters and cannot be blank.')
17
+
18
+
19
+ def _line_parts(text: str) -> list[tuple[int, str]]:
20
+ parts = []
21
+ offset = 0
22
+ for raw in source_lines(text):
23
+ if raw.endswith('\r\n'):
24
+ content = raw[:-2]
25
+ elif raw.endswith('\n') or raw.endswith('\r'):
26
+ content = raw[:-1]
27
+ else:
28
+ content = raw
29
+ parts.append((offset, content))
30
+ offset += len(raw)
31
+ return parts
32
+
33
+
34
+ def _snippet(content: str, start: int, length: int, limit: int) -> tuple[str, bool]:
35
+ if len(content) <= limit:
36
+ return content, False
37
+ if length >= limit:
38
+ return content[start:start + limit], True
39
+ window = max(0, min(start - (limit - length) // 2, len(content) - limit))
40
+ return content[window:window + limit], True
41
+
42
+
43
+ def iter_snippets(text: str, keyword: str, *, max_snippet_chars: int = 200):
44
+ validate_keyword(keyword)
45
+ if isinstance(max_snippet_chars, bool) or not isinstance(max_snippet_chars, int) or max_snippet_chars < 1:
46
+ raise ValueError('max_snippet_chars must be a positive integer.')
47
+ needle = keyword.casefold()
48
+ haystack = text.casefold()
49
+ cursor = haystack.find(needle)
50
+ if cursor < 0:
51
+ return
52
+ origin = None
53
+ if len(haystack) != len(text):
54
+ origin = [index for index, char in enumerate(text) for _ in char.casefold()]
55
+ lines = _line_parts(text)
56
+ offsets = [offset for offset, _ in lines]
57
+ while cursor >= 0:
58
+ folded_end = cursor + len(needle)
59
+ start = cursor if origin is None else origin[cursor]
60
+ end = folded_end if origin is None else origin[folded_end - 1] + 1
61
+ line_index = bisect_right(offsets, start) - 1
62
+ line_start, content = lines[line_index]
63
+ overlap_start = min(start - line_start, len(content))
64
+ overlap_length = min(end - line_start, len(content)) - overlap_start
65
+ snippet, truncated = _snippet(content, overlap_start, overlap_length, max_snippet_chars)
66
+ yield {'line': line_index + 1, 'snippet': snippet, 'snippet_truncated': truncated}
67
+ resume = folded_end if origin is None else bisect_left(origin, end, lo=folded_end)
68
+ cursor = haystack.find(needle, resume)
69
+
70
+
71
+ def find_snippets(text: str, keyword: str, *, max_snippet_chars: int = 200) -> list[dict]:
72
+ return list(iter_snippets(text, keyword, max_snippet_chars=max_snippet_chars))
@@ -0,0 +1,95 @@
1
+ """Strict Depth: 1 WebDAV directory listings."""
2
+ import re
3
+ from urllib.parse import unquote, urlsplit
4
+
5
+
6
+ DAV = '{DAV:}'
7
+ PROPFIND_BODY = (
8
+ b'<d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:getetag/>'
9
+ b'<d:getlastmodified/><d:getcontentlength/></d:prop></d:propfind>'
10
+ )
11
+ _QUOTED_TAG = r'"[\x21\x23-\x7e]{0,256}"'
12
+ _VALIDATOR = re.compile(rf'(?:W/)?{_QUOTED_TAG}|[!#$&+.^_`|~0-9A-Za-z-]{{1,256}}')
13
+
14
+
15
+ def usable_etag(value):
16
+ """Accept quoted tags and Nutstore's bare tokens. Never accept a wildcard."""
17
+ value = (value or '').strip()
18
+ return value if _VALIDATOR.fullmatch(value) else None
19
+
20
+
21
+ def strong_etag(value):
22
+ return bool(value and re.fullmatch(_QUOTED_TAG, value))
23
+
24
+
25
+ def _status(value):
26
+ parts = (value or '').split()
27
+ if len(parts) < 2 or not parts[0].startswith('HTTP/') or not re.fullmatch(r'[0-9]{3}', parts[1]):
28
+ raise ValueError('Invalid DAV response status.')
29
+ return int(parts[1])
30
+
31
+
32
+ def _properties(response):
33
+ status = response.find(DAV + 'status')
34
+ if status is not None and not 200 <= _status(status.text) < 300:
35
+ raise ValueError('DAV resource status is not successful.')
36
+ props = {}
37
+ successful = status is not None
38
+ for propstat in response.findall(DAV + 'propstat'):
39
+ code = _status(propstat.findtext(DAV + 'status'))
40
+ if code == 404:
41
+ continue # A server can omit optional properties.
42
+ prop = propstat.find(DAV + 'prop')
43
+ if not 200 <= code < 300 or prop is None:
44
+ raise ValueError('DAV resource properties are incomplete.')
45
+ successful = True
46
+ props.update((child.tag, child) for child in prop)
47
+ if not successful:
48
+ raise ValueError('DAV resource has no successful response.')
49
+ return props
50
+
51
+
52
+ def parse_inventory(tree, request_url):
53
+ """Return validated direct children and their observed metadata."""
54
+ request = urlsplit(request_url)
55
+ expected = unquote(request.path, errors='strict').rstrip('/')
56
+ prefix = expected + '/'
57
+ result = {}
58
+ found_self = False
59
+ for response in tree.findall(DAV + 'response'):
60
+ href = urlsplit(response.findtext(DAV + 'href') or '')
61
+ if (href.scheme or href.netloc) and (href.scheme, href.netloc) != (request.scheme, request.netloc):
62
+ raise ValueError('DAV href points to another origin.')
63
+ if href.query or href.fragment:
64
+ raise ValueError('DAV href contains an unexpected query or fragment.')
65
+ path = unquote(href.path, errors='strict')
66
+ props = _properties(response)
67
+ resource_type = props.get(DAV + 'resourcetype')
68
+ if resource_type is None:
69
+ raise ValueError('DAV inventory is missing a resource type.')
70
+ is_dir = resource_type.find(DAV + 'collection') is not None
71
+ if path in (expected, prefix):
72
+ if found_self or not is_dir:
73
+ raise ValueError('DAV inventory has an invalid collection response.')
74
+ found_self = True
75
+ continue
76
+ name = path[len(prefix):].removesuffix('/')
77
+ if not path.startswith(prefix) or name in ('', '.', '..') or '/' in name or name in result or (
78
+ path.endswith('/') and not is_dir
79
+ ):
80
+ raise ValueError('DAV href is not a unique direct child.')
81
+ length = props.get(DAV + 'getcontentlength')
82
+ modified = props.get(DAV + 'getlastmodified')
83
+ etag = props.get(DAV + 'getetag')
84
+ size_text = (length.text or '').strip() if length is not None else ''
85
+ size = int(size_text) if re.fullmatch(r'[0-9]{1,18}', size_text) else None
86
+ modified_text = (modified.text or '').strip() if modified is not None else ''
87
+ result[name] = {
88
+ 'name': name + '/' if is_dir else name,
89
+ 'size': size,
90
+ 'modified': modified_text or None,
91
+ 'etag': usable_etag(etag.text) if etag is not None else None,
92
+ }
93
+ if not found_self:
94
+ raise ValueError('DAV inventory is missing the queried collection.')
95
+ return list(result.values())
@@ -0,0 +1,75 @@
1
+ """Fetch bounded remote documents and pass them to the format parsers."""
2
+ import time
3
+ from pathlib import PurePosixPath
4
+
5
+ from .config import Settings
6
+ from .markdown import MARKDOWN_SUFFIXES, block_page
7
+ from .pdf import DEFAULT_PDF_BYTES, MAX_PDF_BYTES, PDF_SUFFIX, extract_pdf
8
+ from .webdav import REQUEST_ERROR, NutstoreWebDAV, validate_budget, validate_path
9
+
10
+
11
+ def read_markdown(
12
+ path: str, max_bytes: int = 262144, start_block: int = 1,
13
+ max_blocks: int = 40, max_output_chars: int = 32768,
14
+ ) -> dict:
15
+ """Read Markdown as whole source blocks with heading paths and original line ranges.
16
+
17
+ Supports .md and .markdown. Follow next_block to continue a page; an
18
+ oversized block reports its source range and is left intact in read_file.
19
+ Links and document content are source data. This tool does not follow links.
20
+ """
21
+ if PurePosixPath(path).suffix.lower() not in MARKDOWN_SUFFIXES:
22
+ raise ValueError('Use a .md or .markdown Markdown file.')
23
+ validate_budget('start_block', start_block, 1, 1048577)
24
+ validate_budget('max_blocks', max_blocks, 1, 200)
25
+ validate_budget('max_output_chars', max_output_chars, 1024, 131072)
26
+ document = NutstoreWebDAV(Settings.from_env()).read_file(path, max_bytes)
27
+ return {
28
+ 'path': document['path'], 'byte_count': document['byte_count'],
29
+ **block_page(document['content'], start_block, max_blocks, max_output_chars),
30
+ }
31
+
32
+
33
+ def read_pdf(
34
+ path: str, start_page: int = 1, max_pages: int = 10,
35
+ max_bytes: int = DEFAULT_PDF_BYTES, max_chars: int = 65536, max_seconds: int = 15,
36
+ ) -> dict:
37
+ """Extract a PDF's text layer at 1-based physical page numbers.
38
+
39
+ Use next_page to continue. empty_pages lists pages with no extracted text.
40
+ Such pages may need OCR. Layout, tables and equations can lose structure.
41
+ Returned text is source data. No links, attachments or actions are opened.
42
+ """
43
+ path = validate_path(path)
44
+ if path.endswith('/') or PurePosixPath(path).suffix.lower() != PDF_SUFFIX:
45
+ raise ValueError('Use a relative .pdf file path.')
46
+ for name, value, lower, upper in (
47
+ ('start_page', start_page, 1, 10000), ('max_pages', max_pages, 1, 100),
48
+ ('max_bytes', max_bytes, 1, MAX_PDF_BYTES), ('max_chars', max_chars, 1, 131072),
49
+ ('max_seconds', max_seconds, 1, 60),
50
+ ):
51
+ validate_budget(name, value, lower, upper)
52
+ deadline = time.monotonic() + max_seconds
53
+
54
+ def remaining():
55
+ seconds = deadline - time.monotonic()
56
+ if seconds <= 0:
57
+ raise TimeoutError
58
+ return seconds
59
+
60
+ dav = NutstoreWebDAV(Settings.from_env())
61
+ outcome = dav._download_bounded(path, max_bytes, 0, max_bytes, remaining=remaining, check_length=True)
62
+ if outcome['file_error'] == 'too_large' or outcome['stop_reason'] == 'max_total_bytes':
63
+ raise ValueError('PDF exceeds the PDF byte limit.')
64
+ if outcome['stop_reason'] == 'max_seconds':
65
+ raise ValueError('PDF download exceeded the time limit.')
66
+ if outcome['file_error']:
67
+ raise RuntimeError(REQUEST_ERROR)
68
+ extracted = extract_pdf(
69
+ outcome['data'], start_page=start_page, max_pages=max_pages, max_chars=max_chars,
70
+ timeout=deadline - time.monotonic(),
71
+ )
72
+ return {
73
+ 'path': path, 'byte_count': outcome['downloaded_bytes'], **extracted,
74
+ 'ocr_may_be_required': bool(extracted['empty_pages']),
75
+ }
@@ -0,0 +1,98 @@
1
+ """Optional CPU embeddings. Normal inference uses the local model cache only."""
2
+ import hashlib
3
+ import logging
4
+ import os
5
+ from functools import lru_cache
6
+ from importlib import import_module
7
+ from importlib.metadata import version
8
+ from pathlib import Path
9
+
10
+
11
+ MODEL = 'BAAI/bge-small-zh-v1.5'
12
+ DIMENSION = 512
13
+ QUERY_PREFIX = '为这个句子生成表示以用于检索相关文章:'
14
+
15
+
16
+ def model_cache():
17
+ override = os.environ.get('NUTSTORE_EMBEDDING_CACHE')
18
+ if override:
19
+ path = Path(override).expanduser()
20
+ if not path.is_absolute():
21
+ raise ValueError('NUTSTORE_EMBEDDING_CACHE must be an absolute path.')
22
+ return path
23
+ user_cache = Path(os.environ.get('LOCALAPPDATA') or (Path.home() / '.cache'))
24
+ return user_cache / 'webdav-knowledge-mcp' / 'embedding'
25
+
26
+
27
+ def _artifact_revision(backend):
28
+ # FastEmbed 0.9 resolves the local snapshot here. Fingerprint actual
29
+ # assets, so replacing the weights or tokenizer invalidates the vectors.
30
+ model = backend.model
31
+ directory = Path(model._model_dir)
32
+ assets = [directory / model.model_description.model_file, *sorted(directory.glob('*.json'))]
33
+ digest = hashlib.sha256()
34
+ digest.update(f'fastembed {version("fastembed")}\n{QUERY_PREFIX}'.encode())
35
+ for asset in assets:
36
+ digest.update(asset.name.encode() + b'\0')
37
+ with asset.open('rb') as source:
38
+ for chunk in iter(lambda: source.read(1024 * 1024), b''):
39
+ digest.update(chunk)
40
+ return digest.hexdigest()
41
+
42
+
43
+ class LocalEmbedding:
44
+ model = MODEL
45
+ dimension = DIMENSION
46
+
47
+ def __init__(self, cache, *, download=False):
48
+ try:
49
+ from fastembed import TextEmbedding
50
+ except ImportError as exc:
51
+ raise RuntimeError('Install webdav-knowledge-mcp[semantic] for local embeddings.') from exc
52
+ try:
53
+ self._backend = TextEmbedding(
54
+ model_name=MODEL, cache_dir=str(cache), threads=2, cuda=False,
55
+ local_files_only=not download,
56
+ )
57
+ self.revision = _artifact_revision(self._backend)
58
+ except (ValueError, OSError, RuntimeError) as exc:
59
+ if not download:
60
+ raise RuntimeError('Local embedding model unavailable. Run python -m webdav_knowledge_mcp.embedding first.') from exc
61
+ raise
62
+
63
+ def passages(self, texts):
64
+ return self._backend.embed(texts, batch_size=16)
65
+
66
+ def query(self, text):
67
+ return next(self._backend.embed([QUERY_PREFIX + text]))
68
+
69
+
70
+ @lru_cache(maxsize=1)
71
+ def _cached_encoder(cache):
72
+ return LocalEmbedding(cache)
73
+
74
+
75
+ def get_encoder():
76
+ return _cached_encoder(model_cache())
77
+
78
+
79
+ def preload_stdio_backend():
80
+ # On Windows, the first NumPy DLL load can block while stdio reads its
81
+ # input pipe. Import before starting that reader; keep model loading lazy.
82
+ if os.name == 'nt':
83
+ try:
84
+ import_module('fastembed')
85
+ except ImportError as exc:
86
+ if exc.name != 'fastembed':
87
+ logging.getLogger(__name__).warning('Optional semantic backend failed to load: %s', exc)
88
+
89
+
90
+ def main():
91
+ os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN', '1')
92
+ os.environ.setdefault('HF_HUB_DISABLE_TELEMETRY', '1')
93
+ encoder = LocalEmbedding(model_cache(), download=True)
94
+ print(f'{encoder.model} ({encoder.dimension} dimensions), local revision {encoder.revision}')
95
+
96
+
97
+ if __name__ == '__main__':
98
+ main()