diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 10b2b972e..9f7312995 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,2 +1,3 @@ # Retrofit annotation commit (opsx-annotate, 2026-05-24) 1e2173556948495a03fa0596628fefccc479c2cd +87ee9f510ab9200862ee029315e04660fc2b6468 diff --git a/lib/Mcp/ScholiqToolProvider.php b/lib/Mcp/ScholiqToolProvider.php index 03a6cbe5e..21f79bb64 100644 --- a/lib/Mcp/ScholiqToolProvider.php +++ b/lib/Mcp/ScholiqToolProvider.php @@ -155,6 +155,8 @@ public function __construct( * Returns the app ID that namespaces every tool id. * * @return string "scholiq" + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-1 */ public function getAppId(): string { @@ -169,6 +171,8 @@ public function getAppId(): string * Per-object authorisation runs in invokeTool(). * * @return array> + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-1 */ public function getTools(): array { @@ -186,6 +190,8 @@ public function getTools(): array * @param array $arguments Tool arguments from the LLM call. * * @return array + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-2 */ public function invokeTool(string $toolId, array $arguments): array { @@ -215,6 +221,8 @@ public function invokeTool(string $toolId, array $arguments): array * @param array $args Tool arguments. * * @return array + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-3 */ private function handleListCourses(array $args): array { @@ -279,6 +287,8 @@ private function handleListCourses(array $args): array * @param array $args Tool arguments. * * @return array{error?: array, limit?: int, status?: string|null} + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-3 */ private function validateListCoursesArgs(array $args): array { @@ -333,6 +343,8 @@ private function validateListCoursesArgs(array $args): array * @param array $args Tool arguments. * * @return array + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-4 */ private function handleGetCourseDetails(array $args): array { @@ -410,6 +422,8 @@ private function handleGetCourseDetails(array $args): array * @param string $courseUuid The parent course UUID. * * @return array> + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-4 */ private function loadCourseModules(string $courseUuid): array { @@ -453,6 +467,8 @@ static function (array $a, array $b): int { * @param string $courseUuid The course UUID. * * @return array + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-3 */ private function courseSource(array $course, string $courseUuid): array { @@ -485,6 +501,8 @@ private function courseSource(array $course, string $courseUuid): array * and is NOT wrapped in catch(\Throwable). * * @return bool True when the caller is an authenticated user. + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-3 */ private function requireCourseReadAccess(): bool { @@ -514,6 +532,8 @@ private function requireCourseReadAccess(): bool * @param string $courseRef The course id/uuid/slug/code. * * @return array|null The normalised course array, or null. + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-4 */ private function findCourse(string $courseRef): ?array { @@ -555,6 +575,8 @@ private function findCourse(string $courseRef): ?array * @param array $course The normalised course array. * * @return array + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-3 */ private function courseSummary(array $course): array { @@ -581,6 +603,8 @@ private function courseSummary(array $course): array * @param array $lesson The normalised lesson array. * * @return array + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-4 */ private function moduleSummary(array $lesson): array { @@ -610,6 +634,8 @@ private function moduleSummary(array $lesson): array * @param string $uuid The object UUID. * * @return string The deep link path, e.g. /apps/scholiq/courses/. + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-4 */ private function buildDeepLink(string $type, string $uuid): string { @@ -629,6 +655,8 @@ private function buildDeepLink(string $type, string $uuid): string * @param mixed $item Raw item from ObjectService. * * @return array + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-5 */ private function toArray(mixed $item): array { @@ -661,6 +689,8 @@ private function toArray(mixed $item): array * @param array $item The normalised object array. * * @return string The UUID, or empty string when not found. + * + * @spec openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-5 */ private function extractUuid(array $item): string { diff --git a/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/design.md b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/design.md new file mode 100644 index 000000000..33b38345b --- /dev/null +++ b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/design.md @@ -0,0 +1,32 @@ +# Design — Retrofit `ai-companion-tools` + +**Retrofit change. Tasks describe retroactive annotation, not new implementation work.** The code already exists at `lib/Mcp/ScholiqToolProvider.php` (shipped 2026-05-12 alongside hydra ADR-034 + ADR-035 and openregister PR #1466). This change documents the observable contract so future changes have something to extend. + +## Goal + +Capture the observed behaviour of the 15 methods on `ScholiqToolProvider` as 5 numbered REQs grouped into a new `ai-companion-tools` capability: + +| REQ | Methods covered | +|---|---| +| REQ-001 — Provider declares an app id and a hard-coded tool catalogue | `getAppId`, `getTools` | +| REQ-002 — Dispatcher routes by tool id and rejects unknown ids without throwing | `invokeTool` | +| REQ-003 — listCourses validates args, gates on authentication, caps results, and returns privacy-safe summaries | `handleListCourses`, `validateListCoursesArgs`, `requireCourseReadAccess`, `courseSummary`, `courseSource` | +| REQ-004 — getCourseDetails resolves a course by id/uuid/slug/code, returns ordered modules, and never leaks learner PII | `handleGetCourseDetails`, `findCourse`, `loadCourseModules`, `moduleSummary`, `buildDeepLink` | +| REQ-005 — Object normalisation accepts arrays, OpenRegister entities, and JsonSerializable shapes | `toArray`, `extractUuid` | + +## Why a new capability (not `--extend`) + +The coverage report parked this cluster under `bucket_2a/assessment` because the matcher had to put it somewhere — but `assessment` is the Tests/Exams capability (item banks, QTI 3.0, proctoring). MCP tool provision is genuinely new territory: a per-app contract with hydra's AI chat companion via openregister's `IMcpToolProvider` abstraction. A new capability lets future work (adding more tools, tightening provider-side auth, switching to a dynamic catalogue) extend a clearly-scoped baseline rather than bloating an unrelated capability. + +## Non-goals + +- No code behaviour changes — annotations only. +- No "fixing" of observed-but-suspicious behaviour. The `requireCourseReadAccess()` tautological tail (`return $userId !== ''` after the empty-string check) is documented in REQ-003 Notes; tightening to a Scholiq-specific group check is a future spec. +- No Dutch translation of tool descriptions — consistent with the rest of MCP tooling at this revision. +- No tools that touch learner data — Enrolment / Attestation / Credential / per-learner tooling is deferred to a follow-up that wires proper per-student authorisation. + +## Notes for archiver + +- New capability spec under `openspec/specs/ai-companion-tools/spec.md` (no existing file — `--cluster` semantics). +- `retrofit: true` in frontmatter so Specter dashboards can filter the retrofit cohort. +- Annotations on `lib/Mcp/ScholiqToolProvider.php` reference `openspec/changes/retrofit-2026-05-24-ai-companion-tools/tasks.md#task-N`; after archive the tags continue resolving via the archived change directory (ADR-003 convention). diff --git a/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/proposal.md b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/proposal.md new file mode 100644 index 000000000..4a5757082 --- /dev/null +++ b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/proposal.md @@ -0,0 +1,30 @@ +# Retrofit — ai-companion-tools + +Describes the observed behaviour of 15 methods on `lib/Mcp/ScholiqToolProvider.php` as 5 new REQs under a brand-new `ai-companion-tools` capability. Code already exists (shipped 2026-05-12 alongside hydra ADR-034 + ADR-035 and openregister PR #1466) — this change retroactively specifies it so future changes have something to extend. + +## Affected code units + +- `lib/Mcp/ScholiqToolProvider.php::getAppId()` +- `lib/Mcp/ScholiqToolProvider.php::getTools()` +- `lib/Mcp/ScholiqToolProvider.php::invokeTool()` +- `lib/Mcp/ScholiqToolProvider.php::handleListCourses()` +- `lib/Mcp/ScholiqToolProvider.php::validateListCoursesArgs()` +- `lib/Mcp/ScholiqToolProvider.php::handleGetCourseDetails()` +- `lib/Mcp/ScholiqToolProvider.php::loadCourseModules()` +- `lib/Mcp/ScholiqToolProvider.php::courseSource()` +- `lib/Mcp/ScholiqToolProvider.php::requireCourseReadAccess()` +- `lib/Mcp/ScholiqToolProvider.php::findCourse()` +- `lib/Mcp/ScholiqToolProvider.php::courseSummary()` +- `lib/Mcp/ScholiqToolProvider.php::moduleSummary()` +- `lib/Mcp/ScholiqToolProvider.php::buildDeepLink()` +- `lib/Mcp/ScholiqToolProvider.php::toArray()` +- `lib/Mcp/ScholiqToolProvider.php::extractUuid()` + +## Approach + +- For each method: describe observed inputs, outputs, pre/postconditions, failure modes from the code as it ships +- Draft REQs that fold the 15 methods into 5 distinct observable behaviours (provider identity & catalogue, dispatch, list-courses tool, get-course-details tool, object normalisation) +- Notes sections surface observed-but-suspicious behaviour (e.g. `requireCourseReadAccess()` ends with a tautological `$userId !== ''` check after already returning false on empty — currently lets every authenticated user through; that is the observed behaviour and is left as-is here) +- Mint as a new capability (not `--extend`) because no MCP / AI-companion capability exists in scholiq's specs/ yet — the coverage report categorised it under bucket_2a/`assessment` only because the matcher had nowhere else to put it + +Source: `openspec/coverage-report.md` generated 2026-05-24. See [retrofit playbook](../../../.github/docs/claude/retrofit.md). diff --git a/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/specs/ai-companion-tools/spec.md b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/specs/ai-companion-tools/spec.md new file mode 100644 index 000000000..b4691287c --- /dev/null +++ b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/specs/ai-companion-tools/spec.md @@ -0,0 +1,122 @@ +--- +retrofit: true +--- + +# ai-companion-tools + +## Why + +The hydra AI Chat Companion (ADR-034 + ADR-035) wires a per-app `IMcpToolProvider` (openregister PR #1466) so an LLM can call back into a Conduction app for live data. Scholiq holds course catalogues alongside privacy-sensitive learner records, so its MVP provider deliberately exposes only the two least-sensitive read-only tools (`scholiq.listCourses`, `scholiq.getCourseDetails`). This capability spec retroactively documents the observable contract of that provider so future changes (adding tools, tightening auth, adopting an MCP-wide registry) extend an explicit baseline rather than relying on code-archaeology. + +## What + +- A per-app `IMcpToolProvider` implementation registered for the `scholiq` app id +- A hard-coded read-only tool catalogue exposing exactly two tools: `scholiq.listCourses` and `scholiq.getCourseDetails` +- Per-call argument validation, then per-object authorisation, then business logic — in that order +- Structured `{success | isError, error, message}` responses for every tool call (no thrown exceptions across the MCP boundary) +- Privacy guarantee: course + module metadata only — never `Enrolment`, `Attestation`, `Credential` or learner objects + +## ADDED Requirements + +### REQ-001: Provider declares an app id and a hard-coded tool catalogue +The provider MUST declare the `"scholiq"` app id and MUST return a fixed tool catalogue containing exactly the two read-only tools `scholiq.listCourses` and `scholiq.getCourseDetails`, regardless of caller identity or permissions. The catalogue MUST advertise input schemas with a `limit` (1–50, default 20) and optional `status` enum (`draft|published|archived`) for `listCourses`, and a required `id` string for `getCourseDetails`. The full catalogue is the discovery surface; per-object authorisation runs later, on invocation. + +#### Scenario: Catalogue is the same for every caller +- GIVEN any caller (signed-in user, admin, or unauthenticated discovery) +- WHEN `getTools()` is invoked +- THEN the response lists exactly `scholiq.listCourses` and `scholiq.getCourseDetails` with their input schemas +- AND the catalogue does not change based on the caller's permissions + +Covers: `getAppId()`, `getTools()`. + +### REQ-002: Dispatcher routes by tool id and rejects unknown ids without throwing +`invokeTool()` MUST route exclusively on the tool id string, dispatching `scholiq.listCourses` to the list-courses handler and `scholiq.getCourseDetails` to the details handler. An unknown tool id MUST return a structured `{isError: true, error: "unknown_tool", message: "..."}` response that names the unknown id and lists the available tool ids — no exception MUST escape the dispatcher. + +#### Scenario: Unknown tool id returns a structured error +- GIVEN any caller invokes `invokeTool('scholiq.nope', [])` +- WHEN the dispatcher matches no handler +- THEN the response is `{isError: true, error: 'unknown_tool', message: "Unknown tool id 'scholiq.nope'. Available tools: scholiq.listCourses, scholiq.getCourseDetails."}` +- AND no exception is thrown across the MCP boundary + +Covers: `invokeTool()`. + +### REQ-003: listCourses validates args, gates on authentication, caps results, and returns privacy-safe summaries +`handleListCourses()` MUST validate arguments first (reject `limit` outside 1–50 and `status` outside the lifecycle enum with `{isError: true, error: "invalid_arguments", ...}`), then gate on authentication via `requireCourseReadAccess()` (returning `{isError: true, error: "forbidden", ...}` for unauthenticated callers), then read at most `LIST_CAP` (20) `Course` objects via `ObjectService::findAll` — applying the optional `lifecycle` filter when `status` is set. Each returned course MUST be reshaped to an allow-listed catalogue summary (`uuid, code, name, name_nl, description, level, language, tags, mandatoryTraining, regulationSlug, renewalCourseSlug, lifecycle`) and accompanied by a citation `source` of `type: "scholiq.course"` pointing at `/apps/scholiq/courses/`. A read failure MUST be logged at `error` level and surfaced as `{isError: true, error: "internal_error", ...}` — no exception escapes the tool. + +#### Scenario: Authenticated list with status filter returns capped, privacy-safe summaries +- GIVEN an authenticated user invokes `handleListCourses({limit: 100, status: 'published'})` +- WHEN the handler runs +- THEN `validateListCoursesArgs` returns `limit: 100, status: 'published'` +- AND the `ObjectService::findAll` call passes `limit: 20` (the hard cap, not 100) and `filters: {lifecycle: 'published'}` +- AND each result in `courses[]` contains only the allow-listed catalogue fields +- AND each entry in `sources[]` has `type: "scholiq.course"` and `url: "/apps/scholiq/courses/"` + +#### Scenario: Unauthenticated caller is rejected before any read +- GIVEN an unauthenticated caller invokes `handleListCourses({})` +- WHEN argument validation passes and `requireCourseReadAccess()` returns false +- THEN the handler returns `{isError: true, error: "forbidden", message: "You must be signed in to list courses."}` +- AND no `ObjectService::findAll` call is made + +#### Notes +- `requireCourseReadAccess()` admits any user with a non-empty `getUID()` — the final `return $userId !== ''` is tautological after the earlier empty-string check and effectively means "authenticated = allowed". OpenRegister's RBAC inside `ObjectService` is the second, per-object gate. This is the observed behaviour; tightening to a Scholiq-specific group check is a future spec. + +Covers: `handleListCourses()`, `validateListCoursesArgs()`, `requireCourseReadAccess()`, `courseSummary()`, `courseSource()`. + +### REQ-004: getCourseDetails resolves a course by id/uuid/slug/code, returns ordered modules, and never leaks learner PII +`handleGetCourseDetails()` MUST require a non-empty `id` argument, then gate on authentication via `requireCourseReadAccess()`, then resolve the course via `findCourse()` — trying direct id/uuid lookup first, then a filtered search by `slug`, then by `code`, returning the first match or null. A null resolution MUST surface as `{isError: true, error: "not_found", ...}`. On success the response MUST include the catalogue summary (REQ-003), an ordered list of `Lesson` summaries (`uuid, name, order, contentType, durationMinutes, learningObjectives, mandatoryTraining, regulationSlug, lifecycle`) sorted ascending by the 1-based `order` field via `loadCourseModules()`, and a `sources[]` array with one `scholiq.course` source plus one `scholiq.module` source per module — every URL built by `buildDeepLink()` from the table `course → /apps/scholiq/courses, module → /apps/scholiq/modules` (with a `{type}s` fallback for unknown types). The response MUST NOT contain `Enrolment`, `Attestation`, `Credential` or any learner-scoped object. Module-list lookup failures MUST be logged and degrade to an empty `modules[]` (course details still render); course-lookup failures MUST surface as `{isError: true, error: "internal_error", ...}`. + +#### Scenario: Resolution falls back from uuid to slug to code +- GIVEN a course exists with `code: 'NL-1'` but no matching uuid or slug +- WHEN an authenticated user invokes `handleGetCourseDetails({id: 'NL-1'})` +- THEN `findCourse('NL-1')` first calls `ObjectService::find(id: 'NL-1', ...)` (returns null) +- AND falls back to `findAll(filters: {slug: 'NL-1'}, limit: 1)` (empty) +- AND then to `findAll(filters: {code: 'NL-1'}, limit: 1)` (returns the course) +- AND the response includes the course summary, ordered modules, and corresponding deep-link sources + +#### Scenario: Module-load failure degrades to empty modules without failing the response +- GIVEN a course resolves successfully +- WHEN `loadCourseModules` throws during `ObjectService::findAll` +- THEN the exception is logged at error level with the courseUuid +- AND the response returns `{success: true, course: {...}, modules: [], sources: [{type: "scholiq.course", ...}]}` + +Covers: `handleGetCourseDetails()`, `findCourse()`, `loadCourseModules()`, `moduleSummary()`, `buildDeepLink()`. + +### REQ-005: Object normalisation accepts arrays, OpenRegister entities, and JsonSerializable shapes +The provider MUST normalise inputs from `ObjectService` into plain `array` via `toArray()` — returning the input unchanged when already an array, otherwise calling `getObject()` then `jsonSerialize()` on objects (in that order, returning the first array-shaped result), with a final `(array)` cast fallback. UUID extraction via `extractUuid()` MUST consult, in order, `uuid`, `id`, `@self.uuid`, `@self.id`, returning the first present value as a string, or the empty string when none are present. These helpers MUST be the only normalisation path used inside the provider so adding a new tool inherits the same shape contract. + +#### Scenario: Entity exposing getObject() is normalised +- GIVEN `ObjectService::findAll` returns objects exposing `getObject(): array` +- WHEN the handler iterates results +- THEN `toArray()` returns the `getObject()` array unchanged +- AND `extractUuid()` finds the uuid at `['uuid']`, `['id']`, `['@self']['uuid']` or `['@self']['id']` + +#### Notes +- The `(array)` cast fallback means objects without `getObject()`/`jsonSerialize()` are exposed with their full property surface, which could include private fields rendered with mangled keys. No such shape is observed in practice from `ObjectService` — kept as a defensive last resort. + +Covers: `toArray()`, `extractUuid()`. + +## Non-Functional Requirements + +- **Privacy:** Tools MUST NOT return `Enrolment`, `Attestation`, `Credential` or any learner-scoped object. The two MVP tools are the catalogue and one course's module structure — both learner-free. +- **Failure mode:** No exception MUST cross the MCP boundary. All failure paths return a structured `{isError: true, error, message}` response and log at `error` level with context. +- **Limits:** `listCourses` MUST cap its result set at 20 regardless of the requested `limit` (which itself is bounded to 1–50 at argument validation). +- **i18n:** Tool descriptions are English-only at this revision (consistent with the rest of MCP tooling, hydra ADR-034). Dutch localisation is a future change. + +## Acceptance Criteria + +- [x] `getAppId()` returns the literal `"scholiq"` +- [x] `getTools()` returns the two-tool catalogue regardless of caller +- [x] `invokeTool('scholiq.nope', [])` returns a structured `unknown_tool` error (no exception) +- [x] `handleListCourses({limit: 100})` caps the underlying `findAll` to `limit: 20` +- [x] `handleListCourses` rejects unauthenticated callers before any read +- [x] `handleGetCourseDetails` resolves by uuid → slug → code in that order +- [x] `loadCourseModules` failures degrade to empty modules + logged error +- [x] No response shape includes `Enrolment`, `Attestation`, `Credential` or learner fields +- [x] `toArray()` returns input unchanged for arrays, uses `getObject()` then `jsonSerialize()` for objects +- [x] `extractUuid()` consults `uuid → id → @self.uuid → @self.id` in that order + +## Notes + +- This spec captures observed behaviour shipped 2026-05-12 alongside hydra ADR-034 + ADR-035 + openregister PR #1466. It is a retrofit — it does not propose changes. +- Future tightening (Scholiq-specific group check in `requireCourseReadAccess`, Dutch tool descriptions, per-learner-authorised tools for enrolment/attestation/credential) belongs in follow-up `MODIFIED Requirements` deltas, not this baseline. +- The provider exposes a `LIST_CAP` of 20 distinct from the catalogue's advertised `limit: 50` upper bound; this is the observed contract — the maximum requested via input schema may exceed the actual cap, and the hard cap wins. diff --git a/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/tasks.md b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/tasks.md new file mode 100644 index 000000000..7da05707d --- /dev/null +++ b/openspec/changes/archive/retrofit-2026-05-24-ai-companion-tools/tasks.md @@ -0,0 +1,9 @@ +# Tasks + +Retroactive annotation only — code already exists. + +- [x] task-1: ai-companion-tools#REQ-001 — Provider declares an app id and a hard-coded tool catalogue (retroactive annotation) +- [x] task-2: ai-companion-tools#REQ-002 — Dispatcher routes by tool id and rejects unknown ids without throwing (retroactive annotation) +- [x] task-3: ai-companion-tools#REQ-003 — listCourses validates args, gates on authentication, caps results, and returns privacy-safe summaries (retroactive annotation) +- [x] task-4: ai-companion-tools#REQ-004 — getCourseDetails resolves a course by id/uuid/slug/code, returns ordered modules, and never leaks learner PII (retroactive annotation) +- [x] task-5: ai-companion-tools#REQ-005 — Object normalisation accepts arrays, OpenRegister entities, and JsonSerializable shapes (retroactive annotation) diff --git a/openspec/specs/ai-companion-tools/spec.md b/openspec/specs/ai-companion-tools/spec.md new file mode 100644 index 000000000..8407b0c5c --- /dev/null +++ b/openspec/specs/ai-companion-tools/spec.md @@ -0,0 +1,141 @@ +--- +slug: ai-companion-tools +title: AI Companion Tools — MCP provider for scholiq +status: implemented +retrofit: true +feature_tier: should +depends_on_adrs: [ADR-005, ADR-022] +created: 2026-05-24 +updated: 2026-05-24 +profiles: [ai-chat-companion] +--- + +# AI Companion Tools + +## Why + +The hydra AI Chat Companion (ADR-034 + ADR-035) wires a per-app `IMcpToolProvider` (openregister PR #1466) so an LLM can call back into a Conduction app for live data. Scholiq holds course catalogues alongside privacy-sensitive learner records, so its MVP provider deliberately exposes only the two least-sensitive read-only tools (`scholiq.listCourses`, `scholiq.getCourseDetails`). This capability spec retroactively documents the observable contract of that provider so future changes (adding tools, tightening auth, adopting an MCP-wide registry) extend an explicit baseline rather than relying on code-archaeology. + +## What + +- A per-app `IMcpToolProvider` implementation registered for the `scholiq` app id +- A hard-coded read-only tool catalogue exposing exactly two tools: `scholiq.listCourses` and `scholiq.getCourseDetails` +- Per-call argument validation, then per-object authorisation, then business logic — in that order +- Structured `{success | isError, error, message}` responses for every tool call (no thrown exceptions across the MCP boundary) +- Privacy guarantee: course + module metadata only — never `Enrolment`, `Attestation`, `Credential` or learner objects + +## Requirements + +### REQ-001: Provider declares an app id and a hard-coded tool catalogue +The provider MUST declare the `"scholiq"` app id and MUST return a fixed tool catalogue containing exactly the two read-only tools `scholiq.listCourses` and `scholiq.getCourseDetails`, regardless of caller identity or permissions. The catalogue MUST advertise input schemas with a `limit` (1–50, default 20) and optional `status` enum (`draft|published|archived`) for `listCourses`, and a required `id` string for `getCourseDetails`. The full catalogue is the discovery surface; per-object authorisation runs later, on invocation. + +#### Scenario: Catalogue is the same for every caller +- GIVEN any caller (signed-in user, admin, or unauthenticated discovery) +- WHEN `getTools()` is invoked +- THEN the response lists exactly `scholiq.listCourses` and `scholiq.getCourseDetails` with their input schemas +- AND the catalogue does not change based on the caller's permissions + +Covers: `getAppId()`, `getTools()`. + +### REQ-002: Dispatcher routes by tool id and rejects unknown ids without throwing +`invokeTool()` MUST route exclusively on the tool id string, dispatching `scholiq.listCourses` to the list-courses handler and `scholiq.getCourseDetails` to the details handler. An unknown tool id MUST return a structured `{isError: true, error: "unknown_tool", message: "..."}` response that names the unknown id and lists the available tool ids — no exception MUST escape the dispatcher. + +#### Scenario: Unknown tool id returns a structured error +- GIVEN any caller invokes `invokeTool('scholiq.nope', [])` +- WHEN the dispatcher matches no handler +- THEN the response is `{isError: true, error: 'unknown_tool', message: "Unknown tool id 'scholiq.nope'. Available tools: scholiq.listCourses, scholiq.getCourseDetails."}` +- AND no exception is thrown across the MCP boundary + +Covers: `invokeTool()`. + +### REQ-003: listCourses validates args, gates on authentication, caps results, and returns privacy-safe summaries +`handleListCourses()` MUST validate arguments first (reject `limit` outside 1–50 and `status` outside the lifecycle enum with `{isError: true, error: "invalid_arguments", ...}`), then gate on authentication via `requireCourseReadAccess()` (returning `{isError: true, error: "forbidden", ...}` for unauthenticated callers), then read at most `LIST_CAP` (20) `Course` objects via `ObjectService::findAll` — applying the optional `lifecycle` filter when `status` is set. Each returned course MUST be reshaped to an allow-listed catalogue summary (`uuid, code, name, name_nl, description, level, language, tags, mandatoryTraining, regulationSlug, renewalCourseSlug, lifecycle`) and accompanied by a citation `source` of `type: "scholiq.course"` pointing at `/apps/scholiq/courses/`. A read failure MUST be logged at `error` level and surfaced as `{isError: true, error: "internal_error", ...}` — no exception escapes the tool. + +#### Scenario: Authenticated list with status filter returns capped, privacy-safe summaries +- GIVEN an authenticated user invokes `handleListCourses({limit: 100, status: 'published'})` +- WHEN the handler runs +- THEN `validateListCoursesArgs` returns `limit: 100, status: 'published'` +- AND the `ObjectService::findAll` call passes `limit: 20` (the hard cap, not 100) and `filters: {lifecycle: 'published'}` +- AND each result in `courses[]` contains only the allow-listed catalogue fields +- AND each entry in `sources[]` has `type: "scholiq.course"` and `url: "/apps/scholiq/courses/"` + +#### Scenario: Unauthenticated caller is rejected before any read +- GIVEN an unauthenticated caller invokes `handleListCourses({})` +- WHEN argument validation passes and `requireCourseReadAccess()` returns false +- THEN the handler returns `{isError: true, error: "forbidden", message: "You must be signed in to list courses."}` +- AND no `ObjectService::findAll` call is made + +#### Notes +- `requireCourseReadAccess()` admits any user with a non-empty `getUID()` — the final `return $userId !== ''` is tautological after the earlier empty-string check and effectively means "authenticated = allowed". OpenRegister's RBAC inside `ObjectService` is the second, per-object gate. This is the observed behaviour; tightening to a Scholiq-specific group check is a future spec. + +Covers: `handleListCourses()`, `validateListCoursesArgs()`, `requireCourseReadAccess()`, `courseSummary()`, `courseSource()`. + +### REQ-004: getCourseDetails resolves a course by id/uuid/slug/code, returns ordered modules, and never leaks learner PII +`handleGetCourseDetails()` MUST require a non-empty `id` argument, then gate on authentication via `requireCourseReadAccess()`, then resolve the course via `findCourse()` — trying direct id/uuid lookup first, then a filtered search by `slug`, then by `code`, returning the first match or null. A null resolution MUST surface as `{isError: true, error: "not_found", ...}`. On success the response MUST include the catalogue summary (REQ-003), an ordered list of `Lesson` summaries (`uuid, name, order, contentType, durationMinutes, learningObjectives, mandatoryTraining, regulationSlug, lifecycle`) sorted ascending by the 1-based `order` field via `loadCourseModules()`, and a `sources[]` array with one `scholiq.course` source plus one `scholiq.module` source per module — every URL built by `buildDeepLink()` from the table `course → /apps/scholiq/courses, module → /apps/scholiq/modules` (with a `{type}s` fallback for unknown types). The response MUST NOT contain `Enrolment`, `Attestation`, `Credential` or any learner-scoped object. Module-list lookup failures MUST be logged and degrade to an empty `modules[]` (course details still render); course-lookup failures MUST surface as `{isError: true, error: "internal_error", ...}`. + +#### Scenario: Resolution falls back from uuid to slug to code +- GIVEN a course exists with `code: 'NL-1'` but no matching uuid or slug +- WHEN an authenticated user invokes `handleGetCourseDetails({id: 'NL-1'})` +- THEN `findCourse('NL-1')` first calls `ObjectService::find(id: 'NL-1', ...)` (returns null) +- AND falls back to `findAll(filters: {slug: 'NL-1'}, limit: 1)` (empty) +- AND then to `findAll(filters: {code: 'NL-1'}, limit: 1)` (returns the course) +- AND the response includes the course summary, ordered modules, and corresponding deep-link sources + +#### Scenario: Module-load failure degrades to empty modules without failing the response +- GIVEN a course resolves successfully +- WHEN `loadCourseModules` throws during `ObjectService::findAll` +- THEN the exception is logged at error level with the courseUuid +- AND the response returns `{success: true, course: {...}, modules: [], sources: [{type: "scholiq.course", ...}]}` + +Covers: `handleGetCourseDetails()`, `findCourse()`, `loadCourseModules()`, `moduleSummary()`, `buildDeepLink()`. + +### REQ-005: Object normalisation accepts arrays, OpenRegister entities, and JsonSerializable shapes +The provider MUST normalise inputs from `ObjectService` into plain `array` via `toArray()` — returning the input unchanged when already an array, otherwise calling `getObject()` then `jsonSerialize()` on objects (in that order, returning the first array-shaped result), with a final `(array)` cast fallback. UUID extraction via `extractUuid()` MUST consult, in order, `uuid`, `id`, `@self.uuid`, `@self.id`, returning the first present value as a string, or the empty string when none are present. These helpers MUST be the only normalisation path used inside the provider so adding a new tool inherits the same shape contract. + +#### Scenario: Entity exposing getObject() is normalised +- GIVEN `ObjectService::findAll` returns objects exposing `getObject(): array` +- WHEN the handler iterates results +- THEN `toArray()` returns the `getObject()` array unchanged +- AND `extractUuid()` finds the uuid at `['uuid']`, `['id']`, `['@self']['uuid']` or `['@self']['id']` + +#### Notes +- The `(array)` cast fallback means objects without `getObject()`/`jsonSerialize()` are exposed with their full property surface, which could include private fields rendered with mangled keys. No such shape is observed in practice from `ObjectService` — kept as a defensive last resort. + +Covers: `toArray()`, `extractUuid()`. + +## Non-Functional Requirements + +- **Privacy:** Tools MUST NOT return `Enrolment`, `Attestation`, `Credential` or any learner-scoped object. The two MVP tools are the catalogue and one course's module structure — both learner-free. +- **Failure mode:** No exception MUST cross the MCP boundary. All failure paths return a structured `{isError: true, error, message}` response and log at `error` level with context. +- **Limits:** `listCourses` MUST cap its result set at 20 regardless of the requested `limit` (which itself is bounded to 1–50 at argument validation). +- **i18n:** Tool descriptions are English-only at this revision (consistent with the rest of MCP tooling, hydra ADR-034). Dutch localisation is a future change. + +## Acceptance Criteria + +- [x] `getAppId()` returns the literal `"scholiq"` +- [x] `getTools()` returns the two-tool catalogue regardless of caller +- [x] `invokeTool('scholiq.nope', [])` returns a structured `unknown_tool` error (no exception) +- [x] `handleListCourses({limit: 100})` caps the underlying `findAll` to `limit: 20` +- [x] `handleListCourses` rejects unauthenticated callers before any read +- [x] `handleGetCourseDetails` resolves by uuid → slug → code in that order +- [x] `loadCourseModules` failures degrade to empty modules + logged error +- [x] No response shape includes `Enrolment`, `Attestation`, `Credential` or learner fields +- [x] `toArray()` returns input unchanged for arrays, uses `getObject()` then `jsonSerialize()` for objects +- [x] `extractUuid()` consults `uuid → id → @self.uuid → @self.id` in that order + +## Data Model + +No new OpenRegister schemas — this capability reads existing `Course` and `Lesson` objects via `ObjectService`. The provider is a thin read-only adapter; persistence and lifecycle stay with `course-management`. + +## Out of Scope + +- Tools that touch learner data (Enrolment, Attestation, Credential, per-learner records) — deferred to a follow-up that wires proper per-student authorisation +- Dutch localisation of tool descriptions +- Tightening `requireCourseReadAccess()` to a Scholiq-specific group check +- A dynamic per-caller catalogue (the catalogue is hard-coded by design at this revision) + +## Notes + +- This spec captures observed behaviour shipped 2026-05-12 alongside hydra ADR-034 + ADR-035 + openregister PR #1466. It is a retrofit — it does not propose changes. +- Future tightening (Scholiq-specific group check in `requireCourseReadAccess`, Dutch tool descriptions, per-learner-authorised tools for enrolment/attestation/credential) belongs in follow-up `MODIFIED Requirements` deltas, not this baseline. +- The provider exposes a `LIST_CAP` of 20 distinct from the catalogue's advertised `limit: 50` upper bound; this is the observed contract — the maximum requested via input schema may exceed the actual cap, and the hard cap wins.