Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]

### 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
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<codelib>` 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 |
Expand Down
13 changes: 11 additions & 2 deletions skills/aclib-import/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand All @@ -46,6 +47,13 @@ The repository contains a generated module catalog built from the `<codelib>` he
Large file: never read it
completely, search the entry by `"path": "<file>"` (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 `<localRepositoryPath>/_codelib/catalog/catalog.md` and `catalog.json`.
- Otherwise GitHub raw:
Expand Down Expand Up @@ -76,7 +84,7 @@ Selecting modules:
- 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).
Expand Down Expand Up @@ -109,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`.

Expand Down
163 changes: 163 additions & 0 deletions src/aclib_import_mcp/catalog.py
Original file line number Diff line number Diff line change
@@ -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"(?<![a-z0-9])" + re.escape(term), text) is not None


def _score(module: dict[str, Any], terms: list[str]) -> 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
80 changes: 75 additions & 5 deletions src/aclib_import_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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 <localRepositoryPath>/_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)."""
Expand All @@ -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)
Expand All @@ -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.
"""
Expand Down
Loading
Loading