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
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 /
Expand Down
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<attr>` (the value must equal the current user's attribute, e.g. `bound:email`). Removed from the schema the model sees. A tool-level `sensitivities: {"<arg>": "<value>"}` 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:

Expand All @@ -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:
Expand Down Expand Up @@ -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/<kb>/documents/<doc>/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.
Expand Down Expand Up @@ -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
Expand Down
68 changes: 67 additions & 1 deletion src/minder_plugin_sdk/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ async def sync(self) -> dict:
Dict,
FrozenSet,
Iterable,
Mapping,
Optional,
Protocol,
Union,
Expand All @@ -48,6 +49,7 @@ async def sync(self) -> dict:
"DocumentsAPI",
"TelegrafAPI",
"TimeseriesAPI",
"MinderAPI",
"UnboundPlatformContext",
"UNBOUND_CONTEXT",
"HOST_CAPABILITIES",
Expand All @@ -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",
]

Expand All @@ -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"
Expand All @@ -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(
{
Expand All @@ -88,6 +108,7 @@ async def sync(self) -> dict:
CAP_TELEGRAF_RELOAD,
CAP_TIMESERIES_WRITE,
CAP_TIMESERIES_LATEST,
CAP_MINDER_API,
}
)

Expand Down Expand Up @@ -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/<kb>/documents/<doc>/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."""
Expand All @@ -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
Expand Down Expand Up @@ -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``."""
Expand All @@ -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
Expand Down
54 changes: 49 additions & 5 deletions src/minder_plugin_sdk/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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.
Expand All @@ -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``,
Expand All @@ -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)
Expand All @@ -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(
Expand All @@ -377,7 +414,9 @@ def for_plugin(
* ``documents.index`` when ``REQUIRES`` lists the ``rag`` bundle;
* ``<name>.*`` 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}
Expand All @@ -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:
Expand Down
Loading
Loading