toolspotter 0.1.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.
Files changed (55) hide show
  1. toolspotter/__init__.py +13 -0
  2. toolspotter/api.py +437 -0
  3. toolspotter/catalog_changes.py +109 -0
  4. toolspotter/catalog_loader.py +188 -0
  5. toolspotter/cli.py +361 -0
  6. toolspotter/config.py +121 -0
  7. toolspotter/database.py +66 -0
  8. toolspotter/domain/__init__.py +21 -0
  9. toolspotter/domain/errors.py +58 -0
  10. toolspotter/domain/models.py +113 -0
  11. toolspotter/domain/naming.py +69 -0
  12. toolspotter/domain/versioning.py +149 -0
  13. toolspotter/engine/__init__.py +5 -0
  14. toolspotter/engine/bm25.py +62 -0
  15. toolspotter/engine/confidence.py +115 -0
  16. toolspotter/engine/dedup.py +60 -0
  17. toolspotter/engine/derive.py +215 -0
  18. toolspotter/engine/guardrail.py +218 -0
  19. toolspotter/engine/hyde.py +86 -0
  20. toolspotter/engine/ingest.py +88 -0
  21. toolspotter/engine/llm_planner.py +147 -0
  22. toolspotter/engine/pipeline.py +783 -0
  23. toolspotter/engine/planner.py +265 -0
  24. toolspotter/engine/retrieval.py +140 -0
  25. toolspotter/engine/text.py +134 -0
  26. toolspotter/history.py +198 -0
  27. toolspotter/importers/__init__.py +12 -0
  28. toolspotter/importers/common.py +62 -0
  29. toolspotter/importers/mcp_importer.py +308 -0
  30. toolspotter/importers/mcp_remote.py +184 -0
  31. toolspotter/index_db.py +166 -0
  32. toolspotter/limits.py +38 -0
  33. toolspotter/log.py +34 -0
  34. toolspotter/mcp_server.py +93 -0
  35. toolspotter/netutil.py +41 -0
  36. toolspotter/postman.py +95 -0
  37. toolspotter/providers/__init__.py +33 -0
  38. toolspotter/providers/base.py +74 -0
  39. toolspotter/providers/gemini.py +136 -0
  40. toolspotter/providers/local_tfidf.py +74 -0
  41. toolspotter/state.py +131 -0
  42. toolspotter/store.py +95 -0
  43. toolspotter/ui/app.js +513 -0
  44. toolspotter/ui/effects.js +130 -0
  45. toolspotter/ui/favicon.svg +4 -0
  46. toolspotter/ui/index.html +162 -0
  47. toolspotter/ui/mark-dark.svg +3 -0
  48. toolspotter/ui/style.css +296 -0
  49. toolspotter/web.py +232 -0
  50. toolspotter-0.1.0.dist-info/METADATA +258 -0
  51. toolspotter-0.1.0.dist-info/RECORD +55 -0
  52. toolspotter-0.1.0.dist-info/WHEEL +5 -0
  53. toolspotter-0.1.0.dist-info/entry_points.txt +2 -0
  54. toolspotter-0.1.0.dist-info/licenses/LICENSE +21 -0
  55. toolspotter-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,13 @@
1
+ """toolspotter — intelligent tool routing engine (routing-as-a-service).
2
+
3
+ Filters a large enterprise tool catalog down to a small, high-precision,
4
+ ordered tool plan per user query. One engine, two entry points:
5
+
6
+ - REST API — ``toolspotter serve``
7
+ - MCP server — ``toolspotter mcp`` (exposes ``find_tools``)
8
+
9
+ See ``docs/design/architecture.md`` for the full architecture.
10
+ """
11
+
12
+ __version__ = "0.1.0"
13
+ __all__ = ["__version__"]
toolspotter/api.py ADDED
@@ -0,0 +1,437 @@
1
+ """REST API — the routing-as-a-service surface (see docs/design/architecture.md).
2
+
3
+ JSON endpoints (no auth — a documented, deliberate omission for this scope):
4
+ - POST /registry register/replace the tool catalog (onboard)
5
+ - GET /registry/tools list every tool
6
+ - GET /registry/tools/{id} read one tool
7
+ - POST /registry/tools create one tool (201)
8
+ - PUT /registry/tools/{id} replace one tool; its id cannot change
9
+ - DELETE /registry/tools/{id} delete one tool
10
+ - POST /route route one query -> selected tools + ordered plan + trace
11
+ - PATCH /registry/mutate apply a PARTIAL catalog update: {"add": [...], "remove": [...]}
12
+ (PATCH, not PUT/POST: this is a partial update of the registry
13
+ resource, not a full replace and not a bare action)
14
+ - GET /history recent requests and their totals
15
+ - DELETE /history delete the saved requests
16
+ - POST /setup save config (provider/model/key) — JSON, same as the others
17
+ - GET /health liveness + engine facts (always open, for probes)
18
+
19
+ The website (``/ui``) and the endpoints made for it (summary, preview, apply,
20
+ export, MCP scan, Postman download) are in ``web.py``.
21
+
22
+ Non-JSON exception:
23
+ - GET /setup a small server-rendered HTML form. This is a deliberate,
24
+ documented exception to the "everything is JSON" rule above:
25
+ it exists purely as a human-facing convenience so a browser can
26
+ open http://host:port/setup directly (no separate frontend, no
27
+ file editing, no interactive terminal) and POST to the same
28
+ /setup JSON endpoint. It is NOT part of the programmatic API
29
+ contract and no client should depend on its HTML shape.
30
+
31
+ One registry per service instance (single-tenant; multi-tenancy is a
32
+ documented future step). The app can boot pre-loaded via `toolspotter serve
33
+ --catalog file.json` or be fed at runtime through POST /registry.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import contextlib
39
+ import json
40
+ import threading
41
+ import time
42
+ from html import escape as _escape
43
+ from typing import Any, Optional
44
+
45
+ from pydantic import BaseModel, Field
46
+
47
+ from toolspotter import __version__
48
+ from toolspotter.config import Settings
49
+ from toolspotter.domain.errors import (
50
+ CatalogError,
51
+ DuplicateToolError,
52
+ InvalidCatalogError,
53
+ InvalidToolError,
54
+ StateError,
55
+ ToolInUseError,
56
+ ToolNotFoundError,
57
+ )
58
+ from toolspotter.domain.versioning import inherit_side_effects
59
+ from toolspotter.engine.pipeline import RoutingEngine
60
+ from toolspotter.history import MAX_ROWS, RequestHistory
61
+ from toolspotter.limits import max_input_bytes
62
+ from toolspotter.log import get_logger
63
+ from toolspotter.netutil import host_name, is_loopback
64
+ from toolspotter.state import SavedState, StateStore
65
+ from toolspotter.web import OriginCheck, PageHeaders, add_website
66
+
67
+ logger = get_logger("api")
68
+
69
+
70
+ class RegistryRequest(BaseModel):
71
+ # `Any`, so the guardrail sees every entry and can report all problems together.
72
+ tools: list[Any] = Field(..., min_length=1, description="Tool definitions")
73
+ # Optional catalog-level metadata (near_duplicate_groups etc.) is honored.
74
+ model_config = {"extra": "allow"}
75
+
76
+
77
+ class RouteRequest(BaseModel):
78
+ query: str = Field(..., min_length=1, max_length=10_000)
79
+ context: Optional[dict[str, Any]] = Field(
80
+ default=None,
81
+ description="Accepted for forward compatibility; routing does not use it yet.",
82
+ )
83
+
84
+
85
+ class MutateRequest(BaseModel):
86
+ add: list[Any] = Field(default_factory=list)
87
+ remove: list[str] = Field(default_factory=list)
88
+
89
+
90
+ class _BodyLimit:
91
+ """ASGI middleware: refuse request bodies over the limit with 413.
92
+
93
+ Counts the bytes actually received, so a missing or false Content-Length
94
+ cannot get a large body through.
95
+ """
96
+
97
+ def __init__(self, app, limit: int) -> None:
98
+ self.app, self.limit = app, limit
99
+
100
+ async def __call__(self, scope, receive, send) -> None:
101
+ if scope["type"] != "http":
102
+ await self.app(scope, receive, send)
103
+ return
104
+ chunks: list[bytes] = []
105
+ size = 0
106
+ while True:
107
+ message = await receive()
108
+ if message["type"] != "http.request":
109
+ return # client went away
110
+ chunk = message.get("body", b"")
111
+ size += len(chunk)
112
+ if size > self.limit:
113
+ body = json.dumps({"detail": f"Request body exceeds {self.limit} bytes."}).encode()
114
+ await send({"type": "http.response.start", "status": 413, "headers": [
115
+ (b"content-type", b"application/json"),
116
+ (b"content-length", str(len(body)).encode())]})
117
+ await send({"type": "http.response.body", "body": body})
118
+ return
119
+ chunks.append(chunk)
120
+ if not message.get("more_body"):
121
+ break
122
+ replayed = False
123
+
124
+ async def replay():
125
+ nonlocal replayed
126
+ if replayed:
127
+ return await receive()
128
+ replayed = True
129
+ return {"type": "http.request", "body": b"".join(chunks), "more_body": False}
130
+
131
+ await self.app(scope, replay, send)
132
+
133
+
134
+ class _HostCheck:
135
+ """ASGI middleware: answer only requests addressed to this machine.
136
+
137
+ A web page can point its own domain name at 127.0.0.1 ("DNS rebinding") and
138
+ then reach a local server from the visitor's browser. Such requests carry the
139
+ page's domain in ``Host``, so they are refused here. Loopback names are always
140
+ accepted, plus any names the operator allowed.
141
+ """
142
+
143
+ def __init__(self, app, allowed: frozenset[str]) -> None:
144
+ self.app, self.allowed = app, allowed
145
+
146
+ async def __call__(self, scope, receive, send) -> None:
147
+ if scope["type"] != "http":
148
+ await self.app(scope, receive, send)
149
+ return
150
+ values = [v for k, v in scope["headers"] if k == b"host"]
151
+ name = host_name(values[0].decode("latin-1")) if len(values) == 1 else ""
152
+ if name and (is_loopback(name) or name in self.allowed):
153
+ await self.app(scope, receive, send)
154
+ return
155
+ body = json.dumps({"detail": (
156
+ "Host header not allowed. This server answers requests for localhost; "
157
+ "start it with --allow-host NAME to accept another name."
158
+ )}).encode()
159
+ await send({"type": "http.response.start", "status": 400, "headers": [
160
+ (b"content-type", b"application/json"),
161
+ (b"content-length", str(len(body)).encode())]})
162
+ await send({"type": "http.response.body", "body": body})
163
+
164
+
165
+ def create_app(
166
+ catalog: Optional[dict[str, Any]] = None,
167
+ store: Optional[StateStore] = None,
168
+ previous: Optional[SavedState] = None,
169
+ allowed_hosts: Optional[list[str]] = None,
170
+ mcp_scan: bool = False,
171
+ ):
172
+ """App factory. Import of FastAPI is deferred so the engine can be
173
+ imported without loading the web packages."""
174
+ try:
175
+ from fastapi import FastAPI, HTTPException, Query
176
+ except ImportError as exc: # pragma: no cover
177
+ raise RuntimeError(
178
+ "FastAPI is not installed — run: pip install toolspotter"
179
+ ) from exc
180
+
181
+ history = RequestHistory(store.database_path if store else None)
182
+
183
+ @contextlib.asynccontextmanager
184
+ async def lifespan(_app):
185
+ yield
186
+ history.close() # write what is still queued
187
+
188
+ app = FastAPI(
189
+ lifespan=lifespan,
190
+ title="ToolSpotter",
191
+ version=__version__,
192
+ description="Intelligent tool routing: large catalog in, minimal ordered tool plan out.",
193
+ )
194
+ app.add_middleware(_BodyLimit, limit=max_input_bytes())
195
+ names = frozenset(host_name(h) for h in allowed_hosts or []) - {""}
196
+ app.add_middleware(PageHeaders)
197
+ app.add_middleware(OriginCheck, allowed=names)
198
+ if allowed_hosts is not None: # None = no Host check (see the CLI)
199
+ app.add_middleware(_HostCheck, allowed=names) # added last = runs first
200
+ state: dict[str, Optional[RoutingEngine]] = {"engine": None}
201
+
202
+ if catalog is not None:
203
+ state["engine"] = RoutingEngine(
204
+ catalog, settings=Settings.from_env(), store=store, previous=previous)
205
+ # One change at a time, so replacing the registry cannot race a tool edit
206
+ # (both save to the same folder). Routing never takes this lock.
207
+ registry_lock = threading.Lock()
208
+
209
+ def _engine_or_400() -> RoutingEngine:
210
+ engine = state["engine"]
211
+ if engine is None:
212
+ raise HTTPException(
213
+ status_code=409,
214
+ detail="No tool registry loaded yet — POST /registry first.",
215
+ )
216
+ return engine
217
+
218
+ @app.post("/registry")
219
+ def register(req: RegistryRequest) -> dict[str, Any]:
220
+ def replace() -> RoutingEngine:
221
+ current = state["engine"]
222
+ before = current.snapshot() if current else previous
223
+ catalog = req.model_dump()
224
+ if before:
225
+ catalog["tools"] = inherit_side_effects(catalog["tools"], before.tools)
226
+ engine = RoutingEngine(
227
+ catalog, settings=Settings.from_env(), store=store, previous=before,
228
+ )
229
+ state["engine"] = engine
230
+ return engine
231
+
232
+ engine = _change(replace)
233
+ return {
234
+ "status": "indexed",
235
+ "tool_count": engine.tool_count,
236
+ "clusters": len(engine.maps.clusters),
237
+ "near_duplicate_groups": len(engine.maps.dup_groups),
238
+ "version_families": len(engine.maps.version_families),
239
+ }
240
+
241
+ @app.post("/route")
242
+ def route(req: RouteRequest) -> dict[str, Any]:
243
+ engine = _engine_or_400()
244
+ started = time.perf_counter()
245
+ result = engine.route(req.query, context=req.context)
246
+ history.record(req.query, result, (time.perf_counter() - started) * 1000)
247
+ payload = result.to_response_dict()
248
+ payload["selected_tool_schemas"] = [
249
+ engine.raw_tool(tid) for tid in result.selected_tools
250
+ ]
251
+ payload["tokens_saved_pct"] = result.tokens_saved_pct
252
+ payload["trace"] = result.trace
253
+ return payload
254
+
255
+ @app.patch("/registry/mutate")
256
+ def mutate(req: MutateRequest) -> dict[str, Any]:
257
+ _engine_or_400()
258
+ return _change(lambda: state["engine"].apply_mutation({"add": req.add, "remove": req.remove}))
259
+
260
+ def _change(action):
261
+ """``_apply`` for operations that change the registry: one at a time."""
262
+ def locked():
263
+ with registry_lock:
264
+ return action()
265
+ return _apply(locked)
266
+
267
+ def _apply(action):
268
+ """Run a registry operation, translating its errors into HTTP responses."""
269
+ try:
270
+ return action()
271
+ except StateError as exc:
272
+ raise HTTPException(
273
+ status_code=500, detail=f"Not saved, so nothing changed: {exc}"
274
+ ) from exc
275
+ except ToolNotFoundError as exc:
276
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
277
+ except DuplicateToolError as exc:
278
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
279
+ except ToolInUseError as exc:
280
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
281
+ except InvalidCatalogError as exc: # before CatalogError, its base class
282
+ raise HTTPException(
283
+ status_code=422, detail={"reason": "INVALID_CATALOG", "rejected": exc.rejected}
284
+ ) from exc
285
+ except InvalidToolError as exc:
286
+ raise HTTPException(
287
+ status_code=422, detail={"reason": exc.reason, "issues": exc.issues}
288
+ ) from exc
289
+ except CatalogError as exc:
290
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
291
+
292
+ @app.get("/registry/tools")
293
+ def list_tools() -> dict[str, Any]:
294
+ tools = _engine_or_400().list_tools()
295
+ return {"tool_count": len(tools), "tools": tools}
296
+
297
+ @app.get("/registry/tools/{tool_id}")
298
+ def read_tool(tool_id: str) -> dict[str, Any]:
299
+ engine = _engine_or_400()
300
+ return _apply(lambda: engine.get_tool(tool_id))
301
+
302
+ @app.post("/registry/tools", status_code=201)
303
+ def create_tool(tool: dict[str, Any]) -> dict[str, Any]:
304
+ _engine_or_400()
305
+ return _change(lambda: state["engine"].create_tool(tool))
306
+
307
+ @app.put("/registry/tools/{tool_id}")
308
+ def update_tool(tool_id: str, tool: dict[str, Any]) -> dict[str, Any]:
309
+ _engine_or_400()
310
+ return _change(lambda: state["engine"].update_tool(tool_id, tool))
311
+
312
+ @app.delete("/registry/tools/{tool_id}")
313
+ def delete_tool(tool_id: str) -> dict[str, Any]:
314
+ _engine_or_400()
315
+ _change(lambda: state["engine"].delete_tool(tool_id))
316
+ return {"deleted": tool_id, "tool_count": state["engine"].tool_count}
317
+
318
+ def _history(action):
319
+ try:
320
+ return action()
321
+ except StateError as exc:
322
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
323
+
324
+ @app.get("/history")
325
+ def read_history(limit: int = Query(20, ge=0, le=MAX_ROWS)) -> dict[str, Any]:
326
+ """Totals over the saved requests, and the newest ``limit`` of them."""
327
+ return _history(lambda: {
328
+ "enabled": history.enabled,
329
+ "summary": history.summary(),
330
+ "requests": history.recent(limit),
331
+ })
332
+
333
+ @app.delete("/history")
334
+ def clear_history() -> dict[str, Any]:
335
+ return {"cleared": _history(history.clear)}
336
+
337
+ def _secret_slot(provider: str) -> Optional[str]:
338
+ """Secret name for a provider, or None if that provider takes no key.
339
+
340
+ Follows the same f"{provider}_key" convention store.py's secret names
341
+ already use (gemini_key) — generic by construction, so a
342
+ newly added provider works without touching this file.
343
+ """
344
+ return f"{provider}_key" if provider and provider != "none" else None
345
+
346
+ @app.get("/setup")
347
+ def setup_page():
348
+ """Browser Settings page — a human-facing convenience, not a JSON API
349
+ endpoint (see the module docstring). One `docker run`, open /setup,
350
+ paste the key, pick a provider and any model name, Save — no file
351
+ editing, no interactive terminal. Key is stored server-side
352
+ (keyring/0600 file), shown only as present/absent, never echoed.
353
+ Provider and model are free text — nothing here is hardcoded to a
354
+ specific provider or model; whatever is currently stored is shown.
355
+ """
356
+ from fastapi.responses import HTMLResponse
357
+ from toolspotter.store import load_secret, load_stored_config
358
+
359
+ stored = load_stored_config()
360
+ provider = str(stored.get("llm_provider", "none"))
361
+ secret_name = _secret_slot(provider)
362
+ key_state = "present" if secret_name and load_secret(secret_name) else "absent"
363
+ # Stored values are user-supplied text: escape before putting them in HTML.
364
+ e = lambda value: _escape(str(value), quote=True) # noqa: E731
365
+ html = f"""<!doctype html><title>ToolSpotter setup</title>
366
+ <style>body{{font-family:sans-serif;max-width:34rem;margin:3rem auto}}label{{display:block;margin:.8rem 0 .2rem}}input{{width:100%;padding:.4rem}}button{{margin-top:1rem;padding:.5rem 1.2rem}}</style>
367
+ <h2>ToolSpotter setup</h2>
368
+ <p>Key for provider "{e(provider)}": <b>{key_state}</b> (stored server-side, never displayed)</p>
369
+ <label>LLM provider ("none" for fully offline, or any provider name ToolSpotter supports)</label>
370
+ <input id=p value="{e(provider)}">
371
+ <label>LLM model (any model name your provider supports)</label>
372
+ <input id=m placeholder="e.g. gemini-3.5-flash-lite" value="{e(stored.get("llm_model", ""))}">
373
+ <label>Embedding provider</label>
374
+ <input id=e value="{e(stored.get("embedding_provider", "local"))}">
375
+ <label>API key (leave blank to keep current; not used for provider "none")</label>
376
+ <input id=k type=password autocomplete=off>
377
+ <button onclick="save()">Save</button><span id=s></span>
378
+ <script>async function save(){{
379
+ const body={{llm_provider:p.value,llm_model:m.value,embedding_provider:e.value}};
380
+ if(k.value) body.api_key=k.value;
381
+ const r=await fetch('/setup',{{method:'POST',headers:{{'content-type':'application/json'}},body:JSON.stringify(body)}});
382
+ s.textContent=r.ok?' saved — restart or re-register to apply':' error';k.value='';}}
383
+ </script>"""
384
+ return HTMLResponse(html)
385
+
386
+ @app.post("/setup")
387
+ def setup_save(body: dict[str, Any]) -> dict[str, Any]:
388
+ from toolspotter.store import load_stored_config, save_secret, save_stored_config
389
+
390
+ key = body.pop("api_key", None)
391
+ allowed = {k: str(v) for k, v in body.items()
392
+ if k in {"llm_provider", "llm_model", "embedding_provider"}}
393
+ if allowed:
394
+ save_stored_config(allowed)
395
+ stored_where = None
396
+ if key:
397
+ provider = allowed.get("llm_provider") or load_stored_config().get("llm_provider", "none")
398
+ secret_name = _secret_slot(provider)
399
+ if secret_name is None:
400
+ raise HTTPException(
401
+ status_code=400,
402
+ detail=f"Provider '{provider}' takes no API key.",
403
+ )
404
+ stored_where = save_secret(secret_name, key)
405
+ return {"status": "saved", "config": allowed,
406
+ "key_stored": stored_where or "unchanged"}
407
+
408
+ @app.get("/health")
409
+ def health() -> dict[str, Any]:
410
+ engine = state["engine"]
411
+ return {
412
+ "status": "ok",
413
+ "version": __version__,
414
+ "registry_loaded": engine is not None,
415
+ "tool_count": engine.tool_count if engine else 0,
416
+ "planner": type(engine.planner).__name__ if engine else None,
417
+ }
418
+
419
+ def _current_state():
420
+ engine = state["engine"]
421
+ return engine.snapshot() if engine else previous
422
+
423
+ def _apply_catalog(prepare):
424
+ """Replace the registry with the catalog ``prepare`` returns, one change at a time."""
425
+ def replace() -> None:
426
+ catalog, before = prepare()
427
+ state["engine"] = RoutingEngine(
428
+ catalog, settings=Settings.from_env(), store=store, previous=before)
429
+
430
+ _change(replace)
431
+
432
+ add_website(
433
+ app, current_engine=lambda: state["engine"], current_state=_current_state,
434
+ apply_catalog=_apply_catalog, run=_apply, saves=store is not None, mcp_scan=mcp_scan,
435
+ )
436
+
437
+ return app
@@ -0,0 +1,109 @@
1
+ """Work out what an upload would do to the registry, before doing it.
2
+
3
+ Two modes:
4
+
5
+ - ``merge``: add new tools and update existing ones; the others stay.
6
+ - ``replace``: the upload becomes the whole registry.
7
+
8
+ A tool that fails validation is skipped and reported. In ``merge`` mode the saved
9
+ definition of that id then stays; in ``replace`` mode it is removed, and the
10
+ result says so.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ from toolspotter.domain.errors import CatalogError
19
+ from toolspotter.domain.versioning import NONE, change_level, inherit_side_effects
20
+ from toolspotter.domain.naming import prepare_tool
21
+ from toolspotter.engine.guardrail import validate_catalog
22
+
23
+ MODES = ("merge", "replace")
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Change:
28
+ """What applying an upload would give."""
29
+
30
+ tools: list[dict[str, Any]] # the registry afterwards
31
+ near_duplicate_groups: list[list[str]]
32
+ added: list[str]
33
+ changed: list[str]
34
+ unchanged: list[str]
35
+ removed: list[str]
36
+ rejected: list[dict[str, Any]]
37
+
38
+ def report(self) -> dict[str, Any]:
39
+ return {
40
+ "added": self.added,
41
+ "changed": self.changed,
42
+ "unchanged": self.unchanged,
43
+ "removed": self.removed,
44
+ "rejected": self.rejected,
45
+ "tool_count_after": len(self.tools),
46
+ }
47
+
48
+
49
+ def _check_groups(groups: Any) -> list[list[str]]:
50
+ if not (isinstance(groups, list) and all(
51
+ isinstance(g, list) and all(isinstance(i, str) for i in g) for g in groups
52
+ )):
53
+ raise CatalogError("near_duplicate_groups must be a list of lists of tool ids.")
54
+ return groups
55
+
56
+
57
+ def plan_change(
58
+ current: list[dict[str, Any]],
59
+ current_groups: list[list[str]],
60
+ submitted: list[Any],
61
+ mode: str = "merge",
62
+ submitted_groups: Any = None,
63
+ ) -> Change:
64
+ """Compare an upload with the current registry. Changes nothing."""
65
+ if mode not in MODES:
66
+ raise CatalogError(f"mode must be one of {', '.join(MODES)}.")
67
+ new_groups = _check_groups([] if submitted_groups is None else submitted_groups)
68
+ saved = {t["id"]: t for t in current}
69
+
70
+ candidates = [(i, prepare_tool(t))
71
+ for i, t in enumerate(inherit_side_effects(submitted, current))]
72
+ rejected: list[dict[str, Any]] = []
73
+ # Dropping an invalid tool can make another one invalid (its replaced_by now
74
+ # points nowhere), so check again until everything left is accepted.
75
+ while True:
76
+ offered = {t["id"] for _, t in candidates
77
+ if isinstance(t, dict) and isinstance(t.get("id"), str)}
78
+ base = [t for t in current if t["id"] not in offered] if mode == "merge" else []
79
+ results = validate_catalog([*base, *(t for _, t in candidates)])[len(base):]
80
+ failed = {index: result for (index, _), result in zip(candidates, results)
81
+ if not result.accepted}
82
+ if not failed:
83
+ break
84
+ rejected.extend(
85
+ {"index": index, "id": result.tool_id, "reason": result.primary_reason,
86
+ "issues": [issue.message for issue in result.issues]}
87
+ for index, result in failed.items()
88
+ )
89
+ candidates = [(i, t) for i, t in candidates if i not in failed]
90
+ rejected.sort(key=lambda item: item["index"])
91
+
92
+ accepted = {t["id"]: t for _, t in candidates}
93
+ added = [i for i in accepted if i not in saved]
94
+ changed = [i for i, t in accepted.items()
95
+ if i in saved and change_level(saved[i], t) != NONE]
96
+ unchanged = [i for i in accepted if i in saved and i not in changed]
97
+ if mode == "merge":
98
+ tools = [accepted.get(t["id"], t) for t in current] + [accepted[i] for i in added]
99
+ removed: list[str] = []
100
+ groups = [*current_groups, *(g for g in new_groups if g not in current_groups)]
101
+ else:
102
+ tools = list(accepted.values())
103
+ removed = [i for i in saved if i not in accepted]
104
+ groups = new_groups
105
+
106
+ present = {t["id"] for t in tools}
107
+ groups = [[i for i in group if i in present] for group in groups]
108
+ return Change(tools, [g for g in groups if len(g) > 1],
109
+ added, changed, unchanged, removed, rejected)