diff --git a/CHANGELOG.md b/CHANGELOG.md index 1366428..8ead47f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ evolve; changes are additive and backwards-compatible where possible. ## [Unreleased] +### `ctx.minder`: Minder's own API for AI tools +Additive. +- `await ctx.minder.call(route, *, method="GET", query=None, json=None)` calls + a plugin-callable Minder route as the invoking user and returns its parsed + JSON. Capability `minder.api` (`CAP_MINDER_API`), granted only while the + plugin serves an AI tool call, for the tool's approved scopes. Errors: + `CapabilityDenied` (not a tool call, route not plugin-callable, scope + missing, deadline passed, refused), `CapabilityInvalid` (rejected + arguments), `CapabilityUnavailable` (unreachable, or past the deadline). + New `MinderAPI` protocol; `PlatformContext` gains `minder`. The unbound, + fake and T4 callback contexts implement it (T4 posts `{"route", "method", + "query", "body"}` to `/v1/plugin-callbacks/minder.api`). +- `AI_TOOLS` entries may declare `minder_scopes`, from the new + `context.MINDER_SCOPES`. `check_plugin` fails on a non-list or an unknown + scope; `check_plugin_warnings` warns when a tool's action calls + `ctx.minder.call` without `minder_scopes` (this becomes an error in a later + release). +- `FakePlatformContext(minder_results={(method, route): ...})`; + `for_plugin` grants `minder.api` when a tool declares `minder_scopes`. + ### `minder_t0_engine` and `minder-plugin try` - New package `minder_t0_engine`: the T0 declarative connector engine that Minder's declarative runner uses (manifest model, placeholders, JMESPath / diff --git a/README.md b/README.md index ad9e6b1..0e0a64a 100644 --- a/README.md +++ b/README.md @@ -99,10 +99,12 @@ AI_TOOLS = [ | `idempotent` | Optional `bool`: calling it twice with the same arguments has the same effect as once. | | `sensitivity` (per argument, in `parameters.properties`) | `recipient`, `url`, `amount`, `free_text`, or `bound:` (the value must equal the current user's attribute, e.g. `bound:email`). Removed from the schema the model sees. A tool-level `sensitivities: {"": ""}` map also works. | | `hosts` | Optional list of egress hosts the tool may reach (`api.example.com`, `*.example.com`). | +| `minder_scopes` | The Minder API scopes the tool needs for `ctx.minder.call` (see below), from `context.MINDER_SCOPES`: `kb.search`, `kb.read_passage`, `conversation.read_current`, `user.profile.basic`, `ticket.create_internal`, `kb.documents.ingest`. A tool call carries only the declared scopes the organisation approved. | All fields are optional in this release, so existing plugins keep loading. `check_plugin` fails on an invalid value (an unknown `effect`, a non-bool -`idempotent`, an unknown sensitivity, a malformed host). +`idempotent`, an unknown sensitivity, a malformed host, a scope outside +`MINDER_SCOPES`). `check_plugin_warnings` (printed as `WARN` by `minder-plugin validate`, which still passes) reports: @@ -114,7 +116,11 @@ still passes) reports: `method`, a recipient-like argument (`to`, `recipient`, `cc`, `bcc`, `webhook_url`, ...) or a `recipient` sensitivity. For example a `read` tool with a `to` argument, or `delete_note` declared `read`. Minder flags the same - contradictions and does not trust such a declaration. + contradictions and does not trust such a declaration; +- a tool whose action calls `ctx.minder.call` without declaring + `minder_scopes` (its calls would be denied). Only the action method's own + body is checked, not helpers it calls. This becomes an error in a later + release. `mcp_annotations(effect, idempotent)` (or `tool_annotations(tool)`) maps an effect to MCP tool annotations, for plugins that also serve their tools over MCP: @@ -236,13 +242,17 @@ class CrawlerPlugin(PluginBase): | `await ctx.documents.index(kb_id, filename, content, content_type)` | `documents.index` | Uploads on behalf of the invoking user. | | `await ctx.telegraf.set_managed_region(toml)` / `clear_managed_region()` / `reload(force=False)` | `telegraf.*` | Only for plugins with `MANAGES = ["telegraf"]`. The platform validates the TOML (allowlisted inputs, size caps) and writes it atomically. | | `await ctx.timeseries.write(lines, precision="s")` / `latest(measurement, tag_key, tag_value, fields=None)` | `timeseries.*` | Only for plugins that declare `TIMESERIES`, and only for the declared measurements. The platform sets the owner and plugin tags. `latest` returns the newest timestamp (or `None`), or `{"time", "fields"}` when `fields` is given. The `write_history` / `latest_influx_date` helpers use it when you pass `ctx=self.ctx`. | +| `await ctx.minder.call(route, *, method="GET", query=None, json=None)` | `minder.api` | Calls a plugin-callable Minder route (e.g. `/v1/knowledge-bases//documents//chunks`) as the invoking user and returns its parsed JSON. Granted only while serving an AI tool call, for the tool's approved `minder_scopes`. `json` is the request body (not on `GET`). | | `ctx.has(capability)` | — | Whether a capability is granted (`"telegraf"` matches any `telegraf.*`). | **Errors** (all subclasses of `PluginError`; messages name the capability and a reason, never the secret or payload): - `CapabilityDenied`: not granted for this invocation (undeclared, wrong - owner/tenant, expired, undeclared plugin edge). Retrying won't help. + owner/tenant, expired, undeclared plugin edge). Retrying won't help. For + `ctx.minder.call` the reason says which: not an AI tool call, not a + plugin-callable route, the token lacks the route's scope, the deadline has + passed, or the route refused the call. - `CapabilityUnavailable`: cannot be served right now. This is also what an **unbound** context raises (a contract-v1 host, or a test without a fake), so catch it to degrade cleanly. @@ -344,6 +354,10 @@ def test_secret_denied(): rejected region. - `timeseries_latest`: `{(measurement, tag_key, tag_value): point}` answers for `ctx.timeseries.latest` (an ISO timestamp, or `{"time", "fields"}`). +- `minder_results`: `{(method, route): value or callable}` answers for + `ctx.minder.call` (a callable gets `query=` and `json=`). Other routes raise + `CapabilityDenied`. The fake does not check scopes; `for_plugin` grants + `minder.api` when a tool declares `minder_scopes`. It records every call in `ctx.calls` with identifying arguments only (secret *keys*, never values; kwarg *names* for invokes; see diff --git a/src/minder_plugin_sdk/context.py b/src/minder_plugin_sdk/context.py index 83eee97..0789981 100644 --- a/src/minder_plugin_sdk/context.py +++ b/src/minder_plugin_sdk/context.py @@ -33,6 +33,7 @@ async def sync(self) -> dict: Dict, FrozenSet, Iterable, + Mapping, Optional, Protocol, Union, @@ -48,6 +49,7 @@ async def sync(self) -> dict: "DocumentsAPI", "TelegrafAPI", "TimeseriesAPI", + "MinderAPI", "UnboundPlatformContext", "UNBOUND_CONTEXT", "HOST_CAPABILITIES", @@ -59,6 +61,8 @@ async def sync(self) -> dict: "CAP_TELEGRAF_RELOAD", "CAP_TIMESERIES_WRITE", "CAP_TIMESERIES_LATEST", + "CAP_MINDER_API", + "MINDER_SCOPES", "capability_granted", ] @@ -68,7 +72,9 @@ async def sync(self) -> dict: # ``PluginMetadata.dependencies`` (plugins.invoke along those edges only), # ``REQUIRES`` (e.g. the ``rag`` bundle for documents.index) and ``MANAGES`` # (``telegraf.*`` for ``MANAGES = ["telegraf"]``) and ``TIMESERIES`` -# (``timeseries.*``, scoped to the declared measurements). +# (``timeseries.*``, scoped to the declared measurements). ``minder.api`` is +# granted per call: only to an AI tool call, for the scopes the tool declares +# in ``minder_scopes`` and the organisation approved. CAP_SECRETS_READ = "secrets.read" CAP_PLUGINS_INVOKE = "plugins.invoke" CAP_DOCUMENTS_INDEX = "documents.index" @@ -77,6 +83,20 @@ async def sync(self) -> dict: CAP_TELEGRAF_RELOAD = "telegraf.reload" CAP_TIMESERIES_WRITE = "timeseries.write" CAP_TIMESERIES_LATEST = "timeseries.latest" +CAP_MINDER_API = "minder.api" + +#: The Minder API scopes an ``AI_TOOLS`` entry may declare in ``minder_scopes``. +#: Each plugin-callable Minder route requires one of them. +MINDER_SCOPES: FrozenSet[str] = frozenset( + { + "kb.search", + "kb.read_passage", + "conversation.read_current", + "user.profile.basic", + "ticket.create_internal", + "kb.documents.ingest", + } +) HOST_CAPABILITIES: FrozenSet[str] = frozenset( { @@ -88,6 +108,7 @@ async def sync(self) -> dict: CAP_TELEGRAF_RELOAD, CAP_TIMESERIES_WRITE, CAP_TIMESERIES_LATEST, + CAP_MINDER_API, } ) @@ -202,6 +223,35 @@ async def latest( ... +@runtime_checkable +class MinderAPI(Protocol): + """Minder's own API, for an AI tool call (capability ``minder.api``). + Granted only while the plugin serves a chat tool call, and only for the + scopes the tool declares in ``minder_scopes`` (and the organisation + approved). It acts as the invoking user: Minder applies that user's + own access on every call.""" + + async def call( + self, + route: str, + *, + method: str = "GET", + query: Optional[Mapping[str, Union[str, int]]] = None, + json: Any = None, + ) -> Any: + """Call the plugin-callable Minder route ``route`` (a path such as + ``/v1/knowledge-bases//documents//chunks``) and return its + parsed JSON answer. ``json`` is the request body (not on ``GET``). + + Raises :class:`CapabilityDenied` when the call is not a tool call, + the route is not plugin-callable, the tool's token lacks the route's + scope, the deadline has passed, or Minder refuses the call; + :class:`CapabilityInvalid` when Minder rejects the arguments; + :class:`CapabilityUnavailable` when the route can't be reached or + runs past the call's deadline.""" + ... + + @runtime_checkable class PlatformContext(Protocol): """What ``self.ctx`` provides to a contract-v2 plugin.""" @@ -221,6 +271,9 @@ def telegraf(self) -> TelegrafAPI: ... @property def timeseries(self) -> TimeseriesAPI: ... + @property + def minder(self) -> MinderAPI: ... + def has(self, capability: str) -> bool: """Whether ``capability`` is granted for this binding (see :func:`capability_granted` for name matching). Use it to switch optional @@ -287,6 +340,18 @@ async def latest( raise _unbound(CAP_TIMESERIES_LATEST) +class _UnboundMinder: + async def call( + self, + route: str, + *, + method: str = "GET", + query: Optional[Mapping[str, Union[str, int]]] = None, + json: Any = None, + ) -> Any: + raise _unbound(CAP_MINDER_API) + + class UnboundPlatformContext: """The context a plugin sees before (or without) a host binding: every call raises :class:`CapabilityUnavailable` and ``has()`` is always ``False``.""" @@ -297,6 +362,7 @@ def __init__(self) -> None: self.documents = _UnboundDocuments() self.telegraf = _UnboundTelegraf() self.timeseries = _UnboundTimeseries() + self.minder = _UnboundMinder() def has(self, capability: str) -> bool: return False diff --git a/src/minder_plugin_sdk/harness.py b/src/minder_plugin_sdk/harness.py index 889f522..2f53428 100644 --- a/src/minder_plugin_sdk/harness.py +++ b/src/minder_plugin_sdk/harness.py @@ -32,6 +32,7 @@ from .capabilities import capabilities from .context import ( CAP_DOCUMENTS_INDEX, + CAP_MINDER_API, CAP_PLUGINS_INVOKE, CAP_SECRETS_READ, CAP_TELEGRAF_CLEAR_MANAGED_REGION, @@ -133,10 +134,11 @@ def check_plugin(plugin: Any) -> List[str]: def check_plugin_warnings(plugin: Any) -> List[str]: """Non-fatal findings that :func:`check_plugin` does not fail on. Empty ⇒ - nothing to report. Today: ``AI_TOOLS`` entries without an ``effect``, and - declared effects that the tool's name, method or arguments contradict - (see ``tool_effects``). A missing ``effect`` may become an error in a - later release.""" + nothing to report. Today: ``AI_TOOLS`` entries without an ``effect``, + declared effects that the tool's name, method or arguments contradict, + and tools whose action calls ``ctx.minder.call`` without + ``minder_scopes`` (see ``tool_effects``). A missing ``effect`` or + ``minder_scopes`` may become an error in a later release.""" return ai_tool_warnings(plugin) @@ -296,6 +298,32 @@ async def latest( return {"time": point.get("time"), "fields": {f: values.get(f) for f in wanted}} +class _FakeMinder: + def __init__(self, fake: "FakePlatformContext") -> None: + self._fake = fake + + async def call( + self, + route: str, + *, + method: str = "GET", + query: Optional[Mapping[str, Union[str, int]]] = None, + json: Any = None, + ) -> Any: + method = method.upper() + self._fake._enter(CAP_MINDER_API, {"route": route, "method": method}) + key = (method, route) + if key not in self._fake.minder_results: + raise CapabilityDenied( + CAP_MINDER_API, f"no fake answer for {method} {route}" + ) + handler = self._fake.minder_results[key] + if callable(handler): + result = handler(query=dict(query or {}), json=json) + return await result if inspect.isawaitable(result) else result + return handler + + class FakePlatformContext: """An in-memory :class:`~minder_plugin_sdk.context.PlatformContext` for plugin unit tests: no platform needed. @@ -317,6 +345,10 @@ class FakePlatformContext: * ``timeseries_latest``: ``{(measurement, tag_key, tag_value): point}`` for ``ctx.timeseries.latest``, where a point is an ISO timestamp or ``{"time": ..., "fields": {...}}``; an unknown series returns ``None``. + * ``minder_results``: ``{(method, route): value-or-callable}`` for + ``ctx.minder.call``; a callable gets ``query=`` and ``json=`` (may be + async). Any other route raises ``CapabilityDenied``, as Minder refuses + a route that is not plugin-callable. The fake does not check scopes. Every call (allowed or not) is appended to ``calls``. Side effects are kept in ``indexed`` (documents, with content), ``telegraf_region``, @@ -338,6 +370,7 @@ def __init__( timeseries_latest: Optional[ Mapping[Tuple[str, str, str], Union[str, Dict[str, Any]]] ] = None, + minder_results: Optional[Mapping[Tuple[str, str], InvokeHandler]] = None, ) -> None: self.secrets_store: Dict[str, str] = dict(secrets or {}) self.grants: Optional[Set[str]] = None if grants is None else set(grants) @@ -355,11 +388,15 @@ def __init__( Tuple[str, str, str], Union[str, Dict[str, Any]] ] = dict(timeseries_latest or {}) self.timeseries_lines: List[str] = [] + self.minder_results: Dict[Tuple[str, str], InvokeHandler] = { + (m.upper(), r): v for (m, r), v in (minder_results or {}).items() + } self.secrets = _FakeSecrets(self) self.plugins = _FakePlugins(self) self.documents = _FakeDocuments(self) self.telegraf = _FakeTelegraf(self) self.timeseries = _FakeTimeseries(self) + self.minder = _FakeMinder(self) @classmethod def for_plugin( @@ -377,7 +414,9 @@ def for_plugin( * ``documents.index`` when ``REQUIRES`` lists the ``rag`` bundle; * ``.*`` for each name in ``MANAGES``; * ``timeseries.*`` when ``TIMESERIES`` is declared (the platform also - limits writes to the declared measurements; this fake does not). + limits writes to the declared measurements; this fake does not); + * ``minder.api`` when an ``AI_TOOLS`` entry declares ``minder_scopes`` + (the platform grants it per tool call only). Other keyword arguments are passed to the constructor.""" grants = {CAP_SECRETS_READ} @@ -390,6 +429,11 @@ def for_plugin( grants.add(f"{name}.*") if getattr(plugin, "TIMESERIES", None) is not None: grants.add("timeseries.*") + if any( + isinstance(t, dict) and t.get("minder_scopes") + for t in getattr(plugin, "AI_TOOLS", None) or [] + ): + grants.add(CAP_MINDER_API) return cls(grants=grants, **kwargs) def has(self, capability: str) -> bool: diff --git a/src/minder_plugin_sdk/t4_callbacks.py b/src/minder_plugin_sdk/t4_callbacks.py index 907e72c..886a5b8 100644 --- a/src/minder_plugin_sdk/t4_callbacks.py +++ b/src/minder_plugin_sdk/t4_callbacks.py @@ -27,6 +27,8 @@ - ``timeseries.write``: ``{"lines": [...], "precision"}``; points written. - ``timeseries.latest``: ``{"measurement", "tag_key", "tag_value", "fields"}``; as ``ctx.timeseries.latest`` returns. +- ``minder.api``: ``{"route", "method", "query", "body"}``; the route's + parsed JSON answer. A 2xx answer is ``{"result": ...}``. Errors map to the context's exceptions: 401/403 to :class:`CapabilityDenied`; 400/404/409/413/422 to @@ -52,6 +54,7 @@ Dict, FrozenSet, Iterable, + Mapping, Optional, Union, ) @@ -59,6 +62,7 @@ from .context import ( CAP_DOCUMENTS_INDEX, + CAP_MINDER_API, CAP_PLUGINS_INVOKE, CAP_SECRETS_READ, CAP_TELEGRAF_CLEAR_MANAGED_REGION, @@ -84,6 +88,7 @@ CAP_DOCUMENTS_INDEX, CAP_TIMESERIES_WRITE, CAP_TIMESERIES_LATEST, + CAP_MINDER_API, } ) @@ -187,6 +192,29 @@ async def latest( return result +class _Minder: + def __init__(self, ctx: "CallbackPlatformContext") -> None: + self._ctx = ctx + + async def call( + self, + route: str, + *, + method: str = "GET", + query: Optional[Mapping[str, Union[str, int]]] = None, + json: Any = None, + ) -> Any: + return await self._ctx.call( + CAP_MINDER_API, + { + "route": route, + "method": method, + "query": None if query is None else dict(query), + "body": json, + }, + ) + + def _as_dict(capability: str, value: Any) -> Dict[str, Any]: if not isinstance(value, dict): raise CapabilityUnavailable(capability, "unexpected response") @@ -246,6 +274,7 @@ def __init__( self.documents = _Documents(self) self.telegraf = _Telegraf() self.timeseries = _Timeseries(self) + self.minder = _Minder(self) def has(self, capability: str) -> bool: if not capability_granted(REMOTE_CAPABILITIES, capability): diff --git a/src/minder_plugin_sdk/tool_effects.py b/src/minder_plugin_sdk/tool_effects.py index 99f2f3a..9719d7a 100644 --- a/src/minder_plugin_sdk/tool_effects.py +++ b/src/minder_plugin_sdk/tool_effects.py @@ -36,15 +36,26 @@ The egress hosts the tool may reach (``api.example.com``, or ``*.example.com`` for any subdomain). +``minder_scopes`` (list of str) + The Minder API scopes the tool needs for ``ctx.minder.call`` (one of + :data:`~minder_plugin_sdk.context.MINDER_SCOPES` each). A tool call's + ``minder.api`` grant carries only the declared scopes the organisation + approved. + ``check_plugin`` reports invalid values as errors (:func:`tool_effect_errors`); :func:`tool_effect_warnings` (via ``check_plugin_warnings``) reports a missing -``effect`` and a declaration that strong evidence contradicts. +``effect``, a declaration that strong evidence contradicts, and a tool whose +action calls ``ctx.minder.call`` without ``minder_scopes``. :func:`mcp_annotations` maps an effect to MCP tool annotations. """ +import ast +import inspect import re +import textwrap from typing import Any, Dict, List, Literal, Mapping, Optional, Tuple, TypedDict +from .context import MINDER_SCOPES from .declarations import is_host_pattern __all__ = [ @@ -94,6 +105,7 @@ class AIToolSpec(TypedDict, total=False): idempotent: bool hosts: List[str] sensitivities: Dict[str, str] + minder_scopes: List[str] def is_valid_sensitivity(value: Any) -> bool: @@ -426,13 +438,46 @@ def tool_effect_errors(plugin: Any) -> List[str]: f"tool {name!r} host {host!r} must be a lowercase host " "name or *.domain pattern (no scheme, port or path)" ) + scopes = tool.get("minder_scopes") + if scopes is not None: + if not isinstance(scopes, (list, tuple)): + errors.append(f"tool {name!r} 'minder_scopes' must be a list of scopes") + else: + for scope in scopes: + if not isinstance(scope, str) or scope not in MINDER_SCOPES: + errors.append( + f"tool {name!r} minder scope {scope!r} must be one of " + f"{', '.join(sorted(MINDER_SCOPES))}" + ) return errors +def _calls_minder_api(plugin: Any, action: Any) -> bool: + """Whether the action method's own code calls ``<...>.minder.call(...)``. + + shortcut: only the action method's body is read, not the helpers it + calls; follow calls if plugins start hiding ``ctx.minder`` in helpers.""" + cls = plugin if isinstance(plugin, type) else type(plugin) + method: Any = getattr(cls, action, None) if isinstance(action, str) else None + try: + tree = ast.parse(textwrap.dedent(inspect.getsource(method))) + except (TypeError, OSError, SyntaxError): + return False + return any( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "call" + and isinstance(node.func.value, ast.Attribute) + and node.func.value.attr == "minder" + for node in ast.walk(tree) + ) + + def tool_effect_warnings(plugin: Any) -> List[str]: """Non-fatal findings on the plugin's ``AI_TOOLS``: a tool without - ``effect``, a sensitivity on an argument the schema doesn't define, and a - declared ``effect`` that strong evidence contradicts (evidence stricter + ``effect``, a sensitivity on an argument the schema doesn't define, a + tool whose action calls ``ctx.minder.call`` without ``minder_scopes``, and + a declared ``effect`` that strong evidence contradicts (evidence stricter than the declaration, e.g. ``read`` with a ``recipient`` argument, or a ``send_*`` / ``delete_*`` tool declared ``read``).""" warnings: List[str] = [] @@ -454,6 +499,14 @@ def tool_effect_warnings(plugin: Any) -> List[str]: f"tool {name!r} declares a sensitivity for {arg!r}, " "which is not one of its parameters" ) + if not tool.get("minder_scopes") and _calls_minder_api( + plugin, tool.get("action") + ): + warnings.append( + f"tool {name!r} calls ctx.minder.call but declares no " + "'minder_scopes'; its calls will be denied (this becomes an " + "error in a later release)" + ) if effect not in _RANK: continue for signal, evidence in _strong_evidence(tool): diff --git a/tests/test_context.py b/tests/test_context.py index b797d85..11ada35 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -37,6 +37,7 @@ def test_unbound_context_conforms_and_has_nothing(): (lambda c: c.telegraf.set_managed_region("[x]"), "telegraf.set_managed_region"), (lambda c: c.telegraf.clear_managed_region(), "telegraf.clear_managed_region"), (lambda c: c.telegraf.reload(force=True), "telegraf.reload"), + (lambda c: c.minder.call("/v1/x"), "minder.api"), ], ) def test_unbound_calls_raise_unavailable(call, capability): diff --git a/tests/test_fake_context.py b/tests/test_fake_context.py index d076b2f..8b54297 100644 --- a/tests/test_fake_context.py +++ b/tests/test_fake_context.py @@ -167,3 +167,31 @@ class Decl(PluginBase): bare = FakePlatformContext.for_plugin(PluginBase(), dependencies=["telegraf"]) assert bare.has("plugins.invoke") assert not bare.has("telegraf") and not bare.has("documents.index") + + +def test_minder_call_answers_configured_routes_only(): + seen = {} + + def chunks(query, json): + seen.update(query=query, json=json) + return [{"text": "x"}] + + ctx = FakePlatformContext(minder_results={("get", "/v1/a"): chunks}) + assert run(ctx.minder.call("/v1/a", query={"n": 1})) == [{"text": "x"}] + assert seen == {"query": {"n": 1}, "json": None} + assert [c.args for c in ctx.called("minder.api")] == [ + {"route": "/v1/a", "method": "GET"} + ] + with pytest.raises(CapabilityDenied): + run(ctx.minder.call("/v1/a", method="POST", json={})) + + +def test_minder_call_needs_the_grant(): + class P(PluginBase): + AI_TOOLS = [{"name": "t", "action": "t", "minder_scopes": ["kb.search"]}] + + assert FakePlatformContext.for_plugin(P()).has("minder.api") + ctx = FakePlatformContext.for_plugin(object()) + assert not ctx.has("minder.api") + with pytest.raises(CapabilityDenied): + run(ctx.minder.call("/v1/a")) diff --git a/tests/test_t4_callbacks.py b/tests/test_t4_callbacks.py index 629b6f2..a53502e 100644 --- a/tests/test_t4_callbacks.py +++ b/tests/test_t4_callbacks.py @@ -152,6 +152,19 @@ def test_callback_base_path_and_default_port_are_handled(): {"measurement": "m", "tag_key": "a", "tag_value": "1", "fields": ["v"]}, {"time": "2026-01-01T00:00:00Z", "fields": {"v": 1}}, ), + ( + lambda c: c.minder.call( + "/v1/kb/k1/items", method="POST", query={"n": 2}, json={"a": 1} + ), + "minder.api", + { + "route": "/v1/kb/k1/items", + "method": "POST", + "query": {"n": 2}, + "body": {"a": 1}, + }, + [{"id": "c1"}], + ), ], ) def test_each_capability_posts_its_body(call, capability, body, result): diff --git a/tests/test_tool_effects.py b/tests/test_tool_effects.py index b426b35..285a390 100644 --- a/tests/test_tool_effects.py +++ b/tests/test_tool_effects.py @@ -64,6 +64,10 @@ def _props(*names: str, **sensitivities: str) -> Dict[str, Any]: ({"hosts": ["https://api.example.com"]}, ["host 'https://api.example.com'"]), ({"hosts": ["api.example.com:443"]}, ["host 'api.example.com:443'"]), ({"hosts": ["*.com"]}, ["host '*.com'"]), + ({"minder_scopes": ["kb.read_passage", "kb.search"]}, []), + ({"minder_scopes": "kb.search"}, ["'minder_scopes' must be a list"]), + ({"minder_scopes": ["kb.admin"]}, ["minder scope 'kb.admin' must be one of"]), + ({"minder_scopes": [{"x": 1}]}, ["minder scope {'x': 1} must be one of"]), ], ) def test_effect_errors(tool: Dict[str, Any], expected: List[str]) -> None: @@ -285,3 +289,40 @@ def test_build_tool_definitions_strips_sensitivity() -> None: } # The plugin's own declaration is left untouched. assert params["properties"]["to"]["sensitivity"] == "recipient" + + +# ── minder_scopes: a tool that calls ctx.minder.call must declare them ─────── +class _MinderCaller(PluginBase): + ACTIONS = frozenset({"read_passage"}) + AI_TOOLS: List[Dict[str, Any]] = [ + {"name": "read_passage", "action": "read_passage", "effect": "read"} + ] + + async def register(self) -> PluginMetadata: + return PluginMetadata(name="p", version="1", description="d", author="a") + + async def read_passage(self, kb_id: str, doc_id: str) -> Any: + return await self.ctx.minder.call( + f"/v1/knowledge-bases/{kb_id}/documents/{doc_id}/chunks" + ) + + +def test_minder_call_without_scopes_is_a_warning_not_an_error() -> None: + plugin = _MinderCaller() + assert check_plugin(plugin) == [] + warnings = check_plugin_warnings(plugin) + assert len(warnings) == 1 + assert "'read_passage' calls ctx.minder.call" in warnings[0] + assert "error in a later release" in warnings[0] + + +def test_minder_call_with_scopes_is_clean() -> None: + class Declared(_MinderCaller): + AI_TOOLS = [{**_MinderCaller.AI_TOOLS[0], "minder_scopes": ["kb.read_passage"]}] + + assert check_plugin(Declared()) == [] + assert check_plugin_warnings(Declared()) == [] + + +def test_tool_without_minder_call_needs_no_scopes() -> None: + assert check_plugin_warnings(_plugin(effect="read")) == []