python-docs-mcp-server 0.1.2__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.
- mcp_server_python_docs/__init__.py +17 -0
- mcp_server_python_docs/__main__.py +574 -0
- mcp_server_python_docs/app_context.py +33 -0
- mcp_server_python_docs/data/synonyms.yaml +194 -0
- mcp_server_python_docs/detection.py +82 -0
- mcp_server_python_docs/diagnostics.py +74 -0
- mcp_server_python_docs/errors.py +33 -0
- mcp_server_python_docs/ingestion/__init__.py +1 -0
- mcp_server_python_docs/ingestion/cpython_versions.py +32 -0
- mcp_server_python_docs/ingestion/inventory.py +178 -0
- mcp_server_python_docs/ingestion/publish.py +504 -0
- mcp_server_python_docs/ingestion/sphinx_json.py +617 -0
- mcp_server_python_docs/models.py +216 -0
- mcp_server_python_docs/py.typed +0 -0
- mcp_server_python_docs/retrieval/__init__.py +31 -0
- mcp_server_python_docs/retrieval/budget.py +63 -0
- mcp_server_python_docs/retrieval/query.py +183 -0
- mcp_server_python_docs/retrieval/ranker.py +369 -0
- mcp_server_python_docs/server.py +329 -0
- mcp_server_python_docs/services/__init__.py +7 -0
- mcp_server_python_docs/services/cache.py +111 -0
- mcp_server_python_docs/services/content.py +155 -0
- mcp_server_python_docs/services/observability.py +130 -0
- mcp_server_python_docs/services/package_docs.py +161 -0
- mcp_server_python_docs/services/persistent_cache.py +147 -0
- mcp_server_python_docs/services/search.py +111 -0
- mcp_server_python_docs/services/version.py +47 -0
- mcp_server_python_docs/services/version_resolution.py +79 -0
- mcp_server_python_docs/storage/__init__.py +1 -0
- mcp_server_python_docs/storage/db.py +146 -0
- mcp_server_python_docs/storage/schema.sql +136 -0
- python_docs_mcp_server-0.1.2.dist-info/METADATA +528 -0
- python_docs_mcp_server-0.1.2.dist-info/RECORD +36 -0
- python_docs_mcp_server-0.1.2.dist-info/WHEEL +4 -0
- python_docs_mcp_server-0.1.2.dist-info/entry_points.txt +3 -0
- python_docs_mcp_server-0.1.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Pydantic input/output models for all MCP tools.
|
|
2
|
+
|
|
3
|
+
These models define the tool contracts. FastMCP auto-generates outputSchema
|
|
4
|
+
from BaseModel return types, providing structuredContent for free (SRVR-05).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
# --- search_docs models ---
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SearchDocsInput(BaseModel):
|
|
16
|
+
"""Input parameters for search_docs tool."""
|
|
17
|
+
|
|
18
|
+
query: str = Field(
|
|
19
|
+
max_length=500,
|
|
20
|
+
description="Search query - Python symbol (asyncio.TaskGroup) or concept (parse json)",
|
|
21
|
+
)
|
|
22
|
+
version: str | None = Field(
|
|
23
|
+
default=None,
|
|
24
|
+
description="Python version (e.g. '3.13'). Defaults to latest.",
|
|
25
|
+
)
|
|
26
|
+
kind: Literal["auto", "page", "symbol", "section", "example"] = Field(
|
|
27
|
+
default="auto",
|
|
28
|
+
description=(
|
|
29
|
+
"Search type. Use 'symbol' for API lookups, "
|
|
30
|
+
"'example' for code samples, 'auto' otherwise."
|
|
31
|
+
),
|
|
32
|
+
)
|
|
33
|
+
max_results: int = Field(
|
|
34
|
+
default=5,
|
|
35
|
+
ge=1,
|
|
36
|
+
le=20,
|
|
37
|
+
description="Maximum number of results to return.",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SymbolHit(BaseModel):
|
|
42
|
+
"""A single search result hit."""
|
|
43
|
+
|
|
44
|
+
uri: str = Field(description="Documentation URI path")
|
|
45
|
+
title: str = Field(description="Display title")
|
|
46
|
+
kind: str = Field(description="Hit type: class, function, method, module, etc.")
|
|
47
|
+
snippet: str = Field(default="", description="Brief excerpt or description")
|
|
48
|
+
score: float = Field(default=0.0, description="Relevance score")
|
|
49
|
+
version: str = Field(description="Python version this hit belongs to")
|
|
50
|
+
slug: str = Field(default="", description="Page slug for get_docs follow-up")
|
|
51
|
+
anchor: str | None = Field(
|
|
52
|
+
default=None,
|
|
53
|
+
description="Section anchor for get_docs follow-up; None for page-level hits",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SearchDocsResult(BaseModel):
|
|
58
|
+
"""Output from search_docs tool."""
|
|
59
|
+
|
|
60
|
+
hits: list[SymbolHit] = Field(
|
|
61
|
+
default_factory=list,
|
|
62
|
+
description="Search result hits",
|
|
63
|
+
)
|
|
64
|
+
note: str | None = Field(
|
|
65
|
+
default=None,
|
|
66
|
+
description="Informational note (e.g., limited search mode)",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# --- get_docs models ---
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class GetDocsInput(BaseModel):
|
|
74
|
+
"""Input parameters for get_docs tool."""
|
|
75
|
+
|
|
76
|
+
slug: str = Field(
|
|
77
|
+
max_length=500,
|
|
78
|
+
description="Page slug (e.g. 'library/asyncio-task.html')",
|
|
79
|
+
)
|
|
80
|
+
version: str | None = Field(
|
|
81
|
+
default=None,
|
|
82
|
+
description="Python version. Defaults to latest.",
|
|
83
|
+
)
|
|
84
|
+
anchor: str | None = Field(
|
|
85
|
+
default=None,
|
|
86
|
+
description="Section anchor for section-only retrieval",
|
|
87
|
+
)
|
|
88
|
+
max_chars: int = Field(
|
|
89
|
+
default=8000,
|
|
90
|
+
ge=100,
|
|
91
|
+
le=50000,
|
|
92
|
+
description="Maximum characters to return",
|
|
93
|
+
)
|
|
94
|
+
start_index: int = Field(
|
|
95
|
+
default=0,
|
|
96
|
+
ge=0,
|
|
97
|
+
description="Start position for pagination",
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class GetDocsResult(BaseModel):
|
|
102
|
+
"""Output from get_docs tool."""
|
|
103
|
+
|
|
104
|
+
content: str = Field(description="Documentation content in markdown")
|
|
105
|
+
slug: str = Field(description="Page slug")
|
|
106
|
+
title: str = Field(description="Page or section title")
|
|
107
|
+
version: str = Field(description="Python version")
|
|
108
|
+
anchor: str | None = Field(
|
|
109
|
+
default=None,
|
|
110
|
+
description="Section anchor if section-level",
|
|
111
|
+
)
|
|
112
|
+
char_count: int = Field(description="Total character count of full content")
|
|
113
|
+
truncated: bool = Field(
|
|
114
|
+
default=False,
|
|
115
|
+
description="Whether content was truncated",
|
|
116
|
+
)
|
|
117
|
+
next_start_index: int | None = Field(
|
|
118
|
+
default=None,
|
|
119
|
+
description="Next start_index for pagination, if truncated",
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# --- list_versions models ---
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class VersionInfo(BaseModel):
|
|
127
|
+
"""Information about an available Python version."""
|
|
128
|
+
|
|
129
|
+
version: str = Field(description="Python version string (e.g. '3.13')")
|
|
130
|
+
language: str = Field(default="en", description="Documentation language")
|
|
131
|
+
label: str = Field(description="Display label")
|
|
132
|
+
is_default: bool = Field(description="Whether this is the default version")
|
|
133
|
+
built_at: str = Field(description="When this version's index was built")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class ListVersionsResult(BaseModel):
|
|
137
|
+
"""Output from list_versions tool."""
|
|
138
|
+
|
|
139
|
+
versions: list[VersionInfo] = Field(
|
|
140
|
+
description="Available documentation versions",
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# --- detect_python_version models ---
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class DetectPythonVersionResult(BaseModel):
|
|
148
|
+
"""Output from detect_python_version tool."""
|
|
149
|
+
|
|
150
|
+
detected_version: str = Field(
|
|
151
|
+
description="Python major.minor detected from the user's environment (e.g. '3.13')"
|
|
152
|
+
)
|
|
153
|
+
source: str = Field(
|
|
154
|
+
description=(
|
|
155
|
+
"How the version was detected: '.python-version file',"
|
|
156
|
+
" 'python3 in PATH', or 'server runtime'"
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
matched_index_version: str | None = Field(
|
|
160
|
+
default=None,
|
|
161
|
+
description="The detected version if it matches an indexed doc set, otherwise null",
|
|
162
|
+
)
|
|
163
|
+
is_default: bool = Field(
|
|
164
|
+
description="Whether this detected version is being used as the default for get_docs"
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# --- lookup_package_docs models ---
|
|
169
|
+
|
|
170
|
+
# Bounded kind vocabulary: hardcoded values from `_source` calls plus the
|
|
171
|
+
# normalized members of `_ALLOWED` (with spaces → underscores) in
|
|
172
|
+
# services/package_docs.py. Keep these in sync.
|
|
173
|
+
PackageKind = Literal[
|
|
174
|
+
"pypi",
|
|
175
|
+
"docs",
|
|
176
|
+
"documentation",
|
|
177
|
+
"homepage",
|
|
178
|
+
"home_page",
|
|
179
|
+
"source",
|
|
180
|
+
"source_code",
|
|
181
|
+
"repository",
|
|
182
|
+
"repo",
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class PackageDocsSource(BaseModel):
|
|
187
|
+
"""A package-declared documentation or project source URL."""
|
|
188
|
+
|
|
189
|
+
label: str = Field(description="Label from PyPI metadata or a normalized core metadata field")
|
|
190
|
+
url: str = Field(description="HTTP(S) URL declared by the package on PyPI")
|
|
191
|
+
kind: PackageKind = Field(
|
|
192
|
+
description="Source category: pypi, docs, documentation, homepage, home_page, "
|
|
193
|
+
"source, source_code, repository, or repo"
|
|
194
|
+
)
|
|
195
|
+
declared_by: str = Field(description="Where this source declaration came from")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class PackageDocsResult(BaseModel):
|
|
199
|
+
"""Output from lookup_package_docs tool."""
|
|
200
|
+
|
|
201
|
+
package: str = Field(description="Canonical package name returned by PyPI when available")
|
|
202
|
+
version: str = Field(description="Latest version reported by PyPI metadata")
|
|
203
|
+
summary: str = Field(default="", description="Package summary from PyPI metadata")
|
|
204
|
+
metadata_source: str = Field(description="Official PyPI JSON API URL used for lookup")
|
|
205
|
+
trust_boundary: Literal["pypi-declared-metadata"] = Field(
|
|
206
|
+
default="pypi-declared-metadata",
|
|
207
|
+
description="Indicates results are limited to PyPI/project-declared metadata",
|
|
208
|
+
)
|
|
209
|
+
sources: list[PackageDocsSource] = Field(
|
|
210
|
+
default_factory=list,
|
|
211
|
+
description="Package-declared PyPI, documentation, homepage, and source URLs",
|
|
212
|
+
)
|
|
213
|
+
note: str | None = Field(
|
|
214
|
+
default=None,
|
|
215
|
+
description="Controlled-scope note, for example skipped labels or not-found details",
|
|
216
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Retrieval layer -- pure-logic query processing, ranking, and budget enforcement.
|
|
2
|
+
|
|
3
|
+
No MCP types, no storage imports. Receives connections and data as parameters.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from mcp_server_python_docs.retrieval.budget import apply_budget
|
|
8
|
+
from mcp_server_python_docs.retrieval.query import (
|
|
9
|
+
build_match_expression,
|
|
10
|
+
classify_query,
|
|
11
|
+
expand_synonyms,
|
|
12
|
+
fts5_escape,
|
|
13
|
+
)
|
|
14
|
+
from mcp_server_python_docs.retrieval.ranker import (
|
|
15
|
+
lookup_symbols_exact,
|
|
16
|
+
search_examples,
|
|
17
|
+
search_sections,
|
|
18
|
+
search_symbols,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"apply_budget",
|
|
23
|
+
"build_match_expression",
|
|
24
|
+
"classify_query",
|
|
25
|
+
"expand_synonyms",
|
|
26
|
+
"fts5_escape",
|
|
27
|
+
"lookup_symbols_exact",
|
|
28
|
+
"search_examples",
|
|
29
|
+
"search_sections",
|
|
30
|
+
"search_symbols",
|
|
31
|
+
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Unicode-safe budget enforcement for content truncation.
|
|
2
|
+
|
|
3
|
+
The single function apply_budget() handles all truncation and pagination
|
|
4
|
+
for content-returning tools. It guarantees:
|
|
5
|
+
- Never splits a Unicode codepoint (Python 3 str slicing is codepoint-safe)
|
|
6
|
+
- Never splits a base character from its combining marks
|
|
7
|
+
- Returns truncation flag and next_start_index for pagination
|
|
8
|
+
|
|
9
|
+
Pure logic -- no MCP types, no storage imports.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import unicodedata
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def apply_budget(
|
|
17
|
+
text: str,
|
|
18
|
+
max_chars: int,
|
|
19
|
+
start_index: int = 0,
|
|
20
|
+
) -> tuple[str, bool, int | None]:
|
|
21
|
+
"""Apply character budget with Unicode-safe truncation (RETR-08).
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
text: Full text content to truncate.
|
|
25
|
+
max_chars: Maximum characters to return. Must be positive for
|
|
26
|
+
meaningful results.
|
|
27
|
+
start_index: Starting position for pagination (codepoint offset).
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
Tuple of (truncated_text, is_truncated, next_start_index).
|
|
31
|
+
next_start_index is None when not truncated (all remaining text fits).
|
|
32
|
+
"""
|
|
33
|
+
if not text or max_chars <= 0:
|
|
34
|
+
return ("", False, None)
|
|
35
|
+
|
|
36
|
+
if start_index >= len(text):
|
|
37
|
+
return ("", False, None)
|
|
38
|
+
|
|
39
|
+
remaining = text[start_index:]
|
|
40
|
+
|
|
41
|
+
if len(remaining) <= max_chars:
|
|
42
|
+
return (remaining, False, None)
|
|
43
|
+
|
|
44
|
+
# Truncate at max_chars boundary
|
|
45
|
+
end = start_index + max_chars
|
|
46
|
+
|
|
47
|
+
# Back up past any combining marks (Unicode category M: Mn, Mc, Me)
|
|
48
|
+
# so we don't separate a base character from its diacritics
|
|
49
|
+
while end > start_index and unicodedata.category(text[end - 1]).startswith("M"):
|
|
50
|
+
end -= 1
|
|
51
|
+
|
|
52
|
+
# If we backed up to start_index (edge case: all combining marks),
|
|
53
|
+
# advance to include at least the base char + its marks
|
|
54
|
+
if end == start_index and start_index < len(text):
|
|
55
|
+
end = start_index + 1
|
|
56
|
+
while end < len(text) and unicodedata.category(text[end]).startswith("M"):
|
|
57
|
+
end += 1
|
|
58
|
+
|
|
59
|
+
result = text[start_index:end]
|
|
60
|
+
truncated = end < len(text)
|
|
61
|
+
next_idx = end if truncated else None
|
|
62
|
+
|
|
63
|
+
return (result, truncated, next_idx)
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Query processing for FTS5 search.
|
|
2
|
+
|
|
3
|
+
Provides FTS5 escape, query classification, and synonym expansion.
|
|
4
|
+
Pure logic -- no MCP types, no storage imports.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
# Pattern for single-word Python module names (e.g., re, os, sys, io)
|
|
13
|
+
_MODULE_PATTERN = re.compile(r"^[a-z_][a-z0-9_]*$")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def fts5_escape(query: str) -> str:
|
|
17
|
+
"""Escape user input for safe FTS5 MATCH queries (RETR-01).
|
|
18
|
+
|
|
19
|
+
Wraps every whitespace-separated token in double quotes to prevent
|
|
20
|
+
FTS5 operators (AND, OR, NOT, NEAR), prefix matching (*), column
|
|
21
|
+
filters (:), grouping (parens), and negation (-) from being
|
|
22
|
+
interpreted.
|
|
23
|
+
|
|
24
|
+
Inside FTS5 double quotes, the only special char is the double quote
|
|
25
|
+
itself, which is escaped by doubling ("").
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
query: Raw user input string.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
Escaped string safe for FTS5 MATCH. Empty/whitespace input
|
|
32
|
+
returns '""' (matches nothing, does not crash).
|
|
33
|
+
"""
|
|
34
|
+
# Strip null bytes and other control characters that crash FTS5
|
|
35
|
+
query = query.replace("\x00", "").strip()
|
|
36
|
+
if not query:
|
|
37
|
+
return '""'
|
|
38
|
+
tokens = query.split()
|
|
39
|
+
escaped = []
|
|
40
|
+
for token in tokens:
|
|
41
|
+
# Strip null bytes from individual tokens too
|
|
42
|
+
token = token.replace("\x00", "")
|
|
43
|
+
if not token:
|
|
44
|
+
continue
|
|
45
|
+
# Escape internal double quotes by doubling them
|
|
46
|
+
safe = token.replace('"', '""')
|
|
47
|
+
# Wrap every token in double quotes
|
|
48
|
+
escaped.append(f'"{safe}"')
|
|
49
|
+
return " ".join(escaped) if escaped else '""'
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def classify_query(
|
|
53
|
+
query: str,
|
|
54
|
+
symbol_exists_fn: Callable[[str], bool],
|
|
55
|
+
) -> Literal["symbol", "fts"]:
|
|
56
|
+
"""Classify whether a query should use symbol fast-path or FTS5 (RETR-04).
|
|
57
|
+
|
|
58
|
+
Symbol-shaped queries are routed to the objects.inv symbol table
|
|
59
|
+
for direct lookup, skipping FTS5 entirely.
|
|
60
|
+
|
|
61
|
+
A query is symbol-shaped if:
|
|
62
|
+
1. It contains a dot (e.g., asyncio.TaskGroup, os.path.join)
|
|
63
|
+
2. It matches the lowercase identifier pattern AND exists in
|
|
64
|
+
the symbol table (prevents false positives on words like
|
|
65
|
+
"test", "list")
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
query: User search query.
|
|
69
|
+
symbol_exists_fn: Callback that checks if a name exists in the
|
|
70
|
+
symbols table. Injected by the service layer to avoid
|
|
71
|
+
importing storage.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
"symbol" for symbol fast-path, "fts" for full-text search.
|
|
75
|
+
"""
|
|
76
|
+
query = query.strip()
|
|
77
|
+
if not query:
|
|
78
|
+
return "fts"
|
|
79
|
+
# Dotted names are always symbol-shaped
|
|
80
|
+
if "." in query:
|
|
81
|
+
return "symbol"
|
|
82
|
+
# Single-word module names (re, os, sys) -- only if they exist
|
|
83
|
+
# in the symbol table to avoid false positives
|
|
84
|
+
if _MODULE_PATTERN.match(query) and symbol_exists_fn(query):
|
|
85
|
+
return "symbol"
|
|
86
|
+
return "fts"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _build_concept_patterns(
|
|
90
|
+
synonyms: dict[str, list[str]],
|
|
91
|
+
) -> dict[str, re.Pattern[str]]:
|
|
92
|
+
"""Pre-compile word-boundary regex patterns for multi-word synonym concepts."""
|
|
93
|
+
patterns: dict[str, re.Pattern[str]] = {}
|
|
94
|
+
for concept in synonyms:
|
|
95
|
+
if " " in concept:
|
|
96
|
+
patterns[concept] = re.compile(r"\b" + re.escape(concept) + r"\b")
|
|
97
|
+
return patterns
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def expand_synonyms(
|
|
101
|
+
query: str,
|
|
102
|
+
synonyms: dict[str, list[str]],
|
|
103
|
+
*,
|
|
104
|
+
_concept_patterns: dict[str, re.Pattern[str]] | None = None,
|
|
105
|
+
) -> set[str]:
|
|
106
|
+
"""Expand query using synonym table for concept search (RETR-05).
|
|
107
|
+
|
|
108
|
+
Checks each token and multi-word phrases against the synonym table.
|
|
109
|
+
Single-word concepts use exact token matching. Multi-word concepts
|
|
110
|
+
use word-boundary regex to avoid substring false positives (CR-01).
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
query: User search query.
|
|
114
|
+
synonyms: Mapping of concept -> list of expansion terms.
|
|
115
|
+
Loaded from synonyms.yaml at startup.
|
|
116
|
+
_concept_patterns: Pre-compiled regex patterns for multi-word
|
|
117
|
+
concepts. Built lazily on first call if not provided.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
Set of terms (original + expansions). Empty set if query
|
|
121
|
+
is empty.
|
|
122
|
+
"""
|
|
123
|
+
query = query.strip()
|
|
124
|
+
if not query:
|
|
125
|
+
return set()
|
|
126
|
+
|
|
127
|
+
tokens = query.lower().split()
|
|
128
|
+
expanded = set(tokens)
|
|
129
|
+
|
|
130
|
+
# Single-word concepts: exact token match (no substring false positives)
|
|
131
|
+
for token in tokens:
|
|
132
|
+
if token in synonyms:
|
|
133
|
+
expanded.update(synonyms[token])
|
|
134
|
+
|
|
135
|
+
# Multi-word concepts: word-boundary regex match (CR-01 fix)
|
|
136
|
+
if _concept_patterns is None:
|
|
137
|
+
_concept_patterns = _build_concept_patterns(synonyms)
|
|
138
|
+
query_lower = query.lower()
|
|
139
|
+
for concept, expansions in synonyms.items():
|
|
140
|
+
if " " not in concept:
|
|
141
|
+
continue
|
|
142
|
+
pattern = _concept_patterns.get(concept)
|
|
143
|
+
if pattern and pattern.search(query_lower):
|
|
144
|
+
expanded.update(expansions)
|
|
145
|
+
|
|
146
|
+
return expanded
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def build_match_expression(
|
|
150
|
+
query: str,
|
|
151
|
+
synonyms: dict[str, list[str]],
|
|
152
|
+
*,
|
|
153
|
+
_concept_patterns: dict[str, re.Pattern[str]] | None = None,
|
|
154
|
+
) -> str:
|
|
155
|
+
"""Build a complete FTS5 MATCH expression with synonym expansion.
|
|
156
|
+
|
|
157
|
+
If synonyms match, produces an OR-joined expression of escaped terms.
|
|
158
|
+
If no synonyms match, produces the plain escaped query (implicit AND).
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
query: User search query.
|
|
162
|
+
synonyms: Synonym mapping for expansion.
|
|
163
|
+
_concept_patterns: Pre-compiled regex patterns for multi-word concepts.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
FTS5-safe MATCH expression string.
|
|
167
|
+
"""
|
|
168
|
+
query = query.strip()
|
|
169
|
+
if not query:
|
|
170
|
+
return '""'
|
|
171
|
+
|
|
172
|
+
expanded = expand_synonyms(query, synonyms, _concept_patterns=_concept_patterns)
|
|
173
|
+
original_tokens = set(query.lower().split())
|
|
174
|
+
|
|
175
|
+
# If expansion added new terms, OR-join all terms
|
|
176
|
+
if expanded != original_tokens:
|
|
177
|
+
original_query = fts5_escape(query)
|
|
178
|
+
escaped_terms = [fts5_escape(term) for term in sorted(expanded)]
|
|
179
|
+
extra_terms = [term for term in escaped_terms if term != original_query]
|
|
180
|
+
return " OR ".join([original_query, *extra_terms])
|
|
181
|
+
|
|
182
|
+
# No expansion -- use plain escaped query (implicit AND)
|
|
183
|
+
return fts5_escape(query)
|