Skip to content

Commit 4c107ae

Browse files
authored
Add aclib_find tool and skill hints in server instructions (#11)
Server instructions and tool descriptions point to the aclib-import skill, catalog-only paths and approval before writing calls. aclib_find searches the module catalog (OR over synonyms, ranked) and falls back to a compact module overview.
1 parent e1cb779 commit 4c107ae

7 files changed

Lines changed: 434 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
66
## [Unreleased]
77

88
### Added
9+
- MCP tool `aclib_find`: search the module catalog by keywords and return only the matching modules
10+
(path, description, dependencies, variants, tests/examples, public members) instead of reading the whole
11+
catalog. Search words are OR-combined and ranked by matched words; without a match (or with
12+
`overview=true`) a compact list of all modules is returned so that the caller can choose by meaning.
13+
- Server instructions and tool descriptions point to the skill `aclib-import`, to catalog-only file paths
14+
and to approval before `aclib_import` / `aclib_compile`.
915
- Skill `aclib-import`: find suitable modules for a task in the ACLib catalog
1016
(`_codelib/catalog/catalog.md` / `catalog.json`, local repository or GitHub) before resolving the import.
1117
- Skill `aclib-import`: read the tests and examples listed in the catalog as usage reference when it is

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ Set them in the MCP server configuration, e.g.:
6161
|---|---|---|---|
6262
| `aclib_get_version` | `database_path` | no | add-in and API version |
6363
| `aclib_get_config` | `database_path`, `source?`, `repo?` | no | configured repositories, resulting source |
64+
| `aclib_find` | `database_path`, `query`, `source?`, `repo?`, `limit?` | no | matching catalog modules: path, description, dependencies, variants, tests/examples, public members |
6465
| `aclib_list_installed` | `database_path` | no | ACLib modules in the database (from their `<codelib>` blocks) |
6566
| `aclib_resolve` | `database_path`, `files[]`, `mode?`, `tests?`, `examples?`, `source?`, `repo?` | no | files incl. dependencies, references, tests/examples, planned action, missing files |
6667
| `aclib_import` | same as `aclib_resolve` | yes (may overwrite) | imported/skipped files, missing dependencies, added/removed references, messages |

‎skills/aclib-import/SKILL.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Only the tools of the `aclib-import` MCP server are used.
2222
|---|---|---|
2323
| `aclib_get_version` | `database_path` | no |
2424
| `aclib_get_config` | `database_path`, `source?`, `repo?` | no |
25+
| `aclib_find` | `database_path`, `query`, `source?`, `repo?`, `limit?` | no |
2526
| `aclib_list_installed` | `database_path` | no |
2627
| `aclib_resolve` | `database_path`, `files[]`, `mode?`, `tests?`, `examples?`, `source?`, `repo?` | no |
2728
| `aclib_import` | same as `aclib_resolve` | yes (may overwrite) |
@@ -46,6 +47,13 @@ The repository contains a generated module catalog built from the `<codelib>` he
4647
Large file: never read it
4748
completely, search the entry by `"path": "<file>"` (e.g. Grep with about 80 lines of context).
4849

50+
Searching (saves tokens): call `aclib_find` with several English synonyms of the task (the catalog is
51+
English and the match is literal text, not meaning; e.g. a "Suchformular" is `search filter criteria form`).
52+
Any word may match, modules with more matching words rank higher. It returns only matching modules with
53+
`uses`, `sameObjectName`, `tests`, `examples` and the matching `publicMembers`. If nothing matches (or with
54+
`overview=true`) it returns a compact list of all modules: choose by meaning from it. Never conclude that
55+
no suitable module exists from one unsuccessful search.
56+
4957
Catalog location (from `aclib_get_config`):
5058
- `localRepositoryPath` set: read `<localRepositoryPath>/_codelib/catalog/catalog.md` and `catalog.json`.
5159
- Otherwise GitHub raw:
@@ -76,7 +84,7 @@ Selecting modules:
7684
- If the tests do not cover the intended use either, say so; do not guess the behaviour.
7785

7886
## Workflow
79-
0. **Discover (only if the user did not name the file paths):** read the catalog (see Catalog), then
87+
0. **Discover (only if the user did not name the file paths):** search the catalog (`aclib_find`, see Catalog), then
8088
show the user a table of candidates: file, description, relevant public members, dependencies
8189
(`usesTransitive`), tests/examples. Recommend one with a short reason and wait for the user's choice.
8290
Mark candidates that are already installed (step 2).
@@ -109,7 +117,8 @@ Selecting modules:
109117
- Missing dependencies (`missing` with `requiredBy`) are skipped by the import -> report them,
110118
the project will probably not compile.
111119
- Never run `aclib_import` / `aclib_compile` while other tools or the user change the same database.
112-
- Take `files` paths only from the catalog or from the user, never guessed.
120+
- Take `files` paths only from the catalog (`aclib_find` / `catalog.md`) or from the user, never guessed.
121+
Do not claim that there is no way to find modules: the catalog and `aclib_find` exist.
113122
- If the catalog was read from another source than the import uses (e.g. local catalog, import from GitHub
114123
`master`), tell the user: a module may differ or be missing there; `aclib_resolve` reports it in `missing`.
115124

‎src/aclib_import_mcp/catalog.py‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
"""Search in the generated ACLib module catalog (``_codelib/catalog/catalog.json``).
2+
3+
The catalog is read from the local repository (path from the wizard configuration) or from
4+
GitHub raw. Only a fixed host and validated repository names are used.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
import json
10+
import re
11+
import urllib.error
12+
import urllib.request
13+
from pathlib import Path
14+
from typing import Any
15+
16+
CATALOG_RELATIVE_PATH = "_codelib/catalog/catalog.json"
17+
GITHUB_RAW_URL = (
18+
"https://raw.githubusercontent.com/{owner}/{repo}/{branch}/" + CATALOG_RELATIVE_PATH
19+
)
20+
DEFAULT_GITHUB = {"owner": "AccessCodeLib", "repo": "AccessCodeLib", "branch": "master"}
21+
HTTP_TIMEOUT_SECONDS = 30
22+
MAX_MEMBERS_SHOWN = 8
23+
_NAME_WEIGHT = 5
24+
_DESCRIPTION_WEIGHT = 3
25+
_MEMBER_WEIGHT = 1
26+
27+
28+
class CatalogError(Exception):
29+
"""The catalog could not be loaded or parsed."""
30+
31+
32+
def github_location(config: dict[str, Any], repo: str | None) -> dict[str, str]:
33+
"""Return ``{owner, repo, branch}``: from ``repo`` ('owner/name[@branch]') or the config."""
34+
if repo:
35+
name, _, branch = repo.partition("@")
36+
owner, _, repo_name = name.partition("/")
37+
return {"owner": owner, "repo": repo_name, "branch": branch or "master"}
38+
github = config.get("github")
39+
if isinstance(github, dict) and all(github.get(k) for k in ("owner", "repo", "branch")):
40+
return {k: str(github[k]) for k in ("owner", "repo", "branch")}
41+
return dict(DEFAULT_GITHUB)
42+
43+
44+
def catalog_origin(config: dict[str, Any], source: str, repo: str | None) -> str:
45+
"""Return the local catalog file path or the GitHub raw URL for the effective source."""
46+
local = str(config.get("localRepositoryPath") or "").strip()
47+
use_local = not repo and (source == "local" or (source == "config" and local))
48+
if use_local:
49+
if not local:
50+
raise CatalogError("No local repository configured in the ACLib Import Wizard.")
51+
return str(Path(local) / CATALOG_RELATIVE_PATH)
52+
location = github_location(config, repo)
53+
return GITHUB_RAW_URL.format(**location)
54+
55+
56+
def load_catalog(origin: str) -> dict[str, Any]:
57+
"""Load and parse the catalog from a file path or an https URL."""
58+
try:
59+
if origin.startswith("https://raw.githubusercontent.com/"):
60+
with urllib.request.urlopen(origin, timeout=HTTP_TIMEOUT_SECONDS) as response: # noqa: S310
61+
raw = response.read()
62+
else:
63+
raw = Path(origin).read_bytes()
64+
data = json.loads(raw.decode("utf-8-sig"))
65+
except urllib.error.HTTPError as exc:
66+
raise CatalogError(f"Catalog not found ({exc.code}): {origin}") from None
67+
except (OSError, urllib.error.URLError, ValueError) as exc:
68+
raise CatalogError(f"Catalog could not be read ({exc}): {origin}") from None
69+
if not isinstance(data, dict) or not isinstance(data.get("modules"), list):
70+
raise CatalogError(f"Catalog has an unexpected format: {origin}")
71+
return data
72+
73+
74+
def _terms(query: str) -> list[str]:
75+
seen: dict[str, None] = {}
76+
for term in re.split(r"[\s,;]+", query.lower().strip()):
77+
if term:
78+
seen[term] = None
79+
return list(seen)
80+
81+
82+
def _hit(term: str, text: str) -> bool:
83+
"""True if ``term`` starts a word in ``text`` (so 'filter' finds 'filters', not 'prefilter')."""
84+
return re.search(r"(?<![a-z0-9])" + re.escape(term), text) is not None
85+
86+
87+
def _score(module: dict[str, Any], terms: list[str]) -> tuple[int, int] | None:
88+
"""Return ``(matched terms, weighted score)`` if at least one term matches, else ``None``."""
89+
name = f"{module.get('path') or ''} {module.get('name') or ''}".lower()
90+
description = str(module.get("description") or "").lower()
91+
members = " ".join(str(m) for m in module.get("publicMembers") or []).lower()
92+
matched = score = 0
93+
for term in terms:
94+
points = (
95+
_NAME_WEIGHT * _hit(term, name)
96+
+ _DESCRIPTION_WEIGHT * _hit(term, description)
97+
+ _MEMBER_WEIGHT * _hit(term, members)
98+
)
99+
if points:
100+
matched += 1
101+
score += points
102+
return (matched, score) if matched else None
103+
104+
105+
def _entry(module: dict[str, Any], terms: list[str]) -> dict[str, Any]:
106+
members = [str(m) for m in module.get("publicMembers") or []]
107+
matching = [m for m in members if any(_hit(t, m.lower()) for t in terms)]
108+
shown = (matching or members)[:MAX_MEMBERS_SHOWN]
109+
entry: dict[str, Any] = {
110+
"path": module.get("path"),
111+
"kind": module.get("kind"),
112+
"description": module.get("description"),
113+
"descriptionSource": module.get("descriptionSource"),
114+
}
115+
for key in ("predeclaredId",):
116+
if module.get(key):
117+
entry[key] = True
118+
for key in ("uses", "replaces", "sameObjectName", "tests", "examples"):
119+
if module.get(key):
120+
entry[key] = module[key]
121+
entry["publicMembers"] = shown
122+
if len(matching or members) > len(shown):
123+
entry["publicMembersTruncated"] = True
124+
return entry
125+
126+
127+
def overview(catalog: dict[str, Any]) -> list[str]:
128+
"""Return one compact ``path - description`` line per module."""
129+
return [
130+
f"{m.get('path')} - {m.get('description') or ''}".rstrip(" -")
131+
for m in catalog["modules"]
132+
if isinstance(m, dict)
133+
]
134+
135+
136+
def search_modules(
137+
catalog: dict[str, Any], query: str, limit: int, want_overview: bool = False
138+
) -> dict[str, Any]:
139+
"""Return the best matches for ``query`` (OR over the words, ranked by matched words).
140+
141+
Without any match, or with ``want_overview``, a compact list of all modules is returned
142+
instead, so that the caller can choose by meaning.
143+
"""
144+
terms = _terms(query)
145+
if not terms:
146+
raise ValueError("query must contain at least one word")
147+
scored = []
148+
for module in catalog["modules"]:
149+
if isinstance(module, dict):
150+
score = _score(module, terms)
151+
if score is not None:
152+
scored.append((score, str(module.get("path")), module))
153+
scored.sort(key=lambda item: (-item[0][0], -item[0][1], item[1]))
154+
result: dict[str, Any] = {
155+
"total": len(scored),
156+
"shown": min(limit, len(scored)),
157+
"modules": [_entry(m, terms) for _, _, m in scored[:limit]],
158+
}
159+
if want_overview or not scored:
160+
result["overview"] = overview(catalog)
161+
if not scored:
162+
result["note"] = "No module matched; choose from the overview by meaning."
163+
return result

‎src/aclib_import_mcp/server.py‎

Lines changed: 75 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,27 @@
1313
from mcp.types import ToolAnnotations
1414
from pydantic import Field
1515

16-
from . import addin
16+
from . import addin, catalog
1717
from .access_com import AccessComError, AccessWorker
1818
from .addin import AclibApiError, AddinError
1919

20-
mcp = FastMCP("aclib-import")
20+
INSTRUCTIONS = """\
21+
ACLib Import Wizard MCP server: import or update AccessCodeLib (ACLib) modules in a Microsoft \
22+
Access database.
23+
24+
Use the skill aclib-import before working with the aclib_* tools. If it is not available in the \
25+
project, tell the user and offer to continue without it only after they agree.
26+
27+
Essential rules if the skill is not available:
28+
- To find a module for a task use aclib_find (search in the module catalog). Never guess file \
29+
paths: take them from aclib_find, the catalog (_codelib/catalog/catalog.md) or from the user.
30+
- Order: aclib_get_version, aclib_list_installed, aclib_resolve (show the planned actions to the \
31+
user), then aclib_import and aclib_compile only after the user approved them.
32+
- mode=all/selected and the action overwrite only after explicit confirmation: local edits of a \
33+
module in the project would be lost.
34+
"""
35+
36+
mcp = FastMCP("aclib-import", instructions=INSTRUCTIONS)
2137

2238
Mode = Literal["missing", "all", "selected"]
2339
Source = Literal["config", "local", "github"]
@@ -192,10 +208,60 @@ async def aclib_get_config(
192208
source: SourceParam = "config",
193209
repo: RepoParam = None,
194210
) -> dict[str, Any]:
195-
"""Return the wizard configuration: repositories and the resulting source."""
211+
"""Return the wizard configuration: repositories and the resulting source.
212+
213+
The module catalog is at <localRepositoryPath>/_codelib/catalog/catalog.md (or on GitHub
214+
raw); to search it use aclib_find.
215+
"""
196216
return await _call_api(database_path, "GetConfig", build_source_options(source, repo))
197217

198218

219+
@mcp.tool(annotations=READ_ONLY.model_copy(update={"openWorldHint": True}))
220+
async def aclib_find(
221+
database_path: DatabasePath,
222+
query: Annotated[
223+
str,
224+
Field(
225+
description="English search words and synonyms (any may match, more matching words "
226+
"rank higher), e.g. 'search filter criteria form'. The catalog is English: "
227+
"translate the task into several synonyms.",
228+
min_length=1,
229+
),
230+
],
231+
source: SourceParam = "config",
232+
repo: RepoParam = None,
233+
limit: Annotated[
234+
int, Field(description="Maximum number of modules returned.", ge=1, le=25)
235+
] = 8,
236+
overview: Annotated[
237+
bool,
238+
Field(description="Also return a compact list of all modules (path and description)."),
239+
] = False,
240+
) -> dict[str, Any]:
241+
"""Find ACLib modules in the module catalog (instead of reading the whole catalog).
242+
243+
The match is literal text, not meaning: pass several English synonyms of the task. If
244+
nothing matches (or overview=true), a compact list of all modules is returned; choose
245+
from it by meaning and do not conclude that no suitable module exists.
246+
247+
Returns per match: path, description, uses (dependencies), replaces, sameObjectName
248+
(variants that cannot be imported together), tests, examples and public members.
249+
Show the candidates to the user and let them choose; pass the chosen paths to
250+
aclib_resolve. Reads only; does not change the database.
251+
"""
252+
config = await _call_api(database_path, "GetConfig", build_source_options(source, repo))
253+
254+
def run() -> dict[str, Any]:
255+
origin = catalog.catalog_origin(config, source, validate_repo(repo, source))
256+
result = catalog.search_modules(catalog.load_catalog(origin), query, limit, overview)
257+
return {"ok": True, "catalog": origin, **result}
258+
259+
try:
260+
return await anyio.to_thread.run_sync(run)
261+
except (catalog.CatalogError, ValueError) as exc:
262+
raise ToolError(str(exc)) from exc
263+
264+
199265
@mcp.tool(annotations=READ_ONLY.model_copy(update={"openWorldHint": False}))
200266
async def aclib_list_installed(database_path: DatabasePath) -> dict[str, Any]:
201267
"""List the ACLib modules installed in the database (from their codelib blocks)."""
@@ -212,10 +278,12 @@ async def aclib_resolve(
212278
source: SourceParam = "config",
213279
repo: RepoParam = None,
214280
) -> dict[str, Any]:
215-
"""Plan an import without changing the database.
281+
"""Plan an import without changing the database. Use the skill aclib-import first.
216282
283+
Take file paths only from aclib_find, the catalog or the user, never guess them.
217284
Returns the files incl. dependencies, references, tests/examples, the planned action per
218-
file (import/skip/overwrite/replaced) and missing files. Call before aclib_import.
285+
file (import/skip/overwrite/replaced) and missing files. Call before aclib_import and
286+
show the result to the user.
219287
"""
220288
file_list = ";".join(validate_files(files))
221289
options = build_options(mode, tests, examples, source, repo)
@@ -238,6 +306,8 @@ async def aclib_import(
238306
) -> dict[str, Any]:
239307
"""Import ACLib modules incl. dependencies and references into the database.
240308
309+
Use the skill aclib-import first. Only after the user approved the plan of aclib_resolve;
310+
take file paths only from aclib_find, the catalog or the user, never guess them.
241311
Existing modules may be overwritten (mode=all/selected). Use the same arguments as a
242312
previous aclib_resolve. Compile the project afterwards.
243313
"""

0 commit comments

Comments
 (0)