Skip to content

feat(skills): admin keys manage library sources over MCP (abilityai/trinity-enterprise#692) - #3514

Merged
vybe merged 6 commits into
devfrom
feature/ent692-skill-sources-mcp
Oct 11, 2026
Merged

vybe merged 6 commits into
devfrom
feature/ent692-skill-sources-mcp

Conversation

@trinity-ability

@trinity-ability trinity-ability commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Skill-library sources can now be managed over MCP by the principals that already hold that authority over REST: an admin's own user-scoped key (and the system agent). Agent-scoped and connector keys are still refused.

New MCP tools (src/mcp-server/src/tools/skill_sources.ts), each a thin proxy over an existing admin route:

Tool Route
list_skill_sources GET /api/skills/sources
register_skill_source POST /api/skills/sources/apply (new, idempotent on url)
update_skill_source PUT /api/skills/sources/{id}
delete_skill_source DELETE /api/skills/sources/{id}
sync_skill_source POST /api/skills/sources/{id}/sync
sync_skill_library POST /api/skills/library/sync

Backend additions:

  • POST /api/skills/sources/apply: register-or-update keyed on the repository URL. Returns 201 created, or 200 updated / unchanged (no write). Only the named fields are patched, and a re-apply never creates a duplicate row. Two rows for one repo on different refs return 409 {code: ambiguous_source, source_ids}; it never guesses. It applies the same URL checks as create (reject_embedded_credentials + validate_skills_library_url, same 400 text) and the same gates (require_admin + reject_agent_principal). Matching uses _same_skills_repo, so the bundled default's scheme-less spelling matches.
  • POST /api/skills/sources takes an optional priority. Its 409-on-duplicate contract is unchanged, because the Settings panel relies on it.
  • GET /api/skills/library/status now carries last_fleet_reinject with counts only: timestamps, trigger, commit and the four agent counts. The per-agent failures map stays on the admin routes. Per-source url and last_error are still stripped from this public projection (ent#334).

Design: the fence is the principal, not the transport

require_admin already admits ADMIN_GATE_SCOPES = {None, user, system} and refuses agent and connector principals itself (#1890, #2323). Exposing the same operations over MCP to that same set of principals grants no new authority. It only removes a transport asymmetry that also kept out the admin's own key.

  • MCP visibility is an allowlist. Each tool sets its own canAccess to SOURCE_ADMIN_SCOPES = {user, system}. Agent, connector, anonymous, ops and unknown scopes are never shown the tools. Calling one by name over the real transport fails, and the tool re-checks scope before any backend call, using accessDenied so the refusal is audited.
  • The backend still decides the role. A user key whose owner is not an admin can see the tools, but the route refuses it with its own Admin access required.
  • Seam for a controller scope (ent#693), not implemented here. Such a scope would join SOURCE_ADMIN_SCOPES and be opted in per route via require_admin_allowing(...) (the ops-key pattern), never by widening ADMIN_GATE_SCOPES.
  • Honest results. Response bodies come back unchanged. A 4xx comes back as {success:false, status, error: <route detail>}, so the embedded-credential refusal keeps its text; a 5xx propagates. The sync tools return {outcome: ran|refused_busy|failed, result, fleet_reinject}. When a re-inject started, they name get_skills_library_status → last_fleet_reinject as the place to read its outcome.
  • Requirements updated first: requirements/skills.md §21.5 no longer says "REST-only". New §21.5.1 says source management is fenced to non-agent principals.

Tests

  • tests/unit/test_ent692_skill_sources_mcp.py: 32 tests, red before the change and green after. They cover:
    • apply create, update-in-place, unchanged, scheme-less match, ambiguous, embedded credentials (same body as create), off-allowlist host;
    • priority on create;
    • the agent key refused on all 7 source routes through the real require_admin, with the per-route reject_agent_principal neutralised. This proves the refusal comes from the gate itself, not a per-endpoint add-on (AC 2);
    • connector keys refused; the admin user key passes; a non-admin user key is refused;
    • the counts-only re-inject summary for non-admin and agent readers;
    • the # mcp: header.
  • src/mcp-server/src/tools/skill_sources.test.ts: 32 tests. They cover:
    • per-tool canAccess allowlist, plus a pin on the scope set;
    • in-tool refusal before any backend call;
    • exact method, path and body per tool, with the response body returned unchanged;
    • refusal detail passthrough, ran/busy/failed mapping, the re-inject pointer;
    • a real createServer and MCP client over streamable HTTP: user and system keys list all six tools; agent and connector keys list none, cannot call one by name, and never reach the backend route.
  • test_ent237_skill_sources.py: the new route is added to the reviewed MUTATING list (that guard caught it, as intended).
  • Runs:
    • Backend: 25 related unit files (skills, 293 admin gate, 1310 auth, 186 enumeration, models-centralized, ent334, …): 819 passed after the guard update.
    • MCP server: npm test, 868/868 passed; tsc --noEmit clean.

Product decisions taken (please confirm)

  1. OSS-core assumed. The skills library and its source management are OSS-core (§21.1 AC#7). These tools add no entitlement gate. Please confirm.
  2. Idempotency lives in a new /apply route, not by changing POST /api/skills/sources. The create route keeps its 409 for the Settings UI.
  3. Ambiguous repo → 409. When one repo is registered on several refs, apply refuses rather than picking one, and the caller uses update_skill_source by id.
  4. name defaults to owner/repo when an apply creates a row without one, and is never overwritten unless it is named.
  5. The system scope can see the tools, because require_admin admits it today.

Fixes abilityai/trinity-enterprise#692

🤖 Generated with Claude Code

trinity-ability and others added 5 commits October 10, 2026 15:04
…ansport (Abilityai/trinity-enterprise#692)

Adds §21.5.1: MCP tools for source management, admitted for the principals
require_admin already admits; agent and connector keys stay refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…status (Abilityai/trinity-enterprise#692)

- POST /api/skills/sources/apply: register-or-update keyed on the
  repository URL (201 created / 200 updated|unchanged / 409
  ambiguous_source), same URL boundary as create, same admin gates.
- POST /api/skills/sources accepts an optional priority.
- GET /api/skills/library/status carries last_fleet_reinject, counts
  only; the per-agent failures map stays on the admin routes.
- routers/skills.py # mcp: header names the new skill_sources.ts tools.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…/trinity-enterprise#692)

list_skill_sources, register_skill_source (idempotent apply),
update_skill_source, delete_skill_source, sync_skill_source and
sync_skill_library: thin proxies over the require_admin source routes.
canAccess is an allow-list of user/system scope, re-checked in-tool;
agent and connector keys are never advertised them and the backend
refuses them regardless. Sync tools report ran / refused_busy / failed
and where a started fleet re-inject's outcome lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…se#692)

architecture/mcp-server.md tool table + count, api-endpoints.md apply
route, skills-library-sync feature flow, user-doc tool counts and rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ong-typed re-inject report (Abilityai/trinity-enterprise#692)

Two review findings on the source-apply / library-status changes:

- `apply_skill_source`: when the matched row is deleted between the match
  and the update, `update_skill_source` answers None. The service reported
  `("updated", None)` and the router 500'd on `source.id` in the audit call.
  It now re-resolves (bounded), so the declared source is re-created.
- `_read_last_fleet_reinject`: a parseable dict with a wrong-typed field
  (null/string count, non-string timestamp) passed the isinstance check and
  failed `FleetReinjectSummary` at response validation, 500-ing the open
  `GET /api/skills/library/status`. The blob is now validated against that
  model inside the fail-soft read and degrades to null.

Both tests were red before the change (6 failures) and are green after.
Learnings fragment added for the response_model-projection class.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trinity-ability

Copy link
Copy Markdown
Contributor Author

/review Report

Branch: feature/ent692-skill-sources-mcp → dev (diffed against the merge-base)
Files Changed: 18 (+1268/-18) in the reviewed head, plus the review-fix commit 4f8288f4b
Scope: CLEAN. The change implements abilityai/trinity-enterprise#692 (A–D). It does not add the declarative sources: document, which was held as a non-goal.
Plan Completion: AC1–AC7: 6 done, 1 unverifiable

  • AC1 done: skill_sources.ts proxies each route, and the body comes back unchanged (pretty-printed JSON).
  • AC2 done: TestAgentKeysRefusedByTheGate runs the real require_admin with the per-route reject_agent_principal neutralised.
  • AC3 done: /apply is idempotent on the repository URL. See I1 and I2 for the edges.
  • AC4 done: the apply response body is byte-equal to create's 400, and the MCP refusal passes the route's detail through.
  • AC5 done: ran / refused_busy / failed, plus the last_fleet_reinject counts on the open status route.
  • AC6 unverifiable from the diff alone: the change is additive (an optional field and a new route), and no automation is touched.
  • AC7 done: requirements §21.5 / §21.5.1.

Execution coverage (Step 2.5)

changed symbol / test file executed by live consumer verdict
POST /skills/sources/apply + apply_skill_source TestApplyIsIdempotentOnUrl, TestApplyRacesAConcurrentDelete (TestClient, real router, real SQLite ops) MCP register_skill_source ✅ executed
SkillSourceCreate.priority TestCreateAcceptsPriority create_skill_source route ✅ executed
FleetReinjectSummary / _read_last_fleet_reinject TestStatusCarriesReinjectSummary, TestStatusSurvivesATypeMalformedReport GET /skills/library/status response_model ✅ executed
skill_sources.ts (6 tools, canAccess, in-tool deny) skill_sources.test.ts: unit tests plus a real createServer over streamable HTTP (list and call-by-name per scope) server.ts registration ✅ executed
TOOL_ACCESS_POLICY rows registration guard in addToolWithAudit (refuses to register a tool with no row) server boot 🛡 guard
# mcp: header test (read_text) — /validate-architecture (Invariant #13) 🛡 guard

Fix mutation: this is a feature PR, so there was no prior fix to revert. For the two review fixes, the new tests failed against the pre-fix code (6 red: AttributeError: 'NoneType' object has no attribute 'id' and ResponseValidationError ×5) and pass after 4f8288f4b.

Critical Findings (block merge)

[C1] Race / error handling: a concurrent DELETE during /apply returned a 500 and reported updated over a row that was gone. (Confidence: 9/10). FIXED in 4f8288f4b.
File: src/backend/services/skill_service.py (apply_skill_source._update), src/backend/routers/skills.py:1161
Evidence: return "updated", db.update_skill_source(existing.id, **changed). update_source returns None when the row is gone. The router then calls await _audit_source(request, admin_user, "skill_source_update", source.id, ...), which raises AttributeError, so the response is a 500.
Issue: if another admin deletes the matched row between the match and the update, the caller gets a 500. Without the audit call, the result would have been {"action":"updated","source":null}, which is a false success.
Fix: _update now returns None when the row vanished, and the apply re-resolves inside a bounded loop of 3. In practice the retry re-creates the declared source (201 created). If the rows keep changing, the loop ends with a 409 that says so. Test: TestApplyRacesAConcurrentDelete.

[C2] Error handling: the open GET /api/skills/library/status returned a 500 on a well-formed but wrong-typed re-inject report. (Confidence: 8/10). FIXED in 4f8288f4b.
File: src/backend/services/skill_service.py (_read_last_fleet_reinject)
Evidence: return report if isinstance(report, dict) else None. The value is then projected through last_fleet_reinject: Optional[FleetReinjectSummary] on the route's response_model, and agents_total: int = 0 rejects null.
Issue: the docstring promises that status never returns a 500 over a malformed blob. In fact, a dict that parses but has a null or string count, or a non-string timestamp, failed response validation. This route is open to every principal, and every agent's Skills tab and the MCP get_skills_library_status read it. The only current writer stores correct types, so triggering this takes a direct DB write or a different writer version. That is why it is rated 8, not 10.
Fix: the blob is validated against FleetReinjectSummary inside the same fail-soft try, and a failure degrades to null for both consumers. The raw blob is still available on the admin GET /api/settings/skills-library. Test: TestStatusSurvivesATypeMalformedReport (5 shapes).

Informational Findings (review required)

[I1] Scope / product: one repo on two refs can't be driven by /apply, even when the caller names the exact ref. (Confidence: 8/10)
File: src/backend/services/skill_service.py (apply_skill_source)
Issue: matching is by repository only. With rows (X, main) and (X, v1), the call apply {url: X, ref: main, priority: 5} returns 409 ambiguous_source. With a single row, a declared document that lists the same repo twice on different refs makes the second apply move the first row's ref, so the two entries flap. AC3 says "idempotent on url", so this follows the issue as written. The PR names it as product decision 3.
Suggestion: when the doc format is designed (with ent#683), consider keying on (url, ref) when ref is named and the exact pair exists.

[I2] Concurrency: two concurrent applies of the same repo on different refs can both insert. (Confidence: 7/10)
Issue: each request sees no match, and the inserts don't collide on UNIQUE(url, ref). The result is two rows for one repo, and the next apply returns 409 ambiguous_source naming both ids. The failure is visible and recoverable with delete_skill_source. Only admins can do this, and it is rare. A real fix needs a cross-worker lock (Redis) or a uniqueness rule on the normalized repo, and neither is warranted here. Left as is.

[I3] Matching edge: .git, a trailing / and case differences don't match. (Confidence: 8/10)
Issue: _same_skills_repo collapses only the scheme/no-scheme split (by design, #2763/ent#346, "closing that tail is tracked separately"). So https://github.com/acme/skills.git applied after https://github.com/acme/skills creates a second row for the same repository. This is pre-existing behaviour, but /apply makes it easier to hit.

[I4] Honesty: sync_skill_source never starts a fleet re-inject. (Confidence: 7/10)
Issue: the per-source route doesn't spawn run_fleet_reinject when the commit moves; only /skills/library/sync does. That is pre-existing REST behaviour. The tool returns fleet_reinject: {started: false}, which is accurate. Its description could also say that running agents keep the old content until a library sync or their next inject.

[I5] Consistency: SkillSourceUpdate (PUT, and so update_skill_source) has no control-character validator on name/ref, while create and apply do. (Confidence: 6/10) This is pre-existing and outside this diff.

[I6] MCP: in dev mode (requireApiKey=false, no auth context), canAccess hides the tools but the in-tool deny admits a call by name. (Confidence: 6/10) This is harmless, because dev mode has no principal to fence, and the backend still enforces the gate.

Clean Categories

  • SQL safety: there is no raw SQL. Writes go through SQLAlchemy insert/update in db/skill_sources.py.
  • Auth boundaries:
    • Every source route keeps Depends(require_admin) plus reject_agent_principal. require_admin itself enforces ADMIN_GATE_SCOPES = {None, user, system}, and AC2 is proven through the real gate.
    • MCP visibility is an allowlist: SOURCE_ADMIN_SCOPES.has(auth?.scope ?? "") means an unknown, ops or absent scope fails closed (feat: MCP inline email auth — frictionless onboarding without a pre-existing Trinity account #848). The tool's own canAccess wins over the group default (server.ts addToolWithAudit), and this is pinned over the real transport.
    • A non-admin user key sees the tools, and the backend refuses it with Admin access required.
  • Route order (Invariant fix: add missing logging_config.py to backend Dockerfile #4): POST /skills/sources/apply is the only POST under /skills/sources/<x>. The {source_id} routes are PUT/DELETE, and .../{id}/sync has an extra segment. No other router mounts /api/skills/sources.
  • Credential-in-URL: /apply uses the same reject_embedded_credentials + validate_skills_library_url as create, with a byte-equal 400. MCP audit (withAudit) records only the target id, never params, so a refused tokenized URL is not logged.
  • Credential exposure: the open status projection is counts only. The failures map stays on admin routes, and per-source url/last_error are still stripped (ent#334).
  • Enterprise disclosure (4.5): the enterprise-docs-guard pattern finds no hits in the added doc lines.
  • Idempotency-Key (Invariant Unified Executions Dashboard (EXEC-022) #18): not applicable, because /apply creates no execution.
  • Enum completeness: the TOOL_ACCESS_POLICY rows are present for all six tools, and registration refuses a tool without one.
  • Docs: requirements, architecture (api-endpoints, mcp-server), feature-flow and user-docs tool counts are all updated.

Summary

  • Critical: 2. Both were fixed in 4f8288f4b, and the tests were red before the fix and green after.
  • Informational: 6. All are product/scope choices or pre-existing behaviour, and are left for maintainer judgment.
  • Scope: clean.

Verification after fixes

  • Backend: pytest unit/test_ent692_skill_sources_mcp.py: 38 passed. Related files (all *skill*, test_293_admin_gate*, test_1310_*, test_186_*, test_models_centralized, *ent334*, *2763*): 1183 passed, 1 skipped.
  • MCP server: npm test: 868/868 passed. npx tsc --noEmit: clean.

Learnings fragment: docs/memory/learnings/2026-10-10-response-model-projection-of-stored-blob.md.

🤖 Generated with Claude Code

@trinity-ability
trinity-ability marked this pull request as ready for review October 10, 2026 20:35
…n the ent692 client (Abilityai/trinity-enterprise#692)

test_duplicate_create_still_409s failed in CI's full-suite regression diff:
a file that evicts db.* after routers.skills is imported leaves the router
catching a stale DuplicateSkillSource, so the facade's raise escaped as a raw
exception instead of a 409. Reproduced locally with a forced eviction; the
client now rebinds DuplicateSkillSource/DefaultSourceExists to the module the
facade raises from.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge-train: batch validated on train/20261011-0752 (#3528)

@vybe
vybe merged commit a27171a into dev Oct 11, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants