diff --git a/CHANGELOG.md b/CHANGELOG.md index 22ab62a..5e315f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +## [0.2.0] - 2026-11-18 + ### Added +- MCP tool `aclib_find`: search the module catalog by keywords and return only the matching modules + (path, description, dependencies, variants, tests/examples, public members) instead of reading the whole + catalog. Search words are OR-combined and ranked by matched words; without a match (or with + `overview=true`) a compact list of all modules is returned so that the caller can choose by meaning. +- Server instructions and tool descriptions point to the skill `aclib-import`, to catalog-only file paths + and to approval before `aclib_import` / `aclib_compile`. - Skill `aclib-import`: find suitable modules for a task in the ACLib catalog (`_codelib/catalog/catalog.md` / `catalog.json`, local repository or GitHub) before resolving the import. +- Skill `aclib-import`: read the tests and examples listed in the catalog as usage reference when it is + unclear how a module is meant to be used (no import required). ## [0.1.0] - 2026-10-12 diff --git a/README.md b/README.md index c060815..ad6928e 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ without the wizard UI. The server only needs the Import Wizard add-in. No other Access MCP server is required. -> Status: early development (0.1.0, first release). +> Status: early development (0.2.0). ## Prerequisites @@ -61,6 +61,7 @@ Set them in the MCP server configuration, e.g.: |---|---|---|---| | `aclib_get_version` | `database_path` | no | add-in and API version | | `aclib_get_config` | `database_path`, `source?`, `repo?` | no | configured repositories, resulting source | +| `aclib_find` | `database_path`, `query`, `source?`, `repo?`, `limit?` | no | matching catalog modules: path, description, dependencies, variants, tests/examples, public members | | `aclib_list_installed` | `database_path` | no | ACLib modules in the database (from their `` blocks) | | `aclib_resolve` | `database_path`, `files[]`, `mode?`, `tests?`, `examples?`, `source?`, `repo?` | no | files incl. dependencies, references, tests/examples, planned action, missing files | | `aclib_import` | same as `aclib_resolve` | yes (may overwrite) | imported/skipped files, missing dependencies, added/removed references, messages | @@ -78,7 +79,8 @@ should require approval. [`skills/aclib-import/SKILL.md`](skills/aclib-import/SKILL.md) describes the workflow for agents (find modules in the ACLib catalog → check version → list installed → resolve → import after approval → -compile). For Claude Code, copy the +compile). If the usage of a module is unclear, the skill points agents to its tests and examples listed in +the catalog. For Claude Code, copy the folder `skills/aclib-import` to `~/.claude/skills/`. ## How it works diff --git a/skills/aclib-import/SKILL.md b/skills/aclib-import/SKILL.md index b9dac54..93eeb53 100644 --- a/skills/aclib-import/SKILL.md +++ b/skills/aclib-import/SKILL.md @@ -22,6 +22,7 @@ Only the tools of the `aclib-import` MCP server are used. |---|---|---| | `aclib_get_version` | `database_path` | no | | `aclib_get_config` | `database_path`, `source?`, `repo?` | no | +| `aclib_find` | `database_path`, `query`, `source?`, `repo?`, `limit?` | no | | `aclib_list_installed` | `database_path` | no | | `aclib_resolve` | `database_path`, `files[]`, `mode?`, `tests?`, `examples?`, `source?`, `repo?` | no | | `aclib_import` | same as `aclib_resolve` | yes (may overwrite) | @@ -46,6 +47,13 @@ The repository contains a generated module catalog built from the `` he Large file: never read it completely, search the entry by `"path": ""` (e.g. Grep with about 80 lines of context). +Searching (saves tokens): call `aclib_find` with several English synonyms of the task (the catalog is +English and the match is literal text, not meaning; e.g. a "Suchformular" is `search filter criteria form`). +Any word may match, modules with more matching words rank higher. It returns only matching modules with +`uses`, `sameObjectName`, `tests`, `examples` and the matching `publicMembers`. If nothing matches (or with +`overview=true`) it returns a compact list of all modules: choose by meaning from it. Never conclude that +no suitable module exists from one unsuccessful search. + Catalog location (from `aclib_get_config`): - `localRepositoryPath` set: read `/_codelib/catalog/catalog.md` and `catalog.json`. - Otherwise GitHub raw: @@ -68,8 +76,15 @@ Selecting modules: - Request only the main module(s); dependencies are added by `aclib_resolve`. - If the catalog contains nothing suitable, say so. Do not invent modules or paths. +## Using a module (tests as usage reference) +- If it is unclear how a module is meant to be used, read its tests and examples: they show typical + calls, parameters and expected results. The catalog lists them per module (`tests`, `examples` + in `catalog.json`); read them from the catalog location (local repository or GitHub raw). + Reading does not require an import. +- If the tests do not cover the intended use either, say so; do not guess the behaviour. + ## Workflow -0. **Discover (only if the user did not name the file paths):** read the catalog (see Catalog), then +0. **Discover (only if the user did not name the file paths):** search the catalog (`aclib_find`, see Catalog), then show the user a table of candidates: file, description, relevant public members, dependencies (`usesTransitive`), tests/examples. Recommend one with a short reason and wait for the user's choice. Mark candidates that are already installed (step 2). @@ -102,7 +117,8 @@ Selecting modules: - Missing dependencies (`missing` with `requiredBy`) are skipped by the import -> report them, the project will probably not compile. - Never run `aclib_import` / `aclib_compile` while other tools or the user change the same database. -- Take `files` paths only from the catalog or from the user, never guessed. +- Take `files` paths only from the catalog (`aclib_find` / `catalog.md`) or from the user, never guessed. + Do not claim that there is no way to find modules: the catalog and `aclib_find` exist. - If the catalog was read from another source than the import uses (e.g. local catalog, import from GitHub `master`), tell the user: a module may differ or be missing there; `aclib_resolve` reports it in `missing`. diff --git a/src/aclib_import_mcp/__init__.py b/src/aclib_import_mcp/__init__.py index 7b4321d..d6c2198 100644 --- a/src/aclib_import_mcp/__init__.py +++ b/src/aclib_import_mcp/__init__.py @@ -1,3 +1,3 @@ """MCP server for the ACLib Import Wizard automation API.""" -__version__ = "0.1.0" +__version__ = "0.2.0" diff --git a/src/aclib_import_mcp/catalog.py b/src/aclib_import_mcp/catalog.py new file mode 100644 index 0000000..1b142da --- /dev/null +++ b/src/aclib_import_mcp/catalog.py @@ -0,0 +1,163 @@ +"""Search in the generated ACLib module catalog (``_codelib/catalog/catalog.json``). + +The catalog is read from the local repository (path from the wizard configuration) or from +GitHub raw. Only a fixed host and validated repository names are used. +""" + +from __future__ import annotations + +import json +import re +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any + +CATALOG_RELATIVE_PATH = "_codelib/catalog/catalog.json" +GITHUB_RAW_URL = ( + "https://raw.githubusercontent.com/{owner}/{repo}/{branch}/" + CATALOG_RELATIVE_PATH +) +DEFAULT_GITHUB = {"owner": "AccessCodeLib", "repo": "AccessCodeLib", "branch": "master"} +HTTP_TIMEOUT_SECONDS = 30 +MAX_MEMBERS_SHOWN = 8 +_NAME_WEIGHT = 5 +_DESCRIPTION_WEIGHT = 3 +_MEMBER_WEIGHT = 1 + + +class CatalogError(Exception): + """The catalog could not be loaded or parsed.""" + + +def github_location(config: dict[str, Any], repo: str | None) -> dict[str, str]: + """Return ``{owner, repo, branch}``: from ``repo`` ('owner/name[@branch]') or the config.""" + if repo: + name, _, branch = repo.partition("@") + owner, _, repo_name = name.partition("/") + return {"owner": owner, "repo": repo_name, "branch": branch or "master"} + github = config.get("github") + if isinstance(github, dict) and all(github.get(k) for k in ("owner", "repo", "branch")): + return {k: str(github[k]) for k in ("owner", "repo", "branch")} + return dict(DEFAULT_GITHUB) + + +def catalog_origin(config: dict[str, Any], source: str, repo: str | None) -> str: + """Return the local catalog file path or the GitHub raw URL for the effective source.""" + local = str(config.get("localRepositoryPath") or "").strip() + use_local = not repo and (source == "local" or (source == "config" and local)) + if use_local: + if not local: + raise CatalogError("No local repository configured in the ACLib Import Wizard.") + return str(Path(local) / CATALOG_RELATIVE_PATH) + location = github_location(config, repo) + return GITHUB_RAW_URL.format(**location) + + +def load_catalog(origin: str) -> dict[str, Any]: + """Load and parse the catalog from a file path or an https URL.""" + try: + if origin.startswith("https://raw.githubusercontent.com/"): + with urllib.request.urlopen(origin, timeout=HTTP_TIMEOUT_SECONDS) as response: # noqa: S310 + raw = response.read() + else: + raw = Path(origin).read_bytes() + data = json.loads(raw.decode("utf-8-sig")) + except urllib.error.HTTPError as exc: + raise CatalogError(f"Catalog not found ({exc.code}): {origin}") from None + except (OSError, urllib.error.URLError, ValueError) as exc: + raise CatalogError(f"Catalog could not be read ({exc}): {origin}") from None + if not isinstance(data, dict) or not isinstance(data.get("modules"), list): + raise CatalogError(f"Catalog has an unexpected format: {origin}") + return data + + +def _terms(query: str) -> list[str]: + seen: dict[str, None] = {} + for term in re.split(r"[\s,;]+", query.lower().strip()): + if term: + seen[term] = None + return list(seen) + + +def _hit(term: str, text: str) -> bool: + """True if ``term`` starts a word in ``text`` (so 'filter' finds 'filters', not 'prefilter').""" + return re.search(r"(? tuple[int, int] | None: + """Return ``(matched terms, weighted score)`` if at least one term matches, else ``None``.""" + name = f"{module.get('path') or ''} {module.get('name') or ''}".lower() + description = str(module.get("description") or "").lower() + members = " ".join(str(m) for m in module.get("publicMembers") or []).lower() + matched = score = 0 + for term in terms: + points = ( + _NAME_WEIGHT * _hit(term, name) + + _DESCRIPTION_WEIGHT * _hit(term, description) + + _MEMBER_WEIGHT * _hit(term, members) + ) + if points: + matched += 1 + score += points + return (matched, score) if matched else None + + +def _entry(module: dict[str, Any], terms: list[str]) -> dict[str, Any]: + members = [str(m) for m in module.get("publicMembers") or []] + matching = [m for m in members if any(_hit(t, m.lower()) for t in terms)] + shown = (matching or members)[:MAX_MEMBERS_SHOWN] + entry: dict[str, Any] = { + "path": module.get("path"), + "kind": module.get("kind"), + "description": module.get("description"), + "descriptionSource": module.get("descriptionSource"), + } + for key in ("predeclaredId",): + if module.get(key): + entry[key] = True + for key in ("uses", "replaces", "sameObjectName", "tests", "examples"): + if module.get(key): + entry[key] = module[key] + entry["publicMembers"] = shown + if len(matching or members) > len(shown): + entry["publicMembersTruncated"] = True + return entry + + +def overview(catalog: dict[str, Any]) -> list[str]: + """Return one compact ``path - description`` line per module.""" + return [ + f"{m.get('path')} - {m.get('description') or ''}".rstrip(" -") + for m in catalog["modules"] + if isinstance(m, dict) + ] + + +def search_modules( + catalog: dict[str, Any], query: str, limit: int, want_overview: bool = False +) -> dict[str, Any]: + """Return the best matches for ``query`` (OR over the words, ranked by matched words). + + Without any match, or with ``want_overview``, a compact list of all modules is returned + instead, so that the caller can choose by meaning. + """ + terms = _terms(query) + if not terms: + raise ValueError("query must contain at least one word") + scored = [] + for module in catalog["modules"]: + if isinstance(module, dict): + score = _score(module, terms) + if score is not None: + scored.append((score, str(module.get("path")), module)) + scored.sort(key=lambda item: (-item[0][0], -item[0][1], item[1])) + result: dict[str, Any] = { + "total": len(scored), + "shown": min(limit, len(scored)), + "modules": [_entry(m, terms) for _, _, m in scored[:limit]], + } + if want_overview or not scored: + result["overview"] = overview(catalog) + if not scored: + result["note"] = "No module matched; choose from the overview by meaning." + return result diff --git a/src/aclib_import_mcp/server.py b/src/aclib_import_mcp/server.py index 483de38..f0f191f 100644 --- a/src/aclib_import_mcp/server.py +++ b/src/aclib_import_mcp/server.py @@ -13,11 +13,27 @@ from mcp.types import ToolAnnotations from pydantic import Field -from . import addin +from . import addin, catalog from .access_com import AccessComError, AccessWorker from .addin import AclibApiError, AddinError -mcp = FastMCP("aclib-import") +INSTRUCTIONS = """\ +ACLib Import Wizard MCP server: import or update AccessCodeLib (ACLib) modules in a Microsoft \ +Access database. + +Use the skill aclib-import before working with the aclib_* tools. If it is not available in the \ +project, tell the user and offer to continue without it only after they agree. + +Essential rules if the skill is not available: +- To find a module for a task use aclib_find (search in the module catalog). Never guess file \ +paths: take them from aclib_find, the catalog (_codelib/catalog/catalog.md) or from the user. +- Order: aclib_get_version, aclib_list_installed, aclib_resolve (show the planned actions to the \ +user), then aclib_import and aclib_compile only after the user approved them. +- mode=all/selected and the action overwrite only after explicit confirmation: local edits of a \ +module in the project would be lost. +""" + +mcp = FastMCP("aclib-import", instructions=INSTRUCTIONS) Mode = Literal["missing", "all", "selected"] Source = Literal["config", "local", "github"] @@ -192,10 +208,60 @@ async def aclib_get_config( source: SourceParam = "config", repo: RepoParam = None, ) -> dict[str, Any]: - """Return the wizard configuration: repositories and the resulting source.""" + """Return the wizard configuration: repositories and the resulting source. + + The module catalog is at /_codelib/catalog/catalog.md (or on GitHub + raw); to search it use aclib_find. + """ return await _call_api(database_path, "GetConfig", build_source_options(source, repo)) +@mcp.tool(annotations=READ_ONLY.model_copy(update={"openWorldHint": True})) +async def aclib_find( + database_path: DatabasePath, + query: Annotated[ + str, + Field( + description="English search words and synonyms (any may match, more matching words " + "rank higher), e.g. 'search filter criteria form'. The catalog is English: " + "translate the task into several synonyms.", + min_length=1, + ), + ], + source: SourceParam = "config", + repo: RepoParam = None, + limit: Annotated[ + int, Field(description="Maximum number of modules returned.", ge=1, le=25) + ] = 8, + overview: Annotated[ + bool, + Field(description="Also return a compact list of all modules (path and description)."), + ] = False, +) -> dict[str, Any]: + """Find ACLib modules in the module catalog (instead of reading the whole catalog). + + The match is literal text, not meaning: pass several English synonyms of the task. If + nothing matches (or overview=true), a compact list of all modules is returned; choose + from it by meaning and do not conclude that no suitable module exists. + + Returns per match: path, description, uses (dependencies), replaces, sameObjectName + (variants that cannot be imported together), tests, examples and public members. + Show the candidates to the user and let them choose; pass the chosen paths to + aclib_resolve. Reads only; does not change the database. + """ + config = await _call_api(database_path, "GetConfig", build_source_options(source, repo)) + + def run() -> dict[str, Any]: + origin = catalog.catalog_origin(config, source, validate_repo(repo, source)) + result = catalog.search_modules(catalog.load_catalog(origin), query, limit, overview) + return {"ok": True, "catalog": origin, **result} + + try: + return await anyio.to_thread.run_sync(run) + except (catalog.CatalogError, ValueError) as exc: + raise ToolError(str(exc)) from exc + + @mcp.tool(annotations=READ_ONLY.model_copy(update={"openWorldHint": False})) async def aclib_list_installed(database_path: DatabasePath) -> dict[str, Any]: """List the ACLib modules installed in the database (from their codelib blocks).""" @@ -212,10 +278,12 @@ async def aclib_resolve( source: SourceParam = "config", repo: RepoParam = None, ) -> dict[str, Any]: - """Plan an import without changing the database. + """Plan an import without changing the database. Use the skill aclib-import first. + Take file paths only from aclib_find, the catalog or the user, never guess them. Returns the files incl. dependencies, references, tests/examples, the planned action per - file (import/skip/overwrite/replaced) and missing files. Call before aclib_import. + file (import/skip/overwrite/replaced) and missing files. Call before aclib_import and + show the result to the user. """ file_list = ";".join(validate_files(files)) options = build_options(mode, tests, examples, source, repo) @@ -238,6 +306,8 @@ async def aclib_import( ) -> dict[str, Any]: """Import ACLib modules incl. dependencies and references into the database. + Use the skill aclib-import first. Only after the user approved the plan of aclib_resolve; + take file paths only from aclib_find, the catalog or the user, never guess them. Existing modules may be overwritten (mode=all/selected). Use the same arguments as a previous aclib_resolve. Compile the project afterwards. """ diff --git a/tests/test_catalog.py b/tests/test_catalog.py new file mode 100644 index 0000000..312e587 --- /dev/null +++ b/tests/test_catalog.py @@ -0,0 +1,104 @@ +import pytest + +from aclib_import_mcp import catalog + +CATALOG = { + "modules": [ + { + "path": "data/SqlTools.cls", + "name": "SqlTools", + "kind": "class", + "description": "Builds SQL strings", + "publicMembers": ["Function BuildCriteria() As String"], + }, + { + "path": "form/filter/FilterControl.cls", + "name": "FilterControl", + "kind": "class", + "description": "Filter form control with SQL output", + "uses": ["data/SqlTools.cls"], + "sameObjectName": ["form/filter/FilterControl_DotNetLib.cls"], + "publicMembers": [f"Sub Member{i}()" for i in range(12)], + }, + ] +} + + +def test_any_term_matches_and_more_matches_rank_higher(): + result = catalog.search_modules(CATALOG, "filter sql", 10) + assert [m["path"] for m in result["modules"]] == [ + "form/filter/FilterControl.cls", + "data/SqlTools.cls", + ] + + +def test_synonyms_find_module_without_literal_query_word(): + result = catalog.search_modules(CATALOG, "search criteria filter", 10) + assert result["modules"][0]["path"] == "form/filter/FilterControl.cls" + assert "overview" not in result + + +def test_terms_match_word_starts_only(): + assert catalog.search_modules(CATALOG, "prefilter", 10)["total"] == 0 + assert catalog.search_modules(CATALOG, "filt", 10)["total"] == 1 + + +def test_no_match_returns_overview(): + result = catalog.search_modules(CATALOG, "pdf", 10) + assert result["total"] == 0 + assert result["overview"] == [ + "data/SqlTools.cls - Builds SQL strings", + "form/filter/FilterControl.cls - Filter form control with SQL output", + ] + assert "overview" in result["note"] + + +def test_overview_on_request(): + result = catalog.search_modules(CATALOG, "sql", 1, want_overview=True) + assert result["shown"] == 1 + assert len(result["overview"]) == 2 + assert "note" not in result + + +def test_ranking_prefers_name_and_description_over_members(): + result = catalog.search_modules(CATALOG, "sql", 10) + assert [m["path"] for m in result["modules"]] == [ + "data/SqlTools.cls", + "form/filter/FilterControl.cls", + ] + assert result["total"] == 2 + + +def test_limit_and_truncation(): + result = catalog.search_modules(CATALOG, "filter", 1) + assert result["shown"] == 1 + entry = result["modules"][0] + assert len(entry["publicMembers"]) == catalog.MAX_MEMBERS_SHOWN + assert entry["publicMembersTruncated"] is True + assert entry["sameObjectName"] == ["form/filter/FilterControl_DotNetLib.cls"] + + +def test_empty_query_is_rejected(): + with pytest.raises(ValueError): + catalog.search_modules(CATALOG, " ", 5) + + +def test_origin_prefers_local_repository_for_config_source(tmp_path): + origin = catalog.catalog_origin({"localRepositoryPath": str(tmp_path)}, "config", None) + assert origin.endswith("catalog.json") + assert str(tmp_path) in origin + + +def test_origin_github_uses_repo_parameter(): + origin = catalog.catalog_origin({"localRepositoryPath": "C:/x"}, "config", "me/lib@dev") + assert origin == "https://raw.githubusercontent.com/me/lib/dev/_codelib/catalog/catalog.json" + + +def test_origin_github_default_without_config(): + origin = catalog.catalog_origin({}, "github", None) + assert "AccessCodeLib/AccessCodeLib/master" in origin + + +def test_origin_local_without_path_fails(): + with pytest.raises(catalog.CatalogError): + catalog.catalog_origin({}, "local", None) diff --git a/tests/test_server.py b/tests/test_server.py index 27032b9..9e8d652 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -198,18 +198,91 @@ def test_tools_are_registered_with_annotations(): assert set(tools) == { "aclib_get_version", "aclib_get_config", + "aclib_find", "aclib_list_installed", "aclib_resolve", "aclib_import", "aclib_compile", } - for name in ("aclib_get_version", "aclib_get_config", "aclib_list_installed", "aclib_resolve"): + for name in ( + "aclib_get_version", + "aclib_get_config", + "aclib_find", + "aclib_list_installed", + "aclib_resolve", + ): assert tools[name].annotations.readOnlyHint is True assert tools["aclib_import"].annotations.readOnlyHint is False assert tools["aclib_import"].annotations.destructiveHint is True assert tools["aclib_compile"].annotations.readOnlyHint is False +def test_instructions_point_to_skill_and_catalog(): + assert "aclib-import" in server.mcp.instructions + assert "aclib_find" in server.mcp.instructions + assert "Never guess" in server.mcp.instructions + + +def test_write_tools_point_to_skill(): + tools = {tool.name: tool for tool in anyio.run(server.mcp.list_tools)} + for name in ("aclib_resolve", "aclib_import"): + assert "skill aclib-import" in tools[name].description + assert "never guess" in tools[name].description + + +def test_find_reads_local_catalog(use_worker, tmp_path): + catalog_file = tmp_path / "_codelib" / "catalog" / "catalog.json" + catalog_file.parent.mkdir(parents=True) + catalog_file.write_text( + json.dumps( + { + "modules": [ + {"path": "data/SqlTools.cls", "name": "SqlTools", "description": "SQL helper"}, + { + "path": "form/filter/FilterControl.cls", + "name": "FilterControl", + "description": "Filter form control", + "uses": ["data/SqlTools.cls"], + "publicMembers": ["Sub Apply()"], + }, + ] + } + ), + encoding="utf-8", + ) + config = json.dumps({"ok": True, "localRepositoryPath": str(tmp_path)}) + app = FakeApp({"GetVersion": VERSION_OK, "GetConfig": config}) + use_worker(FakeWorker(app)) + + result = call(server.aclib_find, database_path=DB, query="Filter") + + assert result["total"] == 1 + assert result["modules"][0]["path"] == "form/filter/FilterControl.cls" + assert result["modules"][0]["uses"] == ["data/SqlTools.cls"] + assert app.calls[-1] == ("GetConfig", "source=config") + + +def test_find_without_match_returns_empty_list(use_worker, tmp_path): + catalog_file = tmp_path / "_codelib" / "catalog" / "catalog.json" + catalog_file.parent.mkdir(parents=True) + catalog_file.write_text(json.dumps({"modules": []}), encoding="utf-8") + config = json.dumps({"ok": True, "localRepositoryPath": str(tmp_path)}) + use_worker(FakeWorker(FakeApp({"GetVersion": VERSION_OK, "GetConfig": config}))) + + result = call(server.aclib_find, database_path=DB, query="nothing") + + assert result["total"] == 0 + assert result["modules"] == [] + + +def test_find_missing_catalog_becomes_tool_error(use_worker, tmp_path): + config = json.dumps({"ok": True, "localRepositoryPath": str(tmp_path)}) + use_worker(FakeWorker(FakeApp({"GetVersion": VERSION_OK, "GetConfig": config}))) + + with pytest.raises(ToolError, match="Catalog could not be read"): + call(server.aclib_find, database_path=DB, query="filter") + + class CompileApp: def __init__(self, compiled, error=None): self.IsCompiled = compiled