diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ead47f..c76246b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ evolve; changes are additive and backwards-compatible where possible. ## [Unreleased] +### T0 `minder_api` step +Additive. +- A declarative step may be `minder_api: {route, method, query, body}` + instead of `request`. It calls Minder's own API through the invocation's + `ctx.minder` (capability `minder.api`) and is not egress. Its parsed answer + is the step's result, as with an HTTP step (`select`, `when`, `foreach`, + `steps.`). It counts toward the per-invocation request cap. A + `minder_api` result can feed a later `request` step, so the data can reach + the plugin's egress hosts. A tool whose plugin declares egress counts as + egressing for local-only content. +- Only a tool that declares `minder_scopes` (new on a declarative tool, + from `context.MINDER_SCOPES`) can use it. The route must start with `/v1/` + and the method must be GET or POST, with a body on POST only (the schema + refuses a body on GET too). Actions, the + schedule and tools without `minder_scopes` are refused at load. +- `minder_t0_engine.Invocation` gains `minder` (the `ctx.minder` handle). + Without it a `minder_api` step raises `CapabilityDenied`. `Operation` + gains `minder_scopes`. The declarative schema gains the `minderApi` + definition, `step.minder_api` and `operation.minder_scopes`. + ### `ctx.minder`: Minder's own API for AI tools Additive. - `await ctx.minder.call(route, *, method="GET", query=None, json=None)` calls diff --git a/README.md b/README.md index 0e0a64a..ad41e9e 100644 --- a/README.md +++ b/README.md @@ -391,6 +391,34 @@ minder-plugin try manifest.yml convert --args '...' --replay fixtures/ - Recordings keep response headers except cookies and hop-by-hop headers; review them before you commit them. +A tool may also call Minder's own API with a `minder_api` step instead of a +`request`. The tool must declare `minder_scopes`, and the step runs through +`ctx.minder.call` (capability `minder.api`) as the invoking user. It is not +egress, so no egress rule applies to it. Its parsed answer is the step's result, +as with an HTTP step, so `select`, `when`, `foreach` and later steps work the same +way. Actions and the schedule can't use it. `minder-plugin try` binds no +`ctx.minder`, so a `minder_api` step is denied there. + +A `minder_api` result can feed a later `request` step, so the data it reads can +reach the plugin's egress hosts. Minder therefore treats a tool whose plugin +declares any egress as egressing when it decides about local-only content. + +```yaml +tools: + passages: + description: Search the knowledge base. + minder_scopes: [kb.search] + parameters: {type: object, properties: {kb: {type: string}, q: {type: string}}} + steps: + - name: hits + minder_api: + route: "/v1/knowledge-bases/{params.kb}/search" # starts with /v1/ + method: POST # GET (default) or POST + query: {limit: 5} + body: {query: "{params.q}"} # POST only + select: results +``` + ## Worked example [`examples/weather_plugin.py`](examples/weather_plugin.py) is a complete, diff --git a/src/minder_plugin_sdk/schemas/declarative-manifest.schema.json b/src/minder_plugin_sdk/schemas/declarative-manifest.schema.json index 9dcd516..8e41a56 100644 --- a/src/minder_plugin_sdk/schemas/declarative-manifest.schema.json +++ b/src/minder_plugin_sdk/schemas/declarative-manifest.schema.json @@ -2,7 +2,7 @@ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://minderhq.github.io/docs/schemas/declarative-manifest.v1alpha1.json", "title": "Minder Declarative Connector Manifest", - "description": "A declarative (T0) connector: HTTP tools, actions, a schedule and an inbound webhook expressed as data, run by Minder's connector engine with no plugin code. This schema checks the structure. At load the engine also checks what JSON Schema cannot express: every base host is in the declared egress, placeholders and JMESPath expressions compile, auth fields fit the auth type, step names are unique, measurements are declared, a webhook action exists and takes a 'body' parameter, and at most 32 tools and actions in total.", + "description": "A declarative (T0) connector: HTTP tools, actions, a schedule and an inbound webhook expressed as data, run by Minder's connector engine with no plugin code. This schema checks the structure. At load the engine also checks what JSON Schema cannot express: every base host is in the declared egress, placeholders and JMESPath expressions compile, auth fields fit the auth type, step names are unique, a minder_api step appears only in a tool that declares minder_scopes and its route has no empty, '.' or '..' segment, no minder_scopes entry is listed twice, measurements are declared, a webhook action exists and takes a 'body' parameter, and at most 32 tools and actions in total.", "type": "object", "required": [ "apiVersion", @@ -225,12 +225,25 @@ "properties": { "effect": { "type": "null" + }, + "minder_scopes": { + "maxItems": 0 + }, + "steps": { + "type": "array", + "items": { + "properties": { + "minder_api": { + "type": "null" + } + } + } } } } ] }, - "description": "Actions (not exposed as AI tools). An action declares no effect." + "description": "Actions (not exposed as AI tools). An action declares no effect, no minder_scopes and no minder_api step." }, "schedule": { "anyOf": [ @@ -632,11 +645,61 @@ }, "additionalProperties": false }, + "minderApi": { + "type": "object", + "description": "A call to Minder's own API through the platform's minder.api capability, as the invoking user and for the tool's approved minder_scopes. Not external egress.", + "required": [ + "route" + ], + "properties": { + "route": { + "type": "string", + "minLength": 4, + "maxLength": 2048, + "pattern": "^/v1/[^?#]*$", + "description": "A plugin-callable Minder route, starting with '/v1/'; placeholders are path-encoded." + }, + "method": { + "enum": [ + "GET", + "POST" + ], + "default": "GET" + }, + "query": { + "type": "object", + "additionalProperties": { + "type": [ + "string", + "number", + "boolean" + ] + } + }, + "body": { + "description": "The JSON request body (POST only); string values are placeholders." + } + }, + "additionalProperties": false, + "if": { + "properties": { + "method": { + "const": "GET" + } + } + }, + "then": { + "properties": { + "body": { + "type": "null" + } + } + } + }, "step": { "type": "object", "required": [ - "name", - "request" + "name" ], "properties": { "name": { @@ -644,7 +707,24 @@ "pattern": "^[a-z][a-z0-9_]{0,63}$" }, "request": { - "$ref": "#/definitions/request" + "anyOf": [ + { + "$ref": "#/definitions/request" + }, + { + "type": "null" + } + ] + }, + "minder_api": { + "anyOf": [ + { + "$ref": "#/definitions/minderApi" + }, + { + "type": "null" + } + ] }, "when": { "anyOf": [ @@ -686,7 +766,30 @@ ] } }, - "additionalProperties": false + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "request" + ], + "properties": { + "request": { + "type": "object" + } + } + }, + { + "required": [ + "minder_api" + ], + "properties": { + "minder_api": { + "type": "object" + } + } + } + ], + "description": "One step: an HTTP 'request' through the plugin's egress, or a 'minder_api' call to Minder's own API (not egress). Exactly one of the two." }, "timeseriesWrite": { "type": "object", @@ -831,6 +934,21 @@ "type": "null" } ] + }, + "minder_scopes": { + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "conversation.read_current", + "kb.documents.ingest", + "kb.read_passage", + "kb.search", + "ticket.create_internal", + "user.profile.basic" + ] + }, + "description": "Tools only: the Minder API scopes its minder_api steps use." } }, "additionalProperties": false @@ -872,8 +990,20 @@ "minItems": 1, "maxItems": 3, "items": { - "$ref": "#/definitions/step" - } + "allOf": [ + { + "$ref": "#/definitions/step" + }, + { + "properties": { + "minder_api": { + "type": "null" + } + } + } + ] + }, + "description": "The schedule's steps; no minder_api step (that is for AI tools only)." }, "measurement": { "type": "string", diff --git a/src/minder_t0_engine/engine.py b/src/minder_t0_engine/engine.py index a2f444d..7929e63 100644 --- a/src/minder_t0_engine/engine.py +++ b/src/minder_t0_engine/engine.py @@ -22,6 +22,14 @@ written}``. The schedule's collect (:meth:`Engine.run_collect`) does the same: its result is that object, or its declared ``output`` mapped over the same context; its ``error_output`` stands in for a failure like an operation's. + +A ``minder_api`` step (only in a tool that declares ``minder_scopes``) calls +Minder's own API through the invocation's ``minder`` handle (the platform +context's ``minder.api`` capability), not through the plugin's egress: no +egress rule, rate or concurrency limit applies, but it counts toward the +per-invocation request cap. Its parsed answer is the step's result, like an +HTTP response. Without a bound handle the step raises ``CapabilityDenied``; +the capability's own errors propagate unchanged. """ import asyncio @@ -48,6 +56,8 @@ import httpx from jmespath.parser import ParsedResult from minder_plugin_sdk import line_protocol +from minder_plugin_sdk.context import CAP_MINDER_API +from minder_plugin_sdk.errors import CapabilityDenied from .egress import AuthInjection, Fetched, PluginEgress from .errors import ( @@ -67,6 +77,7 @@ MAX_REQUESTS_PER_INVOCATION, Base, DeclarativeManifest, + MinderCall, Operation, Request, Step, @@ -167,14 +178,30 @@ class TimeseriesSink(Protocol): async def write(self, lines: Any, precision: str = "s") -> int: ... +class MinderCaller(Protocol): + """The platform context's ``minder`` handle (``ctx.minder``), granted for + the invoking tool call's scopes.""" + + async def call( + self, + route: str, + *, + method: str = "GET", + query: Optional[Mapping[str, Any]] = None, + json: Any = None, + ) -> Any: ... + + @dataclass class Invocation: """What one call runs with. Built per call; never stored by the engine. - ``timeseries`` is where an action's points go (none: nothing written).""" + ``timeseries`` is where an action's points go (none: nothing written); + ``minder`` is what a ``minder_api`` step calls (none: denied).""" config: Mapping[str, Any] secrets: SecretSource timeseries: Optional[TimeseriesSink] = None + minder: Optional[MinderCaller] = None def scrub(value: Any, secrets: Iterable[str]) -> Any: @@ -355,8 +382,29 @@ async def _fetch( ) return body, fetched + async def _minder(self, call: MinderCall, ctx: Mapping[str, Any]) -> Any: + if self.inv.minder is None: + raise CapabilityDenied(CAP_MINDER_API, "not bound to this invocation") + route = render(call.route, ctx, PATH) or "" + # The load check again, on the rendered route: an empty value can + # still leave an empty segment. + if any(seg in ("", ".", "..") for seg in route[1:].split("/")): + raise MappingError("minder_api route has an empty, '.' or '..' segment") + query = self._pairs(call.query, ctx, QUERY) + body = self._json(call.json_body, ctx) if call.has_json else None + self.requests += 1 + if self.requests > MAX_REQUESTS_PER_INVOCATION: + raise LimitExceeded("requests per invocation") + return await self.inv.minder.call( + route, method=call.method, query=query or None, json=body + ) + async def request(self, step: Step, ctx: Mapping[str, Any]) -> Any: + if step.minder is not None: + data = await self._minder(step.minder, ctx) + return search(step.select, data) if step.select is not None else data req = step.request + assert req is not None # compile: exactly one of request / minder_api url, origin = self._url(req, ctx) query = self._pairs(req.query, ctx, QUERY) headers = self._pairs(req.headers, ctx, HEADER) diff --git a/src/minder_t0_engine/model.py b/src/minder_t0_engine/model.py index c8eba5a..863184f 100644 --- a/src/minder_t0_engine/model.py +++ b/src/minder_t0_engine/model.py @@ -35,6 +35,8 @@ parameters: {type: object, properties: {...}, required: [...]} effect: read # optional, tools only: read|write| # send|destructive (tool effect class) + minder_scopes: [kb.search] # optional, tools only: the Minder + # API scopes its minder_api steps use vars: # JMESPath over {params, config, now} frm: upper(trim(params.from_currency)) to: upper(trim(params.to_currency)) @@ -49,6 +51,16 @@ # empty_body: null|error, and for response: xml # xml: {namespaces: drop|keep, prefixes: {atom: }} select: rates # JMESPath over the response + # A tool that declares minder_scopes may instead call Minder's + # own API through the platform's minder.api capability (not + # egress; acting as the invoking user, for the approved scopes): + # - name: passages + # minder_api: + # route: "/v1/knowledge-bases/{params.kb}/search" + # method: POST # GET (default) or POST + # query: {limit: 5} + # body: {query: "{params.q}"} # POST only + # select: results output: "{result: multiply(params.amount, values(steps.rate)[0])}" # On a failure: error_output (JMESPath over {params, config, error} # only; never a response or a secret) and, where it yields null, @@ -97,6 +109,7 @@ from jmespath.parser import ParsedResult from jsonschema import Draft7Validator from jsonschema.exceptions import SchemaError +from minder_plugin_sdk.context import MINDER_SCOPES from pydantic import BaseModel, ConfigDict, Field, ValidationError from .egress_policy import EgressPolicyError, check_host @@ -256,9 +269,18 @@ class RequestModel(_Model): accept_status: List[int] = Field(default_factory=list) +class MinderApiModel(_Model): + route: str = Field(min_length=4, max_length=2048) + method: Literal["GET", "POST"] = "GET" + query: Dict[str, Scalar] = Field(default_factory=dict) + body: Optional[Any] = None + + class StepModel(_Model): name: str - request: RequestModel + # Exactly one of the two (checked at compile). + request: Optional[RequestModel] = None + minder_api: Optional[MinderApiModel] = None when: Optional[str] = None foreach: Optional[str] = None max_items: int = Field(10, ge=1, le=MAX_FANOUT) @@ -285,6 +307,7 @@ class OperationModel(_Model): admin_only: bool = False timeseries: Optional[TimeseriesWriteModel] = None effect: Optional[Literal["read", "write", "send", "destructive"]] = None + minder_scopes: List[str] = Field(default_factory=list) class ScheduleModel(_Model): @@ -432,16 +455,32 @@ class Request: xml_prefixes: Tuple[Tuple[str, str], ...] = () +@dataclass(frozen=True) +class MinderCall: + """A call to Minder's own API (capability ``minder.api``), made through + the invocation's platform context rather than the plugin's egress.""" + + method: str + #: The route path, starting ``/v1/``; placeholders are path-encoded. + route: Template + query: Tuple[Tuple[str, Template], ...] + json_body: Any + has_json: bool + + @dataclass(frozen=True) class Step: name: str - request: Request + #: The HTTP request, or None for a ``minder_api`` step. + request: Optional[Request] foreach: Optional[ParsedResult] max_items: int select: Optional[ParsedResult] #: JMESPath over the context; a falsy result skips the step (its result #: is null and no request is made). when: Optional[ParsedResult] = None + #: A ``minder_api`` step's call (then ``request`` is None). + minder: Optional[MinderCall] = None #: Declared values: (name, JMESPath over {params, config, now}), in order. @@ -479,6 +518,9 @@ class Operation: #: A tool's declared effect class, served with its AI tool so the #: registry's tool-effect analysis sees the declaration. effect: Optional[str] = None + #: A tool's declared Minder API scopes, served with its AI tool so the + #: platform grants ``minder.api`` for them (and only them). + minder_scopes: Tuple[str, ...] = () @dataclass(frozen=True) @@ -914,6 +956,37 @@ def _request( ) +def _minder_call(raw: MinderApiModel, where: str, scope: _Scope) -> MinderCall: + route = raw.route + if not route.startswith("/v1/"): + raise ManifestError(f"{where}.route: a Minder route starting with '/v1/'") + if "?" in route or "#" in route: + raise ManifestError(f"{where}.route: use 'query', not '?' in the route") + if any(seg in ("", ".", "..") for seg in route[1:].split("/")): + raise ManifestError(f"{where}.route: no empty, '.' or '..' segments") + route_t = scope.check(parse_template(route, f"{where}.route"), f"{where}.route") + query: List[Tuple[str, Template]] = [] + for key, value in raw.query.items(): + if not _PARAM_NAME.match(key): + raise ManifestError(f"{where}.query: {key!r} is not a valid name") + text = value if isinstance(value, str) else literal_text(value) + query.append( + (key, scope.check(parse_template(text, f"{where}.query.{key}"), where)) + ) + has_json = raw.body is not None + if has_json and raw.method == "GET": + raise ManifestError(f"{where}.body: GET takes no body") + return MinderCall( + method=raw.method, + route=route_t, + query=tuple(query), + json_body=( + _json_templates(raw.body, f"{where}.body", scope) if has_json else None + ), + has_json=has_json, + ) + + def _xml_prefixes(raw: RequestModel, where: str) -> Tuple[Tuple[str, str], ...]: """The ``xml`` option, checked: only on an XML response; ``prefixes`` (prefix -> namespace URI) only with ``namespaces: keep``, each prefix a @@ -945,7 +1018,10 @@ def _steps( where: str, bases: Dict[str, Base], scope: _Scope, + minder: bool = False, ) -> Tuple[Step, ...]: + """``minder``: whether ``minder_api`` steps are allowed here (a tool that + declares ``minder_scopes``).""" seen: List[str] = [] out: List[Step] = [] for i, raw in enumerate(raws): @@ -960,10 +1036,25 @@ def _steps( item=raw.foreach is not None, vars=scope.vars, ) + if (raw.request is None) == (raw.minder_api is None): + raise ManifestError(f"{w}: exactly one of 'request' or 'minder_api'") + if raw.minder_api is not None and not minder: + raise ManifestError( + f"{w}.minder_api: only in an AI tool that declares minder_scopes" + ) out.append( Step( name=raw.name, - request=_request(raw.request, f"{w}.request", bases, step_scope), + request=( + _request(raw.request, f"{w}.request", bases, step_scope) + if raw.request is not None + else None + ), + minder=( + _minder_call(raw.minder_api, f"{w}.minder_api", step_scope) + if raw.minder_api is not None + else None + ), foreach=( compile_expr(raw.foreach, f"{w}.foreach") if raw.foreach is not None @@ -1067,6 +1158,13 @@ def _operation( raise ManifestError(f"{where}.effect: only an AI tool declares an effect") if raw.effect == "read" and not read_only: raise ManifestError(f"{where}.effect: a read tool must be read_only") + if raw.minder_scopes and kind != "tool": + raise ManifestError(f"{where}.minder_scopes: only an AI tool declares them") + for s in raw.minder_scopes: + if s not in MINDER_SCOPES: + raise ManifestError(f"{where}.minder_scopes: {s!r} is not a Minder scope") + if len(set(raw.minder_scopes)) != len(raw.minder_scopes): + raise ManifestError(f"{where}.minder_scopes: a scope is listed twice") timeseries: Optional[TimeseriesWrite] = None if raw.timeseries is not None: # A write is a side effect: never from an AI tool or a read-only action. @@ -1084,7 +1182,7 @@ def _operation( description=raw.description, parameters=schema, validator=Draft7Validator(schema), - steps=_steps(raw.steps, where, bases, scope), + steps=_steps(raw.steps, where, bases, scope, minder=bool(raw.minder_scopes)), output=( compile_expr(raw.output, f"{where}.output") if raw.output is not None @@ -1101,6 +1199,7 @@ def _operation( timeseries=timeseries, vars=variables, effect=raw.effect, + minder_scopes=tuple(raw.minder_scopes), ) diff --git a/tests/fixtures/declarative/every_field.yml b/tests/fixtures/declarative/every_field.yml index 4e6fdbe..44e7637 100644 --- a/tests/fixtures/declarative/every_field.yml +++ b/tests/fixtures/declarative/every_field.yml @@ -81,6 +81,23 @@ spec: output: "{hits: steps.hits, detail: steps.detail}" error_output: "{error: error.kind}" on_error: {error: unavailable} + passages: + description: Search a knowledge base through Minder's own API. + effect: read + minder_scopes: [kb.search] + parameters: + type: object + properties: + kb: {type: string} + q: {type: string} + steps: + - name: hits + minder_api: + route: "/v1/knowledge-bases/{params.kb}/search" + method: POST + query: {limit: 5} + body: {query: "{params.q}"} + select: results actions: ingest: description: Store a delivered event. diff --git a/tests/test_manifest_schemas.py b/tests/test_manifest_schemas.py index f118ce6..c425a27 100644 --- a/tests/test_manifest_schemas.py +++ b/tests/test_manifest_schemas.py @@ -213,6 +213,7 @@ def _mutate(path: str, value: Any = None, delete: bool = False) -> Dict[str, Any "spec.tools.search.steps.0.extra", "spec.tools.search.steps.0.request.extra", "spec.tools.search.steps.0.request.paginate.extra", + "spec.tools.passages.steps.0.minder_api.extra", "spec.actions.ingest.steps.0.request.body.extra", "spec.actions.feed.steps.0.request.xml.extra", "spec.actions.feed.timeseries.extra", @@ -241,6 +242,8 @@ def test_unknown_fields_are_refused_at_every_level(path): "spec.tools.search.steps.0.name", "spec.tools.search.steps.0.request", "spec.tools.search.steps.0.request.base", + "spec.tools.passages.steps.0.minder_api", + "spec.tools.passages.steps.0.minder_api.route", "spec.tools.search.steps.0.request.paginate.type", "spec.actions.feed.timeseries.points", "spec.schedule.steps", @@ -272,6 +275,14 @@ def test_required_fields_are_required(path): ("spec.tools.search.steps.0.request.paginate.max_pages", 11), ("spec.tools.search.steps.0.request.query", {"q": ["a"]}), ("spec.tools.search.effect", "maybe"), + ("spec.tools.passages.steps.0.minder_api.method", "PUT"), + ("spec.tools.passages.steps.0.minder_api.route", "/api/v1/x"), + ("spec.tools.passages.steps.0.minder_api.route", "https://h/v1/x"), + ("spec.tools.passages.steps.0.minder_api.route", "/v1/x?y=1"), + ("spec.tools.passages.steps.0.minder_api.query", {"q": ["a"]}), + ("spec.tools.passages.minder_scopes", ["kb.nope"]), + ("spec.tools.passages.minder_scopes", ["kb.search", "kb.search"]), + ("spec.tools.passages.minder_scopes", "kb.search"), ("spec.tools.search.parameters", {"type": "array"}), ("spec.tools.search.description", ""), ("spec.tools.search.steps.0.name", "Bad-Name"), @@ -307,6 +318,32 @@ def test_a_tool_cannot_write_time_series_and_an_action_has_no_effect(): assert _errors(manifest) +def test_a_step_is_a_request_or_a_minder_api_call_and_only_tools_call_minder(): + manifest = _load(EVERY_FIELD) + step = manifest["spec"]["tools"]["passages"]["steps"][0] + both = copy.deepcopy(manifest) + both["spec"]["tools"]["passages"]["steps"][0]["request"] = {"base": "api"} + assert _errors(both) + for key in ("actions.feed", "schedule"): + m = copy.deepcopy(manifest) + node: Any = m["spec"] + for k in key.split("."): + node = node[k] + node["steps"] = [step] + assert _errors(m), key + m = copy.deepcopy(manifest) + m["spec"]["actions"]["feed"]["minder_scopes"] = ["kb.search"] + assert _errors(m) + get = copy.deepcopy(manifest) + call = get["spec"]["tools"]["passages"]["steps"][0]["minder_api"] + call["method"] = "GET" + assert _errors(get) # a body on GET, as the engine refuses + del call["method"] # GET by default + assert _errors(get) + call["body"] = None + assert _errors(get) == [] + + def test_a_connector_needs_a_tool_an_action_or_a_schedule(): manifest = _load(EVERY_FIELD) for key in ("tools", "actions", "schedule", "webhook"): @@ -326,6 +363,7 @@ def test_optional_fields_accept_null(): "spec.tools.search.output", "spec.tools.search.read_only", "spec.tools.search.steps.0.when", + "spec.tools.passages.steps.0.minder_api.body", "spec.tools.search.steps.0.request.paginate", "spec.tools.search.steps.0.request.follow_redirects", "spec.schedule.cron", diff --git a/tests/test_t0_engine.py b/tests/test_t0_engine.py index 9ff9423..a9a909b 100644 --- a/tests/test_t0_engine.py +++ b/tests/test_t0_engine.py @@ -2416,3 +2416,173 @@ async def test_schedule_vars_feed_its_request(): lines = await engine(data, up).run_schedule(inv({"FX_BASE": " try "})) assert up.requests[0].url.params["from"] == "TRY" assert lines[0] == "fx_rate,base=TRY,quote=USD rate=1.1" + + +# ── minder_api steps ───────────────────────────────────────────────────── + + +def minder_manifest(**tool_extra: Any) -> Dict: + """A tool that reads Minder's own API, then fetches one upstream item.""" + op = tool( + [ + { + "name": "hits", + "minder_api": { + "route": "/v1/knowledge-bases/{params.q}/search", + "method": "POST", + "query": {"limit": 5}, + "body": {"query": "{params.q}", "fixed": True}, + }, + "select": "results[0]", + }, + { + "name": "doc", + "request": {"base": "api", "path": "/items/{steps.hits.id}"}, + }, + ], + minder_scopes=["kb.search"], + output="{first: steps.hits.title, doc: steps.doc.name}", + ) + op.update(tool_extra) + return manifest({"tools": {"passages": op}}) + + +async def test_minder_api_step_calls_ctx_minder_and_feeds_later_steps(): + from minder_plugin_sdk.context import CAP_MINDER_API + from minder_plugin_sdk.harness import FakePlatformContext + + seen: List[Dict[str, Any]] = [] + + def answer(query: Dict[str, Any], json: Any) -> Any: + seen.append({"query": query, "json": json}) + return {"results": [{"id": "d1", "title": "First"}], "total": 1} + + route = "/v1/knowledge-bases/a%2Fb/search" # the placeholder is path-encoded + ctx = FakePlatformContext( + grants={CAP_MINDER_API}, minder_results={("POST", route): answer} + ) + up = Upstream() + up.route("api.example.com", "/v1/items/d1", httpx.Response(200, json={"name": "D"})) + dns_calls: List[str] = [] + e = engine(minder_manifest(), up, dns=resolver(calls=dns_calls)) + m = e.manifest.tools["passages"] + assert m.minder_scopes == ("kb.search",) + assert m.steps[0].request is None and m.steps[0].minder is not None + + out = await e.run_operation( + "passages", + {"q": "a/b"}, + Invocation(config={}, secrets=Secrets(), minder=ctx.minder), + ) + assert out == {"first": "First", "doc": "D"} + assert [c.args for c in ctx.called(CAP_MINDER_API)] == [ + {"route": route, "method": "POST"} + ] + assert seen == [{"query": {"limit": "5"}, "json": {"query": "a/b", "fixed": True}}] + # Only the HTTP step went through egress: the Minder call is not egress. + assert dns_calls == ["api.example.com"] + assert [r.url.raw_path for r in up.requests] == [b"/v1/items/d1"] + + +async def test_minder_api_step_is_denied_without_the_capability(): + from minder_plugin_sdk.context import CAP_MINDER_API + from minder_plugin_sdk.errors import CapabilityDenied + from minder_plugin_sdk.harness import FakePlatformContext + + up = Upstream() + e = engine(minder_manifest(), up) + denied = FakePlatformContext(grants=set()) + with pytest.raises(CapabilityDenied): + await e.run_operation( + "passages", + {"q": "x"}, + Invocation(config={}, secrets=Secrets(), minder=denied.minder), + ) + assert denied.called(CAP_MINDER_API) + # No handle bound (not a tool call): denied before anything is sent. + with pytest.raises(CapabilityDenied): + await e.run_operation("passages", {"q": "x"}, inv()) + assert up.requests == [] + + +async def test_minder_api_rendered_route_is_rechecked(): + from minder_plugin_sdk.harness import FakePlatformContext + + ctx = FakePlatformContext() + e = engine(minder_manifest(), Upstream()) + # An empty value leaves an empty segment: refused before any call. + with pytest.raises(MappingError, match="segment"): + await e.run_operation( + "passages", + {"q": ""}, + Invocation(config={}, secrets=Secrets(), minder=ctx.minder), + ) + assert ctx.calls == [] + + +def _minder_step(**call: Any) -> Dict[str, Any]: + return {"name": "m", "minder_api": {"route": "/v1/me", **call}} + + +@pytest.mark.parametrize( + "spec, match", + [ + # a tool without minder_scopes + ({"tools": {"t": tool([_minder_step()])}}, "declares minder_scopes"), + # an action, even one that lists scopes + ( + {"tools": {}, "actions": {"a": tool([_minder_step()])}}, + "declares minder_scopes", + ), + ( + {"actions": {"a": tool([_minder_step()], minder_scopes=["kb.search"])}}, + "only an AI tool", + ), + ( + { + "timeseries": {"measurements": ["m1"]}, + "schedule": { + "steps": [_minder_step()], + "measurement": "m1", + "points": "`[]`", + }, + }, + "declares minder_scopes", + ), + ( + {"tools": {"t": tool([_minder_step()], minder_scopes=["kb.nope"])}}, + "not a Minder scope", + ), + ( + {"tools": {"t": tool([_minder_step()], minder_scopes=["kb.search"] * 2)}}, + "listed twice", + ), + ], +) +def test_minder_api_steps_need_a_tool_with_minder_scopes(spec, match): + with pytest.raises(ManifestError, match=match): + load_manifest(manifest(spec)) + + +@pytest.mark.parametrize( + "step, match", + [ + ({"name": "m", "minder_api": {"route": "/api/v1/me"}}, "starting with '/v1/'"), + ({"name": "m", "minder_api": {"route": "https://x/v1/me"}}, "'/v1/'"), + ({"name": "m", "minder_api": {"route": "/v1/../internal"}}, "'..' segments"), + ({"name": "m", "minder_api": {"route": "/v1/me?x=1"}}, "use 'query'"), + ({"name": "m", "minder_api": {"route": "/v1/{secret.X}"}}, "placeholder root"), + (_minder_step(method="PUT"), "invalid manifest"), + (_minder_step(body={"a": 1}), "GET takes no body"), + (_minder_step(headers={"a": "b"}), "invalid manifest"), + ({"name": "m"}, "exactly one of"), + ( + {**_minder_step(), "request": {"base": "api", "path": "/x"}}, + "exactly one of", + ), + ], +) +def test_minder_api_route_and_method_are_validated_at_load(step, match): + op = tool([step], minder_scopes=["kb.search"]) + with pytest.raises(ManifestError, match=match): + load_manifest(manifest({"tools": {"t": op}}))