From 8277e09b39e4c597ac14738386a52af18f698851 Mon Sep 17 00:00:00 2001 From: Guillaume Leroy Date: Tue, 6 Oct 2026 16:54:49 +0200 Subject: [PATCH] feat!: remove A2A agents from the registry The registry now catalogs MCP servers only. Migration 000026 deletes agent rows from the shared tables and drops the agent tables. --- .github/workflows/quality.yml | 25 +- ARCHITECTURE.md | 38 +- CLAUDE.md | 8 +- CONTRIBUTING.md | 5 +- README.md | 15 +- deploy/.env.example | 11 +- deploy/bootstrap.example.yaml | 355 +-- deploy/config.example.yaml | 8 +- deploy/helm/ai-registry/Chart.yaml | 3 +- deploy/helm/ai-registry/README.md | 4 +- .../ai-registry/files/bootstrap-sample.yaml | 355 +-- .../templates/api/configmap-bootstrap.yaml | 2 +- .../ai-registry/templates/http-route.yaml | 13 +- .../helm/ai-registry/templates/ingress.yaml | 13 +- deploy/helm/ai-registry/values.yaml | 6 +- docker-compose.yml | 5 +- docs/astro.config.ts | 2 +- docs/src/content/docs/guides/local-stack.md | 1 - docs/src/content/docs/guides/seeding.md | 4 +- docs/src/content/docs/index.md | 14 +- .../content/docs/reference/configuration.md | 2 +- server/Dockerfile | 2 +- server/api/a2a-agent-card.schema.json | 91 - server/api/openapi.yaml | 2574 ++++------------- server/api/spec.go | 14 +- server/go.mod | 1 - server/go.sum | 2 - server/internal/agents/card.go | 217 -- server/internal/agents/card_test.go | 273 -- server/internal/bootstrap/bootstrap.go | 230 -- server/internal/bootstrap/bootstrap_test.go | 204 +- server/internal/bootstrap/spec.go | 55 - server/internal/config/config.go | 10 +- server/internal/domain/agent.go | 190 -- server/internal/domain/agent_test.go | 190 -- server/internal/domain/audit.go | 27 +- server/internal/domain/entrychange.go | 1 - server/internal/domain/report.go | 2 +- server/internal/domain/url_test.go | 40 +- server/internal/http/handlers/activity.go | 43 +- .../internal/http/handlers/activity_test.go | 91 +- server/internal/http/handlers/agent.go | 807 ------ server/internal/http/handlers/agent_test.go | 1067 ------- server/internal/http/handlers/agentcard.go | 84 - .../internal/http/handlers/agentcard_test.go | 384 --- server/internal/http/handlers/audit.go | 2 +- server/internal/http/handlers/audit_test.go | 8 +- server/internal/http/handlers/entrychange.go | 117 +- .../http/handlers/entrychange_test.go | 144 +- server/internal/http/handlers/publisher.go | 4 +- server/internal/http/handlers/reports.go | 9 +- server/internal/http/handlers/reports_test.go | 16 +- server/internal/http/handlers/review.go | 282 +- server/internal/http/handlers/review_test.go | 187 +- .../http/handlers/router_security_test.go | 8 +- server/internal/http/handlers/stats_test.go | 19 +- .../internal/http/handlers/testmain_test.go | 2 +- .../http/handlers/url_validation_test.go | 20 - server/internal/http/handlers/visibility.go | 63 - .../internal/http/handlers/visibility_test.go | 108 - server/internal/http/router.go | 57 +- .../internal/http/router_admin_guard_test.go | 4 - server/internal/observability/metrics.go | 10 - .../observability/observability_test.go | 3 - server/internal/problem/problem_test.go | 6 +- server/internal/store/agent.go | 1013 ------- server/internal/store/agent_test.go | 841 ------ server/internal/store/changelog.go | 54 +- server/internal/store/entrychange.go | 55 - server/internal/store/entrychange_test.go | 32 - server/internal/store/migrate_test.go | 20 +- server/internal/store/publisher.go | 31 +- server/internal/store/publisher_stats_test.go | 8 - server/internal/store/publisher_test.go | 58 +- server/internal/store/reports.go | 10 +- server/internal/store/reports_test.go | 16 +- server/internal/store/review.go | 402 +-- server/internal/store/review_test.go | 387 +-- server/internal/store/stats.go | 55 +- server/internal/store/stats_test.go | 14 +- server/internal/store/tags.go | 7 +- server/internal/store/tags_test.go | 72 - server/internal/store/testhelper_test.go | 2 +- .../migrations/000026_remove_agents.down.sql | 108 + server/migrations/000026_remove_agents.up.sql | 22 + test/load/smoke.js | 7 - test/nginx/routing.sh | 2 +- web/e2e/activity.spec.ts | 6 +- web/e2e/admin-stats.spec.ts | 9 +- web/e2e/admin.spec.ts | 89 +- web/e2e/coverage-admin.spec.ts | 7 - web/e2e/coverage-public.spec.ts | 61 +- web/e2e/detail.spec.ts | 124 +- web/e2e/public.spec.ts | 62 +- web/e2e/user-journeys.spec.ts | 59 +- web/nginx.conf | 14 - .../components/admin/activity-timeline.tsx | 3 +- .../admin/new-version-form.test.tsx | 65 +- web/src/components/admin/new-version-form.tsx | 600 +--- .../admin/publisher-overview.test.tsx | 14 +- .../components/admin/publisher-overview.tsx | 52 +- .../admin/request-deletion-button.test.tsx | 19 +- .../admin/request-deletion-button.tsx | 16 +- .../admin/versions-section.test.tsx | 37 +- web/src/components/admin/versions-section.tsx | 81 +- web/src/components/agents/agent-card.test.tsx | 103 - web/src/components/agents/agent-card.tsx | 96 - web/src/components/agents/auth-guide.test.tsx | 37 - web/src/components/agents/auth-guide.tsx | 71 - .../agents/snippet-generator.test.tsx | 53 - .../components/agents/snippet-generator.tsx | 148 - ...-tiles.test.tsx => protocol-tile.test.tsx} | 31 +- web/src/components/home/protocol-tile.tsx | 45 + web/src/components/home/protocol-tiles.tsx | 88 - .../components/layout/admin-sidebar.test.tsx | 11 - web/src/components/layout/admin-sidebar.tsx | 3 +- web/src/components/layout/footer.tsx | 2 +- web/src/components/layout/header.tsx | 8 +- .../components/shared/activity-feed.test.tsx | 31 +- web/src/components/shared/activity-feed.tsx | 25 +- .../components/shared/publisher-sidebar.tsx | 21 +- .../shared/related-entries.test.tsx | 31 +- web/src/components/shared/related-entries.tsx | 37 +- .../components/shared/report-dialog.test.tsx | 10 +- web/src/components/shared/report-dialog.tsx | 6 +- .../shared/sticky-detail-header.test.tsx | 2 - .../shared/sticky-detail-header.tsx | 4 +- .../shared/version-history.test.tsx | 27 +- web/src/components/shared/version-history.tsx | 21 +- web/src/components/ui/resource-icon.test.tsx | 7 +- web/src/components/ui/resource-icon.tsx | 5 +- web/src/components/ui/search-bar.test.tsx | 2 +- web/src/components/ui/search-bar.tsx | 85 +- web/src/hooks/use-record-event.test.ts | 31 +- web/src/hooks/use-record-event.ts | 51 +- web/src/lib/field-explanations.test.ts | 8 - web/src/lib/field-explanations.ts | 17 - web/src/lib/mode-labels.test.ts | 46 - web/src/lib/mode-labels.ts | 70 - web/src/lib/schema.d.ts | 1927 ++---------- web/src/pages/admin/agents/detail.test.tsx | 304 -- web/src/pages/admin/agents/detail.tsx | 509 ---- web/src/pages/admin/agents/list.test.tsx | 203 -- web/src/pages/admin/agents/list.tsx | 332 --- web/src/pages/admin/agents/new.test.tsx | 191 -- web/src/pages/admin/agents/new.tsx | 481 --- web/src/pages/admin/audit.test.tsx | 31 +- web/src/pages/admin/audit.tsx | 15 - web/src/pages/admin/dashboard.test.tsx | 27 +- web/src/pages/admin/dashboard.tsx | 176 +- web/src/pages/admin/layout.test.tsx | 1 - web/src/pages/admin/mcp/detail.tsx | 3 +- .../pages/admin/publishers/detail.test.tsx | 23 +- web/src/pages/admin/publishers/detail.tsx | 83 +- web/src/pages/admin/publishers/list.tsx | 2 +- web/src/pages/admin/publishers/new.tsx | 2 +- web/src/pages/admin/reports.tsx | 9 +- web/src/pages/admin/review/index.test.tsx | 16 +- web/src/pages/admin/review/index.tsx | 92 +- web/src/pages/agents/detail.test.tsx | 244 -- web/src/pages/agents/detail.tsx | 382 --- web/src/pages/agents/list.test.tsx | 137 - web/src/pages/agents/list.tsx | 107 - web/src/pages/agents/namespace.test.tsx | 165 -- web/src/pages/agents/namespace.tsx | 150 - web/src/pages/changelog.test.tsx | 11 +- web/src/pages/changelog.tsx | 15 +- web/src/pages/explore.test.tsx | 126 +- web/src/pages/explore.tsx | 138 +- web/src/pages/getting-started.test.tsx | 2 +- web/src/pages/getting-started.tsx | 105 +- web/src/pages/home.test.tsx | 43 +- web/src/pages/home.tsx | 65 +- web/src/pages/mcp/detail.test.tsx | 2 +- web/src/pages/mcp/detail.tsx | 11 +- web/src/pages/mcp/namespace.test.tsx | 2 +- web/src/pages/mcp/namespace.tsx | 5 +- web/src/pages/publishers/detail.test.tsx | 15 +- web/src/pages/publishers/detail.tsx | 48 +- web/src/router.tsx | 12 - web/vite.config.ts | 9 - 181 files changed, 1850 insertions(+), 18695 deletions(-) delete mode 100644 server/api/a2a-agent-card.schema.json delete mode 100644 server/internal/agents/card.go delete mode 100644 server/internal/agents/card_test.go delete mode 100644 server/internal/domain/agent.go delete mode 100644 server/internal/domain/agent_test.go delete mode 100644 server/internal/http/handlers/agent.go delete mode 100644 server/internal/http/handlers/agent_test.go delete mode 100644 server/internal/http/handlers/agentcard.go delete mode 100644 server/internal/http/handlers/agentcard_test.go delete mode 100644 server/internal/store/agent.go delete mode 100644 server/internal/store/agent_test.go create mode 100644 server/migrations/000026_remove_agents.down.sql create mode 100644 server/migrations/000026_remove_agents.up.sql delete mode 100644 web/src/components/agents/agent-card.test.tsx delete mode 100644 web/src/components/agents/agent-card.tsx delete mode 100644 web/src/components/agents/auth-guide.test.tsx delete mode 100644 web/src/components/agents/auth-guide.tsx delete mode 100644 web/src/components/agents/snippet-generator.test.tsx delete mode 100644 web/src/components/agents/snippet-generator.tsx rename web/src/components/home/{protocol-tiles.test.tsx => protocol-tile.test.tsx} (50%) create mode 100644 web/src/components/home/protocol-tile.tsx delete mode 100644 web/src/components/home/protocol-tiles.tsx delete mode 100644 web/src/lib/mode-labels.test.ts delete mode 100644 web/src/lib/mode-labels.ts delete mode 100644 web/src/pages/admin/agents/detail.test.tsx delete mode 100644 web/src/pages/admin/agents/detail.tsx delete mode 100644 web/src/pages/admin/agents/list.test.tsx delete mode 100644 web/src/pages/admin/agents/list.tsx delete mode 100644 web/src/pages/admin/agents/new.test.tsx delete mode 100644 web/src/pages/admin/agents/new.tsx delete mode 100644 web/src/pages/agents/detail.test.tsx delete mode 100644 web/src/pages/agents/detail.tsx delete mode 100644 web/src/pages/agents/list.test.tsx delete mode 100644 web/src/pages/agents/list.tsx delete mode 100644 web/src/pages/agents/namespace.test.tsx delete mode 100644 web/src/pages/agents/namespace.tsx diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 1c49e82e..9335a624 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -1,7 +1,7 @@ name: Quality # All correctness gates: Go build + unit/integration tests, the OpenAPI↔router -# and A2A contract suites, web build + unit tests, Helm render validation, and +# contract suites, web build + unit tests, Helm render validation, and # the Playwright + k6 end-to-end suite. Static analysis (gofmt/vet/eslint/tsc/ # helm lint/...) lives in the separate Lint workflow via pre-commit. on: @@ -46,17 +46,13 @@ jobs: # Explicit conformance + contract suite run. Everything under this step # already ran as part of `go test ./...` above — the repeat is deliberate - # so the CI log surfaces these tests by name. If the A2A Agent Card schema, - # OpenAPI↔router contract, or the admin-guard router contract are ever - # deleted or renamed without updating this step, CI fails loudly instead - # of silently passing. + # so the CI log surfaces these tests by name. If the OpenAPI↔router or the + # admin-guard router contract is ever deleted or renamed without updating + # this step, CI fails loudly instead of silently passing. - name: Contract & conformance suites (named) working-directory: server run: | set -euo pipefail - go test -count=1 -v \ - -run '^(TestAgentCardHandler_PerAgentCard_A2AConformance$|TestAgentCardHandler_GlobalAgentCard_A2AConformance$|TestAgentCardHandler_GlobalAgentCard_MisconfiguredReturns500$|TestRegistryCard_A2AConformance$)' \ - ./internal/http/handlers/... go test -count=1 -v \ -run '^(TestOpenAPIContract_MatchesRouter$|TestAllWriteRoutesRequireAdmin$|TestPublicWriteRoutesBypassAdmin$)' \ ./internal/http/ @@ -79,12 +75,12 @@ jobs: } # ── OpenAPI ↔ router contract ──────────────────────────────────────────────── - # Dedicated, fast job that only runs the OpenAPI↔router and A2A Agent Card - # conformance suites. Duplicates what the server job covers, but surfaces the + # Dedicated, fast job that only runs the OpenAPI↔router contract suites. + # Duplicates what the server job covers, but surfaces the # result as its own required check so a spec drift is obvious in the PR UI # without digging into a long log. contract: - name: API contract (OpenAPI + A2A) + name: API contract (OpenAPI) runs-on: ubuntu-latest timeout-minutes: 5 @@ -105,9 +101,6 @@ jobs: go test -count=1 -v \ -run '^(TestOpenAPIContract_MatchesRouter$|TestAllWriteRoutesRequireAdmin$|TestPublicWriteRoutesBypassAdmin$)' \ ./internal/http/ - go test -count=1 -v \ - -run '^(TestAgentCardHandler_PerAgentCard_A2AConformance$|TestAgentCardHandler_GlobalAgentCard_A2AConformance$|TestAgentCardHandler_GlobalAgentCard_MisconfiguredReturns500$|TestRegistryCard_A2AConformance$)' \ - ./internal/http/handlers/... # ── Web: build/typecheck, OpenAPI sync, unit tests ─────────────────────────── web: @@ -383,8 +376,8 @@ jobs: echo "Server ready." # ── Web (native Vite server) ────────────────────────────────────────── - # The Vite server binds :3000 and proxies /api, /config.json, and the A2A - # agent-card paths to the server on :8081 (see web/vite.config.ts), the + # The Vite server binds :3000 and proxies /api, /config.json, and + # /.well-known to the server on :8081 (see web/vite.config.ts), the # same surface nginx serves in production. # # `--host 0.0.0.0` forces the dev server onto IPv4. Vite's default host is diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7af811f0..a65e9c02 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -8,8 +8,8 @@ How the AI Registry is put together and why. Commands to run it live in The registry is one Go HTTP service backed by PostgreSQL, plus a static React SPA that is purely a client of the service's versioned API. The service owns -every piece of state and every rule: catalog entries (MCP servers, A2A agents), -their immutable versions, the review workflow, publisher-scoped RBAC, and token +every piece of state and every rule: catalog entries (MCP servers), their +immutable versions, the review workflow, publisher-scoped RBAC, and token issuance. An external OIDC provider is optional and only authenticates people; it never decides what they may do. @@ -44,11 +44,10 @@ docker-compose, nginx (or the Vite dev server) proxies `/api` as well. ### `server/` — the registry service -The single source of truth. It serves the API under `/api/v1`, the discovery -documents (`/.well-known/jwks.json`, `/.well-known/agent-card.json`, per-agent -cards under `/agents/{namespace}/{slug}/.well-known/agent-card.json`), the -OpenAPI document at `/openapi.yaml`, `/config.json` for the SPA, the -`/healthz` / `/readyz` probes and Prometheus `/metrics`. +The single source of truth. It serves the API under `/api/v1`, the JWKS at +`/.well-known/jwks.json`, the OpenAPI document at `/openapi.yaml`, +`/config.json` for the SPA, the `/healthz` / `/readyz` probes and Prometheus +`/metrics`. On start-up, in order: load configuration, set up OpenTelemetry, run the database migrations, seed the bootstrap Server Admin, reconcile the @@ -65,9 +64,8 @@ flush. See [server/cmd/server/main.go](server/cmd/server/main.go). | [`internal/auth`](server/internal/auth/) | Token authority, refresh tokens, OIDC broker, password hashing, bearer authentication, RBAC guards. | | [`internal/domain`](server/internal/domain/) | Entity types, the role lattice, validation, lifecycle rules. No I/O. | | [`internal/store`](server/internal/store/) | Hand-written SQL over `pgx`, migrations runner, seeding. Every query is traced. | -| [`internal/agents`](server/internal/agents/) | Builds A2A Agent Cards from stored agent versions. | | [`internal/tooldiscovery`](server/internal/tooldiscovery/) | MCP client behind "Fetch from server" and "Detect from server": connects to a remote server's declared URL and transport, runs `tools/list`, probes the protocol revisions it accepts, refuses internal addresses. Stores nothing. | -| [`internal/bootstrap`](server/internal/bootstrap/) | Declarative YAML/JSON loader that upserts publishers, servers and agents. | +| [`internal/bootstrap`](server/internal/bootstrap/) | Declarative YAML/JSON loader that upserts publishers and servers. | | [`internal/config`](server/internal/config/) | Resolves every setting from env, YAML file, then default. | | [`internal/observability`](server/internal/observability/) | The one OTel SDK setup (tracer, meter, logger providers) and the metric definitions. | | [`internal/problem`](server/internal/problem/) | RFC 7807 `application/problem+json` responses. | @@ -164,9 +162,7 @@ forward-only migrations in [server/migrations/](server/migrations/). ```mermaid erDiagram publishers ||--o{ mcp_servers : owns - publishers ||--o{ agents : owns mcp_servers ||--o{ mcp_server_versions : has - agents ||--o{ agent_versions : has publishers ||--o{ role_grants : "scopes (null = global)" users ||--o{ role_grants : "granted to" groups ||--o{ role_grants : "granted to" @@ -174,15 +170,13 @@ erDiagram users ||--o{ group_members : "member of" users ||--o{ refresh_tokens : holds mcp_servers ||--o{ entry_change_requests : "pending changes" - agents ||--o{ entry_change_requests : "pending changes" ``` -- **Publishers own everything.** Every MCP server and agent belongs to exactly +- **Publishers own everything.** Every MCP server belongs to exactly one publisher, and its `{namespace}` path segment *is* that publisher's slug. Slugs are unique per publisher, not globally. - **Versions are immutable once published.** A version row is never edited - after `published_at` is set, because consumers cache server metadata and agent - cards. + after `published_at` is set, because consumers cache server metadata. - **`audit_log` and `reports` are polymorphic** (`resource_type` + `resource_id`, `target_type` + `target_id`); the bootstrap loader writes synthetic audit events too. @@ -231,8 +225,7 @@ carries the proposed mutation as a JSONB `payload`, and approval dispatches on `(resource_type, action)` to apply it in the same transaction ([server/internal/store/entrychange.go](server/internal/store/entrychange.go)). A partial unique index allows one pending entry-change per entry, independently -of the pending version and pending deletion an entry may also have. Agents -mirror MCP servers exactly. +of the pending version and pending deletion an entry may also have. ## Design decisions @@ -310,10 +303,7 @@ span ([server/internal/http/](server/internal/http/)). `(created_at, id)`, so inserts do not shift pages under a paging client. The SPA mirrors this with "Load more" rather than page numbers. -**The MCP wire format follows the upstream `server.json` shapes** and agent -cards follow the A2A Agent Card schema, pinned in -[server/api/a2a-agent-card.schema.json](server/api/a2a-agent-card.schema.json) -and checked by conformance tests. `tools[]` on an MCP version is the +**The MCP wire format follows the upstream `server.json` shapes.** `tools[]` on an MCP version is the publisher-declared tool list, distinct from the spec's `capabilities.tools` negotiation flag. @@ -378,10 +368,10 @@ states (`success`, `warning`, `highlight`) are tokens rather than Tailwind colors so both themes stay in step; only instance-tag colors, which a Server Admin picks, keep the stock palette. -**Detail pages lead with how to connect.** An MCP server or agent page puts +**Detail pages lead with how to connect.** An MCP server page puts the endpoint (or run command) in a side column that is always in view, above the README on a phone, and keeps the README in the Overview tab so a long one -never pushes Usage, Tools or Skills off screen. Cards in a listing carry one +never pushes Usage or Tools off screen. Cards in a listing carry one link target and one row of facts; status shows only when it is not `published`, since everything in the public catalog is. @@ -434,7 +424,7 @@ link target and one row of facts; status shows only when it is not direct `publish` endpoint without a second pair of eyes. - There are no registry-native API keys: machine access requires an OIDC provider issuing tokens with the configured audience. -- The catalog covers MCP servers and A2A agents only. +- The catalog covers MCP servers only. - "Fetch from server" and "Detect from server" reach only remote servers that accept anonymous connections. A stdio server runs on the consumer's machine and a server behind authentication rejects the registry, so their diff --git a/CLAUDE.md b/CLAUDE.md index a22d51bc..d1457eec 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,9 +4,8 @@ Guidance for Claude Code when working in this repository. ## Project -AI Registry — a centralized catalog for AI ecosystem artifacts (MCP servers, -A2A agents), exposed via a versioned HTTP API with two SPA -clients (read-only user UI, authenticated admin UI). +AI Registry — a centralized catalog for MCP servers, exposed via a versioned +HTTP API with two SPA clients (read-only user UI, authenticated admin UI). ## Tech stack @@ -33,7 +32,7 @@ clients (read-only user UI, authenticated admin UI). ## Repository layout -- `server/` — Go service. `internal/{http,agents,auth,bootstrap,config,domain,store,observability,problem}`, +- `server/` — Go service. `internal/{http,auth,bootstrap,config,domain,store,observability,problem}`, `api/` (embedded OpenAPI spec), `migrations/`, `cmd/`. - `web/` — the SPA (pages in `src/pages/`). - `deploy/` — ops (compose files, Helm, example configs). @@ -97,4 +96,3 @@ from env/secrets, not a committed file. ## References - MCP: https://modelcontextprotocol.io/ -- A2A / Agent Card: https://a2a-protocol.org/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8d080b5b..2f9d831f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -117,9 +117,8 @@ cd server && go test -coverprofile=coverage.out ./... && go tool cover -func=cov ``` The contract suites are part of `go test ./...`; they assert that the OpenAPI -operations and the chi routes match one-to-one, that every write route is -guarded, and that emitted Agent Cards conform to the pinned A2A schema. Adding -a route without its spec entry, or the reverse, fails them. +operations and the chi routes match one-to-one and that every write route is +guarded. Adding a route without its spec entry, or the reverse, fails them. ### Web — unit and component diff --git a/README.md b/README.md index fb8a6d6c..69f1acf7 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,14 @@ # AI Registry -A self-hostable registry for AI ecosystem artifacts — **MCP servers** and -**A2A agents** — with a versioned HTTP API, a public catalog UI and an admin -console. +A self-hostable registry for **MCP servers**, with a versioned HTTP API, a +public catalog UI and an admin console. [![Lint](https://github.com/Haibread/ai-registry/actions/workflows/lint.yml/badge.svg)](https://github.com/Haibread/ai-registry/actions/workflows/lint.yml) [![Quality](https://github.com/Haibread/ai-registry/actions/workflows/quality.yml/badge.svg)](https://github.com/Haibread/ai-registry/actions/workflows/quality.yml) [![Docker](https://github.com/Haibread/ai-registry/actions/workflows/docker.yml/badge.svg)](https://github.com/Haibread/ai-registry/actions/workflows/docker.yml) ## Description -Teams building with MCP servers and A2A agents end up with them scattered +Teams building with MCP servers end up with them scattered across repositories, wikis and chat threads. The AI Registry is one catalog where publishers declare them, reviewers approve them, and people and machines discover them. @@ -19,9 +18,7 @@ discover them. move through draft, published and deprecated. - **Spec-aware** — MCP metadata follows the [Model Context Protocol](https://modelcontextprotocol.io/) `server.json` - shapes; every agent gets an [A2A](https://a2a-protocol.org/) Agent Card at - `/agents/{namespace}/{slug}/.well-known/agent-card.json`, and the registry - publishes its own at `/.well-known/agent-card.json`. + shapes. - **Review workflow** — Editors propose versions, deletions and entry changes; Reviewers approve them. - **Publisher-scoped RBAC** — Viewer, Editor, Reviewer and Admin roles granted @@ -32,8 +29,8 @@ discover them. 3.1 document is served at `/openapi.yaml`. - **Observable** — OpenTelemetry traces, metrics and logs over OTLP. -It hosts metadata only: it does not run, proxy or sandbox the servers and -agents it lists. The only connections it makes to a listed server are the +It hosts metadata only: it does not run, proxy or sandbox the servers it +lists. The only connections it makes to a listed server are the handshakes and `tools/list` an author asks for from the MCP forms. The documentation lives at diff --git a/deploy/.env.example b/deploy/.env.example index 93e6e6d2..a2628259 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -24,7 +24,7 @@ # ── Bootstrap file (optional) ───────────────────────────────────────────────── # Path to a YAML or JSON file containing initial registry data (publishers, -# MCP servers, agents). When set, the server upserts all entries on startup +# MCP servers). When set, the server upserts all entries on startup # before accepting traffic. Safe to run repeatedly — existing entries are # skipped. Leave unset in production if you do not want any pre-loaded data. # See deploy/bootstrap.example.yaml for the format. @@ -59,12 +59,9 @@ SHUTDOWN_DRAIN_DELAY=5s # Example: http://localhost:3000,https://registry.example.com CORS_ALLOWED_ORIGINS= -# Public-facing base URL of this deployment. Used by the A2A global agent -# card at /.well-known/agent-card.json, as the access-token issuer and to -# derive the OIDC redirects. Must be the externally reachable URL (the address -# clients use), not an internal Docker network address. The agent card -# returns HTTP 500 when this is empty rather than silently advertising -# localhost to external consumers. YAML key: +# Public-facing base URL of this deployment. Used as the access-token issuer +# and to derive the OIDC redirects. Must be the externally reachable URL (the +# address clients use), not an internal Docker network address. YAML key: # `http.public_base_url`. Default is empty. # Example: https://registry.example.com PUBLIC_BASE_URL=http://localhost:3000 diff --git a/deploy/bootstrap.example.yaml b/deploy/bootstrap.example.yaml index 4d4f8b64..b76d39a4 100644 --- a/deploy/bootstrap.example.yaml +++ b/deploy/bootstrap.example.yaml @@ -20,8 +20,8 @@ # • readme — long-form markdown rendered on the detail page # • capabilities (MCP versions) — free-form MCP capabilities JSON # -# Authorization: MCP servers and agents are scoped directly to -# their owning publisher. Roles (Viewer/Editor/Reviewer/Admin) are granted to +# Authorization: MCP servers are scoped directly to their owning +# publisher. Roles (Viewer/Editor/Reviewer/Admin) are granted to # users and groups — either via the admin API or seeded here in `groups` + # `grants` (idempotent, source = config). The group slugs below match the # group-membership claim the dev Keycloak realm emits, so a federated user @@ -868,354 +868,3 @@ mcp_servers: version: "0.1.0" transport: type: "stdio" - -# ── Agents ──────────────────────────────────────────────────────────────────── -agents: - # anthropic/code-review — published, public - - publisher: "anthropic" - slug: "code-review" - name: "Code Review Agent" - description: "Automatically reviews pull requests and suggests improvements." - public: true - featured: true - verified: true - tags: - - "code-review" - - "git" - - "devtools" - - "official" - readme: | - # Code Review Agent - - Reads a pull request diff and posts inline comments that flag bugs, - style issues, and missing tests. - - ## What it's good at - - - Spotting copy/paste bugs - - Catching missing null / error checks - - Suggesting test cases for new branches - - ## What it's not - - It is **not** a replacement for human review on anything security- or - architecture-sensitive. Use it as a first pass, not the final word. - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://agents.anthropic.com/code-review" - default_input_modes: - - "text/plain" - default_output_modes: - - "text/plain" - skills: - - id: "review-pr" - name: "Review Pull Request" - description: "Analyse a PR diff and post inline comments" - tags: - - "git" - - "code-quality" - - id: "suggest-fix" - name: "Suggest Fix" - description: "Generate a code fix for a flagged issue" - tags: - - "code-quality" - authentication: - - scheme: "Bearer" - - # anthropic/browser-agent — published, public, text + image I/O - - publisher: "anthropic" - slug: "browser-agent" - name: "Browser Automation Agent" - description: "Controls a real browser to fill forms, click buttons, and extract information from any website." - public: true - featured: true - verified: true - tags: - - "browser" - - "automation" - - "multimodal" - - "official" - readme: | - # Browser Automation Agent - - A headful browser agent. Give it a goal in plain English ("book me a - table for two at 8pm") and it will navigate, click, type and screenshot - its way to the result. - - ## I/O modes - - - **Input:** `text/plain`, `application/json` - - **Output:** `text/plain`, `image/png` (screenshots) - - Screenshots are returned alongside text so your host can show the user - what the agent actually did. - versions: - - version: "1.2.0" - status: "published" - endpoint_url: "https://agents.anthropic.com/browser" - default_input_modes: - - "text/plain" - - "application/json" - default_output_modes: - - "text/plain" - - "image/png" - skills: - - id: "navigate" - name: "Navigate" - description: "Open a URL in the browser" - tags: - - "browser" - - "automation" - - id: "click" - name: "Click Element" - description: "Click on a CSS selector" - tags: - - "browser" - - "automation" - - id: "screenshot" - name: "Screenshot" - description: "Capture the current viewport as a PNG" - tags: - - "browser" - - "visual" - - id: "extract" - name: "Extract Data" - description: "Pull structured data from a page using a schema" - tags: - - "browser" - - "data" - authentication: - - scheme: "Bearer" - - # openai/data-analyst — published, public - - publisher: "openai" - slug: "data-analyst" - name: "Data Analyst Agent" - description: "Analyses structured datasets and produces charts and summaries." - public: true - featured: true - verified: true - tags: - - "data" - - "analytics" - - "charts" - - "csv" - readme: | - # Data Analyst Agent - - Accepts CSV, JSON, or plain-text datasets and returns a written - analysis alongside any charts it decided to draw. - - ## Typical flow - - 1. Host uploads a CSV via `text/csv` input - 2. Agent runs exploratory stats and picks an appropriate chart - 3. Agent replies with a written summary (`text/plain`), the generated - chart (`image/png`), and the raw numbers (`application/json`) - versions: - - version: "0.9.0" - status: "published" - endpoint_url: "https://agents.openai.com/data-analyst" - default_input_modes: - - "text/plain" - - "application/json" - - "text/csv" - default_output_modes: - - "text/plain" - - "image/png" - - "application/json" - skills: - - id: "analyse-csv" - name: "Analyse CSV" - description: "Parse and summarise a CSV file" - tags: - - "data" - - "csv" - - id: "plot-chart" - name: "Plot Chart" - description: "Generate a chart from tabular data" - tags: - - "data" - - "visualisation" - - id: "sql-query" - name: "SQL Query" - description: "Run a SQL query against an uploaded file" - tags: - - "data" - - "sql" - authentication: - - scheme: "ApiKey" - - # openai/research-agent — deprecated - - publisher: "openai" - slug: "research-agent" - name: "Research Agent" - description: "Searches the web and academic databases to answer deep research questions." - public: true - verified: true - status: "deprecated" - tags: - - "research" - - "search" - - "deprecated" - readme: | - # Research Agent (deprecated) - - Replaced by the newer `openai/deep-research` agent, which uses a - long-horizon planner and can run for minutes without losing track of - its sub-goals. - - The 0.5.x line will continue to respond but receives no new features. - versions: - - version: "0.5.0" - status: "published" - endpoint_url: "https://agents.openai.com/research" - default_input_modes: - - "text/plain" - default_output_modes: - - "text/plain" - skills: - - id: "web-search" - name: "Web Search" - description: "Search the public web" - tags: - - "search" - - "research" - - id: "paper-search" - name: "Paper Search" - description: "Query arXiv and Semantic Scholar" - tags: - - "research" - - "academic" - authentication: - - scheme: "Bearer" - - # community/docs-writer — published, public - - publisher: "community" - slug: "docs-writer" - name: "Documentation Writer" - description: "Generates and maintains API documentation from source code." - public: true - tags: - - "docs" - - "openapi" - - "devtools" - readme: | - # Documentation Writer - - Reads a codebase and emits Markdown / OpenAPI documentation for public - interfaces. Plug it into CI to keep your docs in sync with the code on - every merge. - versions: - - version: "0.2.0" - status: "published" - endpoint_url: "https://community.example.com/agents/docs-writer" - default_input_modes: - - "text/plain" - default_output_modes: - - "text/plain" - skills: - - id: "generate-docs" - name: "Generate Docs" - description: "Extract and write API documentation from code" - tags: - - "docs" - - "openapi" - authentication: - - scheme: "Bearer" - - # community/devops-agent — draft (never published) - - publisher: "community" - slug: "devops-agent" - name: "DevOps Agent" - description: "Provisions cloud infrastructure, manages CI/CD pipelines, and monitors deployments." - public: true - tags: - - "devops" - - "cloud" - - "ci-cd" - - "experimental" - readme: | - # DevOps Agent (draft) - - Experimental agent for driving cloud infrastructure. Currently - targets AWS and GCP; Azure support is on the roadmap. - - > This version is **draft** — breaking changes will land before 1.0. - versions: - - version: "0.1.0" - status: "draft" - endpoint_url: "https://community.example.com/agents/devops" - default_input_modes: - - "text/plain" - - "application/json" - default_output_modes: - - "text/plain" - - "application/json" - skills: - - id: "deploy" - name: "Deploy" - description: "Deploy an application to a cloud provider" - tags: - - "cloud" - - "deploy" - - id: "monitor" - name: "Monitor" - description: "Check deployment health and logs" - tags: - - "cloud" - - "observability" - - id: "rollback" - name: "Rollback" - description: "Roll back to a previous release" - tags: - - "cloud" - - "deploy" - authentication: - - scheme: "Bearer" - - scheme: "ApiKey" - - # community/security-scanner — published, private - - publisher: "community" - slug: "security-scanner" - name: "Security Scanner Agent" - description: "Scans codebases and infrastructure configs for common vulnerabilities." - public: false - tags: - - "security" - - "sast" - - "iac" - readme: | - # Security Scanner Agent (internal) - - Runs static analysis across code and IaC (Terraform, Helm, k8s - manifests) and returns a structured finding report. - - Kept **private** so that the list of known-vulnerable patterns isn't - visible to unauthenticated users. - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://community.example.com/agents/security-scanner" - default_input_modes: - - "text/plain" - - "application/json" - default_output_modes: - - "text/plain" - - "application/json" - skills: - - id: "scan-code" - name: "Scan Code" - description: "Static analysis for common CVEs" - tags: - - "security" - - "sast" - - id: "scan-infra" - name: "Scan Infra" - description: "Check IaC files for misconfigurations" - tags: - - "security" - - "iac" - authentication: - - scheme: "ApiKey" diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 720e8eed..fce1dead 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -26,10 +26,8 @@ http: # Per-IP request budget for unauthenticated reads on /api/v1, in # requests per minute. public_rate_limit_rpm: 1000 - # Externally reachable URL of this deployment. Surfaced in the global A2A - # agent card, used as the access-token issuer and to derive the OIDC - # redirects. Empty makes the agent card return HTTP 500 rather than - # advertise localhost to external consumers. Example: "https://registry.example.com". + # Externally reachable URL of this deployment. Used as the access-token + # issuer and to derive the OIDC redirects. Example: "https://registry.example.com". public_base_url: "" # On SIGTERM/SIGINT, /readyz answers 503 for this long while requests are # still served, so load balancers stop routing here before the listener @@ -70,7 +68,7 @@ tool_discovery: rate_limit_rpm: 30 # Optional bootstrap data file. Path to a YAML/JSON document of publishers, -# MCP servers and agents that the server upserts on startup +# and MCP servers that the server upserts on startup # before accepting traffic. The `--bootstrap-file` CLI flag overrides # this YAML key and the BOOTSTRAP_FILE env var. bootstrap_file: "" diff --git a/deploy/helm/ai-registry/Chart.yaml b/deploy/helm/ai-registry/Chart.yaml index b98efef9..498958b6 100644 --- a/deploy/helm/ai-registry/Chart.yaml +++ b/deploy/helm/ai-registry/Chart.yaml @@ -1,13 +1,12 @@ apiVersion: v2 name: ai-registry -description: A centralized registry for AI ecosystem artifacts (MCP servers and AI agents) +description: A centralized registry for MCP servers type: application version: 0.4.0-rc13 appVersion: "0.4.0-rc13" keywords: - ai - mcp - - agent - registry home: https://github.com/haibread/ai-registry sources: diff --git a/deploy/helm/ai-registry/README.md b/deploy/helm/ai-registry/README.md index 73b0fad4..4cf93e06 100644 --- a/deploy/helm/ai-registry/README.md +++ b/deploy/helm/ai-registry/README.md @@ -2,7 +2,7 @@ ![Version: 0.4.0-rc13](https://img.shields.io/badge/Version-0.4.0--rc13-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 0.4.0-rc13](https://img.shields.io/badge/AppVersion-0.4.0--rc13-informational?style=flat-square) -A centralized registry for AI ecosystem artifacts (MCP servers and AI agents) +A centralized registry for MCP servers **Homepage:** @@ -67,7 +67,7 @@ A centralized registry for AI ecosystem artifacts (MCP servers and AI agents) | api.oidcRolesClaim | string | `nil` | OIDC id_token claim path the broker reads realm/global roles from at login. Unset → server default (`realm_access.roles`). | | api.oidcScopes | list | `[]` | OAuth scopes requested at the authorize endpoint. Empty → server default (openid, profile, email). | | api.otlpEndpoint | string | `nil` | OTLP gRPC endpoint for traces/metrics export, e.g. "http://otel-collector:4317". Unset → export disabled. | -| api.publicBaseURL | string | `nil` | [REQUIRED] Public-facing base URL of the deployment (what clients use), e.g. "https://registry.example.com". Used by the A2A global agent card, as the access-token issuer and to derive the OIDC redirects. | +| api.publicBaseURL | string | `nil` | [REQUIRED] Public-facing base URL of the deployment (what clients use), e.g. "https://registry.example.com". Used as the access-token issuer and to derive the OIDC redirects. | | api.readinessProbe | object | `{"failureThreshold":3,"httpGet":{"path":"/readyz","port":"http"},"initialDelaySeconds":5,"periodSeconds":10,"timeoutSeconds":3}` | Readiness probe (full probe object — override any field). | | api.readinessProbe.failureThreshold | int | `3` | Consecutive failures before the pod is marked unready. | | api.readinessProbe.httpGet.path | string | `"/readyz"` | Path polled for readiness. | diff --git a/deploy/helm/ai-registry/files/bootstrap-sample.yaml b/deploy/helm/ai-registry/files/bootstrap-sample.yaml index 4d4f8b64..b76d39a4 100644 --- a/deploy/helm/ai-registry/files/bootstrap-sample.yaml +++ b/deploy/helm/ai-registry/files/bootstrap-sample.yaml @@ -20,8 +20,8 @@ # • readme — long-form markdown rendered on the detail page # • capabilities (MCP versions) — free-form MCP capabilities JSON # -# Authorization: MCP servers and agents are scoped directly to -# their owning publisher. Roles (Viewer/Editor/Reviewer/Admin) are granted to +# Authorization: MCP servers are scoped directly to their owning +# publisher. Roles (Viewer/Editor/Reviewer/Admin) are granted to # users and groups — either via the admin API or seeded here in `groups` + # `grants` (idempotent, source = config). The group slugs below match the # group-membership claim the dev Keycloak realm emits, so a federated user @@ -868,354 +868,3 @@ mcp_servers: version: "0.1.0" transport: type: "stdio" - -# ── Agents ──────────────────────────────────────────────────────────────────── -agents: - # anthropic/code-review — published, public - - publisher: "anthropic" - slug: "code-review" - name: "Code Review Agent" - description: "Automatically reviews pull requests and suggests improvements." - public: true - featured: true - verified: true - tags: - - "code-review" - - "git" - - "devtools" - - "official" - readme: | - # Code Review Agent - - Reads a pull request diff and posts inline comments that flag bugs, - style issues, and missing tests. - - ## What it's good at - - - Spotting copy/paste bugs - - Catching missing null / error checks - - Suggesting test cases for new branches - - ## What it's not - - It is **not** a replacement for human review on anything security- or - architecture-sensitive. Use it as a first pass, not the final word. - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://agents.anthropic.com/code-review" - default_input_modes: - - "text/plain" - default_output_modes: - - "text/plain" - skills: - - id: "review-pr" - name: "Review Pull Request" - description: "Analyse a PR diff and post inline comments" - tags: - - "git" - - "code-quality" - - id: "suggest-fix" - name: "Suggest Fix" - description: "Generate a code fix for a flagged issue" - tags: - - "code-quality" - authentication: - - scheme: "Bearer" - - # anthropic/browser-agent — published, public, text + image I/O - - publisher: "anthropic" - slug: "browser-agent" - name: "Browser Automation Agent" - description: "Controls a real browser to fill forms, click buttons, and extract information from any website." - public: true - featured: true - verified: true - tags: - - "browser" - - "automation" - - "multimodal" - - "official" - readme: | - # Browser Automation Agent - - A headful browser agent. Give it a goal in plain English ("book me a - table for two at 8pm") and it will navigate, click, type and screenshot - its way to the result. - - ## I/O modes - - - **Input:** `text/plain`, `application/json` - - **Output:** `text/plain`, `image/png` (screenshots) - - Screenshots are returned alongside text so your host can show the user - what the agent actually did. - versions: - - version: "1.2.0" - status: "published" - endpoint_url: "https://agents.anthropic.com/browser" - default_input_modes: - - "text/plain" - - "application/json" - default_output_modes: - - "text/plain" - - "image/png" - skills: - - id: "navigate" - name: "Navigate" - description: "Open a URL in the browser" - tags: - - "browser" - - "automation" - - id: "click" - name: "Click Element" - description: "Click on a CSS selector" - tags: - - "browser" - - "automation" - - id: "screenshot" - name: "Screenshot" - description: "Capture the current viewport as a PNG" - tags: - - "browser" - - "visual" - - id: "extract" - name: "Extract Data" - description: "Pull structured data from a page using a schema" - tags: - - "browser" - - "data" - authentication: - - scheme: "Bearer" - - # openai/data-analyst — published, public - - publisher: "openai" - slug: "data-analyst" - name: "Data Analyst Agent" - description: "Analyses structured datasets and produces charts and summaries." - public: true - featured: true - verified: true - tags: - - "data" - - "analytics" - - "charts" - - "csv" - readme: | - # Data Analyst Agent - - Accepts CSV, JSON, or plain-text datasets and returns a written - analysis alongside any charts it decided to draw. - - ## Typical flow - - 1. Host uploads a CSV via `text/csv` input - 2. Agent runs exploratory stats and picks an appropriate chart - 3. Agent replies with a written summary (`text/plain`), the generated - chart (`image/png`), and the raw numbers (`application/json`) - versions: - - version: "0.9.0" - status: "published" - endpoint_url: "https://agents.openai.com/data-analyst" - default_input_modes: - - "text/plain" - - "application/json" - - "text/csv" - default_output_modes: - - "text/plain" - - "image/png" - - "application/json" - skills: - - id: "analyse-csv" - name: "Analyse CSV" - description: "Parse and summarise a CSV file" - tags: - - "data" - - "csv" - - id: "plot-chart" - name: "Plot Chart" - description: "Generate a chart from tabular data" - tags: - - "data" - - "visualisation" - - id: "sql-query" - name: "SQL Query" - description: "Run a SQL query against an uploaded file" - tags: - - "data" - - "sql" - authentication: - - scheme: "ApiKey" - - # openai/research-agent — deprecated - - publisher: "openai" - slug: "research-agent" - name: "Research Agent" - description: "Searches the web and academic databases to answer deep research questions." - public: true - verified: true - status: "deprecated" - tags: - - "research" - - "search" - - "deprecated" - readme: | - # Research Agent (deprecated) - - Replaced by the newer `openai/deep-research` agent, which uses a - long-horizon planner and can run for minutes without losing track of - its sub-goals. - - The 0.5.x line will continue to respond but receives no new features. - versions: - - version: "0.5.0" - status: "published" - endpoint_url: "https://agents.openai.com/research" - default_input_modes: - - "text/plain" - default_output_modes: - - "text/plain" - skills: - - id: "web-search" - name: "Web Search" - description: "Search the public web" - tags: - - "search" - - "research" - - id: "paper-search" - name: "Paper Search" - description: "Query arXiv and Semantic Scholar" - tags: - - "research" - - "academic" - authentication: - - scheme: "Bearer" - - # community/docs-writer — published, public - - publisher: "community" - slug: "docs-writer" - name: "Documentation Writer" - description: "Generates and maintains API documentation from source code." - public: true - tags: - - "docs" - - "openapi" - - "devtools" - readme: | - # Documentation Writer - - Reads a codebase and emits Markdown / OpenAPI documentation for public - interfaces. Plug it into CI to keep your docs in sync with the code on - every merge. - versions: - - version: "0.2.0" - status: "published" - endpoint_url: "https://community.example.com/agents/docs-writer" - default_input_modes: - - "text/plain" - default_output_modes: - - "text/plain" - skills: - - id: "generate-docs" - name: "Generate Docs" - description: "Extract and write API documentation from code" - tags: - - "docs" - - "openapi" - authentication: - - scheme: "Bearer" - - # community/devops-agent — draft (never published) - - publisher: "community" - slug: "devops-agent" - name: "DevOps Agent" - description: "Provisions cloud infrastructure, manages CI/CD pipelines, and monitors deployments." - public: true - tags: - - "devops" - - "cloud" - - "ci-cd" - - "experimental" - readme: | - # DevOps Agent (draft) - - Experimental agent for driving cloud infrastructure. Currently - targets AWS and GCP; Azure support is on the roadmap. - - > This version is **draft** — breaking changes will land before 1.0. - versions: - - version: "0.1.0" - status: "draft" - endpoint_url: "https://community.example.com/agents/devops" - default_input_modes: - - "text/plain" - - "application/json" - default_output_modes: - - "text/plain" - - "application/json" - skills: - - id: "deploy" - name: "Deploy" - description: "Deploy an application to a cloud provider" - tags: - - "cloud" - - "deploy" - - id: "monitor" - name: "Monitor" - description: "Check deployment health and logs" - tags: - - "cloud" - - "observability" - - id: "rollback" - name: "Rollback" - description: "Roll back to a previous release" - tags: - - "cloud" - - "deploy" - authentication: - - scheme: "Bearer" - - scheme: "ApiKey" - - # community/security-scanner — published, private - - publisher: "community" - slug: "security-scanner" - name: "Security Scanner Agent" - description: "Scans codebases and infrastructure configs for common vulnerabilities." - public: false - tags: - - "security" - - "sast" - - "iac" - readme: | - # Security Scanner Agent (internal) - - Runs static analysis across code and IaC (Terraform, Helm, k8s - manifests) and returns a structured finding report. - - Kept **private** so that the list of known-vulnerable patterns isn't - visible to unauthenticated users. - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://community.example.com/agents/security-scanner" - default_input_modes: - - "text/plain" - - "application/json" - default_output_modes: - - "text/plain" - - "application/json" - skills: - - id: "scan-code" - name: "Scan Code" - description: "Static analysis for common CVEs" - tags: - - "security" - - "sast" - - id: "scan-infra" - name: "Scan Infra" - description: "Check IaC files for misconfigurations" - tags: - - "security" - - "iac" - authentication: - - scheme: "ApiKey" diff --git a/deploy/helm/ai-registry/templates/api/configmap-bootstrap.yaml b/deploy/helm/ai-registry/templates/api/configmap-bootstrap.yaml index 41a86467..f73dcb15 100644 --- a/deploy/helm/ai-registry/templates/api/configmap-bootstrap.yaml +++ b/deploy/helm/ai-registry/templates/api/configmap-bootstrap.yaml @@ -6,7 +6,7 @@ Content precedence (highest wins): 2. api.bootstrap.sampleData — the built-in sample data bundled with the chart The server reads this file at startup (BOOTSTRAP_FILE env var) and upserts -all publishers, MCP servers, and agents. Running it multiple times is safe — +all publishers and MCP servers. Running it multiple times is safe — existing entries are skipped. */}} {{- if .Values.api.bootstrap.enabled -}} diff --git a/deploy/helm/ai-registry/templates/http-route.yaml b/deploy/helm/ai-registry/templates/http-route.yaml index ab608811..aa91cfd0 100644 --- a/deploy/helm/ai-registry/templates/http-route.yaml +++ b/deploy/helm/ai-registry/templates/http-route.yaml @@ -7,13 +7,12 @@ in the cluster. Two routes only: * /api → server, so the bulk API traffic reaches the backend directly. * / → web, where nginx serves the SPA AND proxies the remaining backend - paths (/.well-known/, the A2A agent card, /docs, /openapi.yaml, - /config.json, /healthz, /readyz). It answers /metrics with a 404: that - endpoint is scraped on the api Service only. Keeping that long tail in - nginx.conf avoids a second, drift-prone copy of the routing table here - — and avoids routing SPA routes such as /agents/{ns}/{slug} to the - backend. Gateway API ranks PathPrefix matches by specificity, so /api - wins over / for /api/* regardless of rule order. + paths (/.well-known/, /docs, /openapi.yaml, /config.json, /healthz, + /readyz). It answers /metrics with a 404: that endpoint is scraped + on the api Service only. Keeping that long tail in nginx.conf avoids + a second, drift-prone copy of the routing table here. Gateway API + ranks PathPrefix matches by specificity, so /api wins over / for + /api/* regardless of rule order. TLS termination is configured on the Gateway listener, not here. Point your Gateway listener at the appropriate certificate and set httpRoute.host to the diff --git a/deploy/helm/ai-registry/templates/ingress.yaml b/deploy/helm/ai-registry/templates/ingress.yaml index 9f1addd1..8180ad92 100644 --- a/deploy/helm/ai-registry/templates/ingress.yaml +++ b/deploy/helm/ai-registry/templates/ingress.yaml @@ -3,13 +3,12 @@ Two routes only: * /api → server, so the bulk API traffic reaches the backend directly. * / → web, where nginx serves the SPA AND proxies the remaining backend - paths (/.well-known/, the A2A agent card, /docs, /openapi.yaml, - /config.json, /healthz, /readyz). It answers /metrics with a 404: that - endpoint is scraped on the api Service only. Keeping that long tail in - nginx.conf avoids a second, drift-prone copy of the routing table here - — and avoids routing SPA routes such as /agents/{ns}/{slug} to the - backend. The nginx-ingress controller matches the longest prefix, so - /api wins over / for /api/* regardless of rule order. + paths (/.well-known/, /docs, /openapi.yaml, /config.json, /healthz, + /readyz). It answers /metrics with a 404: that endpoint is scraped + on the api Service only. Keeping that long tail in nginx.conf avoids + a second, drift-prone copy of the routing table here. The + nginx-ingress controller matches the longest prefix, so /api wins + over / for /api/* regardless of rule order. */}} apiVersion: networking.k8s.io/v1 kind: Ingress diff --git a/deploy/helm/ai-registry/values.yaml b/deploy/helm/ai-registry/values.yaml index 3d69e341..6153d917 100644 --- a/deploy/helm/ai-registry/values.yaml +++ b/deploy/helm/ai-registry/values.yaml @@ -294,8 +294,8 @@ api: # client IP is the rightmost X-Forwarded-For hop outside this range. trustedProxyCIDR: ~ # -- (string) [REQUIRED] Public-facing base URL of the deployment (what - # clients use), e.g. "https://registry.example.com". Used by the A2A global - # agent card, as the access-token issuer and to derive the OIDC redirects. + # clients use), e.g. "https://registry.example.com". Used as the + # access-token issuer and to derive the OIDC redirects. publicBaseURL: ~ # ── Shutdown ───────────────────────────────────────────────────────────── @@ -319,7 +319,7 @@ api: # ── Bootstrap ──────────────────────────────────────────────────────────── # When enabled, the server loads a bootstrap file on startup and idempotently - # upserts all publishers, MCP servers, and agents. + # upserts all publishers and MCP servers. bootstrap: # -- Load a bootstrap file on startup. enabled: false diff --git a/docker-compose.yml b/docker-compose.yml index d5086eda..7b53f294 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -121,9 +121,8 @@ services: JWT_SIGNING_SEED: ${JWT_SIGNING_SEED:-} DATABASE_URL: ${DATABASE_URL:-postgres://registry:registry@postgres:5432/registry?sslmode=disable} CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-http://localhost:3000} - # Public-facing base URL. The A2A global agent card handler returns - # HTTP 500 when unset rather than silently advertising localhost to - # external consumers; set it here so the stack works out of the box. + # Public-facing base URL: the access-token issuer and the base of the + # OIDC redirects. PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3000} # Mount the example bootstrap file and enable it automatically. Remove or # override BOOTSTRAP_FILE in .env to disable. diff --git a/docs/astro.config.ts b/docs/astro.config.ts index 9b347831..4df135e1 100644 --- a/docs/astro.config.ts +++ b/docs/astro.config.ts @@ -34,7 +34,7 @@ export default defineConfig({ starlight({ title: "AI Registry", description: - "A self-hostable registry for MCP servers and A2A agents, with a versioned HTTP API, a public catalog and an admin console.", + "A self-hostable registry for MCP servers, with a versioned HTTP API, a public catalog and an admin console.", logo: { src: "../logo.svg" }, favicon: "/favicon.svg", social: [{ icon: "github", label: "GitHub", href: REPOSITORY }], diff --git a/docs/src/content/docs/guides/local-stack.md b/docs/src/content/docs/guides/local-stack.md index 2a2e4d0b..7267273c 100644 --- a/docs/src/content/docs/guides/local-stack.md +++ b/docs/src/content/docs/guides/local-stack.md @@ -27,7 +27,6 @@ docker compose --profile prod --profile observability up -d --build | http://localhost:3000/admin | Admin console (sign in through Keycloak) | | http://localhost:8081/openapi.yaml | OpenAPI 3.1 document | | http://localhost:8081/api/v1/mcp/servers | JSON API | -| http://localhost:8081/.well-known/agent-card.json | The registry's own A2A Agent Card | | http://localhost:8080 | Keycloak, realm `ai-registry` | | http://localhost:16686 | Jaeger, with the `observability` profile | diff --git a/docs/src/content/docs/guides/seeding.md b/docs/src/content/docs/guides/seeding.md index 3830f63a..5a07ca8f 100644 --- a/docs/src/content/docs/guides/seeding.md +++ b/docs/src/content/docs/guides/seeding.md @@ -1,12 +1,12 @@ --- title: Seed the catalog from a file -description: Declare publishers, MCP servers and agents in a file the server upserts on start. +description: Declare publishers and MCP servers in a file the server upserts on start. sidebar: order: 2 --- Point `BOOTSTRAP_FILE` (or `--bootstrap-file`) at a YAML or JSON file and the -server upserts the publishers, MCP servers and agents it declares on every +server upserts the publishers and MCP servers it declares on every start. Existing rows are left untouched, except that newly declared `tools[]` are backfilled; role grants are managed through the API, not this file. See [deploy/bootstrap.example.yaml](https://github.com/Haibread/ai-registry/blob/main/deploy/bootstrap.example.yaml). diff --git a/docs/src/content/docs/index.md b/docs/src/content/docs/index.md index 5765d800..c8e12b19 100644 --- a/docs/src/content/docs/index.md +++ b/docs/src/content/docs/index.md @@ -1,14 +1,14 @@ --- title: AI Registry -description: A self-hostable registry for MCP servers and A2A agents. +description: A self-hostable registry for MCP servers. template: splash hero: - tagline: A self-hostable registry for MCP servers and A2A agents, with a versioned HTTP API, a public catalog and an admin console. + tagline: A self-hostable registry for MCP servers, with a versioned HTTP API, a public catalog and an admin console. image: file: ../../../../logo.svg --- -Teams building with MCP servers and A2A agents end up with them scattered +Teams building with MCP servers end up with them scattered across repositories, wikis and chat threads. The AI Registry is one catalog where publishers declare them, reviewers approve them, and people and machines discover them. @@ -17,9 +17,7 @@ discover them. move through draft, published and deprecated. - **Spec-aware** — MCP metadata follows the [Model Context Protocol](https://modelcontextprotocol.io/) `server.json` - shapes; every agent gets an [A2A](https://a2a-protocol.org/) Agent Card at - `/agents/{namespace}/{slug}/.well-known/agent-card.json`, and the registry - publishes its own at `/.well-known/agent-card.json`. + shapes. - **Review workflow** — Editors propose versions, deletions and entry changes; Reviewers approve them. - **Publisher-scoped RBAC** — Viewer, Editor, Reviewer and Admin roles granted @@ -30,8 +28,8 @@ discover them. 3.1 document is served at `/openapi.yaml`. - **Observable** — OpenTelemetry traces, metrics and logs over OTLP. -It hosts metadata only: it does not run, proxy or sandbox the servers and -agents it lists. The only connections it makes to a listed server are the +It hosts metadata only: it does not run, proxy or sandbox the servers it +lists. The only connections it makes to a listed server are the handshakes and `tools/list` an author asks for from the MCP forms. ## Where to start diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index 239e8c4b..1ad3c0dc 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -15,7 +15,7 @@ set: | Variable | Required | Default | Description | | --- | --- | --- | --- | | `DATABASE_URL` | yes | — | PostgreSQL connection string | -| `PUBLIC_BASE_URL` | yes | — | External URL of the deployment, used in agent cards and login redirects | +| `PUBLIC_BASE_URL` | yes | — | External URL of the deployment, used as the access-token issuer and in login redirects | | `JWT_SIGNING_KEY` or `JWT_SIGNING_SEED` | yes | ephemeral key | PEM Ed25519 key, or a ≥ 32-char secret the key is derived from; without either, tokens survive neither a restart nor a second replica | | `CORS_ALLOWED_ORIGINS` | when the SPA is on another origin | — | Comma-separated allowed origins | | `AUTH_BOOTSTRAP_ADMIN_EMAIL` / `AUTH_BOOTSTRAP_ADMIN_PASSWORD` | no | — | Seeds a local Server Admin on first start | diff --git a/server/Dockerfile b/server/Dockerfile index cd937cd5..99e5dcbf 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -49,7 +49,7 @@ FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55 # static labels are the fallback for local builds that don't go through CI. # https://github.com/opencontainers/image-spec/blob/main/annotations.md LABEL org.opencontainers.image.title="ai-registry-server" \ - org.opencontainers.image.description="AI Registry HTTP API (MCP + A2A agent cards)" \ + org.opencontainers.image.description="AI Registry HTTP API (MCP servers)" \ org.opencontainers.image.source="https://github.com/haibread/ai-registry" \ org.opencontainers.image.url="https://github.com/haibread/ai-registry" \ org.opencontainers.image.documentation="https://github.com/haibread/ai-registry/blob/main/README.md" \ diff --git a/server/api/a2a-agent-card.schema.json b/server/api/a2a-agent-card.schema.json deleted file mode 100644 index de87d109..00000000 --- a/server/api/a2a-agent-card.schema.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://ai-registry.example/schemas/a2a-agent-card.schema.json", - "title": "A2A Agent Card", - "description": "Minimal JSON Schema for the A2A (Agent-to-Agent) Agent Card document, pinned to the A2A specification as of June 2025 (https://github.com/a2aproject/A2A). This schema exists to catch regressions in card generation; it is not the official A2A schema. Only the MUST-level fields from the spec are enforced here. Extra (additive) fields are allowed so the registry can evolve without breaking the schema — strictness on `required` is where the real protection lives.", - - "type": "object", - "required": [ - "name", - "version", - "url", - "capabilities", - "defaultInputModes", - "defaultOutputModes", - "skills" - ], - "properties": { - "name": { "type": "string", "minLength": 1 }, - "description": { "type": "string" }, - "version": { "type": "string", "minLength": 1 }, - "url": { "type": "string", "format": "uri" }, - "iconUrl": { "type": "string", "format": "uri" }, - "documentationUrl": { "type": "string", "format": "uri" }, - - "provider": { - "type": "object", - "required": ["organization"], - "properties": { - "organization": { "type": "string", "minLength": 1 }, - "url": { "type": "string", "format": "uri" } - } - }, - - "capabilities": { - "type": "object", - "description": "The A2A spec allows any of these flags to be omitted; when present they must be booleans.", - "properties": { - "streaming": { "type": "boolean" }, - "pushNotifications": { "type": "boolean" }, - "stateTransitionHistory": { "type": "boolean" }, - "extendedAgentCard": { "type": "boolean" } - } - }, - - "defaultInputModes": { - "type": "array", - "minItems": 1, - "items": { "type": "string", "minLength": 1 } - }, - "defaultOutputModes": { - "type": "array", - "minItems": 1, - "items": { "type": "string", "minLength": 1 } - }, - - "skills": { - "type": "array", - "items": { - "type": "object", - "required": ["id", "name", "description", "tags"], - "properties": { - "id": { "type": "string", "minLength": 1 }, - "name": { "type": "string", "minLength": 1 }, - "description": { "type": "string", "minLength": 1 }, - "tags": { - "type": "array", - "items": { "type": "string", "minLength": 1 } - }, - "examples": { "type": "array", "items": { "type": "string" } }, - "inputModes": { "type": "array", "items": { "type": "string" } }, - "outputModes": { "type": "array", "items": { "type": "string" } } - } - } - }, - - "securitySchemes": { - "type": "object", - "description": "A2A delegates security scheme shapes to OpenAPI 3 (type: http | apiKey | oauth2 | openIdConnect). The registry allows exactly those four. We enforce the type discriminator at the scheme level; deeper per-scheme shape is left to the unit tests on buildSecuritySchemes in internal/agents/card.go.", - "additionalProperties": { - "type": "object", - "required": ["type"], - "properties": { - "type": { - "type": "string", - "enum": ["http", "apiKey", "oauth2", "openIdConnect"] - } - } - } - } - } -} diff --git a/server/api/openapi.yaml b/server/api/openapi.yaml index 00e534af..3a0b2650 100644 --- a/server/api/openapi.yaml +++ b/server/api/openapi.yaml @@ -2,7 +2,7 @@ openapi: 3.1.0 info: title: AI Registry API description: > - Centralized registry for MCP servers and AI agents. + Centralized registry for MCP servers. Exposes a versioned HTTP API; all UIs are clients of this API. version: 0.4.0-rc9 contact: @@ -18,8 +18,6 @@ tags: description: Publisher management (admin only) - name: mcp description: MCP server registry (v1) - - name: agents - description: AI agent registry (v1) - name: tags description: Instance-wide tag vocabulary (curated by Server Admins) - name: audit @@ -116,23 +114,6 @@ paths: schema: type: string - /.well-known/agent-card.json: - get: - operationId: globalAgentCard - summary: Global registry A2A Agent Card - description: > - Returns the Google A2A-compatible Agent Card for the registry itself, - making the registry a first-class A2A citizen. - tags: - - agents - responses: - "200": - description: A2A Agent Card - content: - application/json: - schema: - type: object - /.well-known/jwks.json: get: operationId: jwks @@ -1095,7 +1076,7 @@ paths: summary: Delete a publisher (admin only) description: > Hard-deletes the publisher and cascades the deletion to every resource - it owns — all MCP servers and agents, their versions, and any reports + it owns — all MCP servers, their versions, and any reports filed against them — in a single transaction. Owned resources never block the delete. tags: @@ -1149,7 +1130,7 @@ paths: summary: Per-publisher activity feed (member) description: > The audit feed for a single publisher, newest first, paginated. Covers - the lifecycle of every MCP server and agent under the publisher. Open to + the lifecycle of every MCP server under the publisher. Open to any member of the publisher (Viewer and up) or a Server Admin; others get 403. Unlike the public per-resource feed, this members-only feed names the actor (the publisher's own collaborators). @@ -2295,1134 +2276,206 @@ paths: "409": $ref: "#/components/responses/Conflict" - # ── Agents ──────────────────────────────────────────────────────────────── + # ── Stats & Audit ───────────────────────────────────────────────────────── + + /api/v1/public-stats: + get: + operationId: getPublicStats + summary: Public registry statistics (published entries only) + tags: + - system + responses: + "200": + description: Public counts for each resource type + content: + application/json: + schema: + $ref: "#/components/schemas/PublicStats" + "429": + $ref: "#/components/responses/RateLimited" - /api/v1/agents: + /api/v1/changelog: get: - operationId: listAgents - summary: List agents + operationId: getChangelog + summary: Recently published MCP server versions + description: > + Aggregated timeline of version publications, newest first. Only + published versions of public, non-deleted entries are returned. tags: - - agents + - system parameters: - - $ref: "#/components/parameters/LimitParam" - - $ref: "#/components/parameters/CursorParam" - - name: q - in: query - description: Full-text search query (prefix matching) - schema: - type: string - - name: namespace - in: query - description: Filter by publisher slug - schema: - type: string - - name: mine - in: query - description: >- - Scope the listing to resources the authenticated caller can manage. - Server Admins and global-grant holders see every - publisher; an author sees only the publishers they hold a role on, - including their own private/draft entries; a caller with no grants - sees nothing. Requires authentication (401 otherwise). - schema: - type: boolean - - name: status - in: query - description: Filter by lifecycle status - schema: - type: string - enum: - - draft - - published - - deprecated - - name: visibility + - name: limit in: query - description: Filter by visibility (admin only) schema: - type: string - enum: - - public - - private - - name: sort + type: integer + minimum: 1 + maximum: 200 + default: 50 + responses: + "200": + description: Recent version publications across the registry + content: + application/json: + schema: + $ref: "#/components/schemas/ChangelogList" + "429": + $ref: "#/components/responses/RateLimited" + + /api/v1/stats: + get: + operationId: getStats + summary: Registry resource counts (admin only) + tags: + - system + security: + - bearerAuth: [] + responses: + "200": + description: Total counts for each resource type + content: + application/json: + schema: + $ref: "#/components/schemas/RegistryCounts" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + + /api/v1/audit: + get: + operationId: listAuditEvents + summary: List audit log events (admin only) + tags: + - audit + security: + - bearerAuth: [] + parameters: + - name: resource_type in: query - description: Sort order for results (ignored when q is provided — search results are ranked by relevance) + description: Filter by resource type (mcp_server, publisher) schema: type: string - enum: - - created_at_desc - - updated_at_desc - - published_at_desc - - name_asc - - name_desc - default: created_at_desc - - name: featured - in: query - description: Filter by featured status - schema: - type: boolean - - name: tag + - name: resource_id in: query - description: >- - Filter by instance-tag slug carried by the latest published - version (exact match, single tag) + description: Filter by resource ULID schema: type: string - - name: published_since + - name: actor in: query - description: Filter to entries whose latest version was published after this ISO 8601 date-time (e.g. 2025-01-01T00:00:00Z) + description: Filter by Keycloak subject UUID schema: type: string - format: date-time + - $ref: "#/components/parameters/LimitParam" + - $ref: "#/components/parameters/CursorParam" responses: "200": - description: Paginated list of agents + description: Paginated list of audit events content: application/json: schema: - $ref: "#/components/schemas/AgentList" - "429": - $ref: "#/components/responses/RateLimited" + $ref: "#/components/schemas/AuditEventList" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + + /api/v1/reports: post: - operationId: createAgent - summary: Create an agent entry (publisher Editor) + operationId: createReport + summary: File a community issue report description: > - Creates an agent under the publisher named by `namespace`. Requires the - Editor role on that publisher (Admin / Server Admin satisfy it). The new - agent is private + draft. 401 when unauthenticated, 403 - without the role. + Public, rate-limited endpoint for anyone to report problems with a + registry entry (broken packaging, misleading description, spam, + security concern, etc.). Admins triage reports via the admin queue. tags: - - agents - security: - - bearerAuth: [] + - reports requestBody: required: true content: application/json: schema: - $ref: "#/components/schemas/CreateAgentRequest" + $ref: "#/components/schemas/CreateReportRequest" responses: "201": - description: Agent created + description: Report accepted content: application/json: schema: - $ref: "#/components/schemas/Agent" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "409": - $ref: "#/components/responses/Conflict" + $ref: "#/components/schemas/Report" "422": $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}: + "429": + $ref: "#/components/responses/RateLimited" get: - operationId: getAgent - summary: Get an agent by namespace/slug + operationId: listReports + summary: List community issue reports (admin only) tags: - - agents + - reports + security: + - bearerAuth: [] parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" + - name: status + in: query + description: Filter by status + schema: + type: string + enum: + - pending + - reviewed + - dismissed + - name: limit + in: query + schema: + type: integer + minimum: 1 + maximum: 200 + default: 50 responses: "200": - description: Agent detail + description: List of reports content: application/json: schema: - $ref: "#/components/schemas/Agent" - "404": - $ref: "#/components/responses/NotFound" - "429": - $ref: "#/components/responses/RateLimited" + $ref: "#/components/schemas/ReportList" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + + /api/v1/reports/{id}: patch: - operationId: patchAgent - summary: Update an agent's metadata (admin only) + operationId: updateReportStatus + summary: Update a report's status (admin only) tags: - - agents + - reports security: - bearerAuth: [] parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" + - name: id + in: path + required: true + schema: + type: string requestBody: required: true content: application/json: schema: - type: object - properties: - name: - type: string - description: - type: string + $ref: "#/components/schemas/UpdateReportStatusRequest" responses: "200": - description: Updated agent immediately (Server Admin escape hatch) - content: - application/json: - schema: - $ref: "#/components/schemas/Agent" - "202": - description: Metadata edit enqueued for review (non-admin Editor) + description: Updated content: application/json: schema: - $ref: "#/components/schemas/EntryChangeAccepted" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: a change is already pending review on this entry - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - "422": - $ref: "#/components/responses/ValidationError" - delete: - operationId: deleteAgent - summary: Force-delete an agent (admin only — bypasses workflow) - description: | - Admin-only escape hatch that hard-tombstones the agent and all its - versions to status='deleted' without going through the - change-approval workflow. Publisher Editors must use - POST /api/v1/agents/{namespace}/{slug}/deletion-request and wait - for a reviewer's approve to delete; this endpoint is the admin - force-delete path. - tags: - - agents - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "204": - description: Agent deleted - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - - /api/v1/agents/{namespace}/{slug}/visibility: - post: - operationId: setAgentVisibility - summary: Set agent visibility (Editor/Admin) - description: > - Requires the Editor role on the owning publisher (Admin / Server Admin - satisfy it). Switching to `public` requires an approved (published) - version — a `public` request on a draft returns 409. Switching back to - `private` is always allowed. - tags: - - agents - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/SetVisibilityRequest" - responses: - "200": - description: Visibility updated immediately (Server Admin escape hatch) - content: - application/json: - schema: - type: object - properties: - visibility: - type: string - enum: - - public - - private - "202": - description: Visibility change enqueued for review (non-admin Editor) - content: - application/json: - schema: - $ref: "#/components/schemas/EntryChangeAccepted" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: > - Cannot make public — the entry has no approved (published) version - yet; or a change is already pending review on this entry. - content: - application/problem+json: - schema: - $ref: "#/components/schemas/Problem" - "422": - $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}/deprecate: - post: - operationId: deprecateAgent - summary: Deprecate an agent (Editor enqueues, Server Admin immediate) - tags: - - agents - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "200": - description: Agent deprecated immediately (Server Admin escape hatch) - content: - application/json: - schema: - type: object - properties: - status: - type: string - "202": - description: Deprecation enqueued for review (non-admin Editor) - content: - application/json: - schema: - $ref: "#/components/schemas/EntryChangeAccepted" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - $ref: "#/components/responses/Conflict" - - /api/v1/agents/{namespace}/{slug}/undeprecate: - post: - operationId: undeprecateAgent - summary: Republish a deprecated agent (Editor enqueues, Server Admin immediate) - description: > - Reverses a deprecation: the entry returns to `published`. Only valid - when the entry is currently `deprecated` (409 otherwise). Editors - enqueue the change for review like the other entry-level mutations; - Server Admins apply it immediately. - tags: - - agents - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "200": - description: Agent republished immediately (Server Admin escape hatch) - content: - application/json: - schema: - type: object - properties: - status: - type: string - "202": - description: Republish enqueued for review (non-admin Editor) - content: - application/json: - schema: - $ref: "#/components/schemas/EntryChangeAccepted" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - $ref: "#/components/responses/Conflict" - - /api/v1/agents/{namespace}/{slug}/view: - post: - operationId: recordAgentView - summary: Record a view event for an agent (fire-and-forget) - tags: - - agents - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "204": - description: View recorded - "404": - $ref: "#/components/responses/NotFound" - "429": - $ref: "#/components/responses/RateLimited" - - /api/v1/agents/{namespace}/{slug}/copy: - post: - operationId: recordAgentCopy - summary: Record a copy event for an agent (fire-and-forget) - tags: - - agents - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "204": - description: Copy recorded - "404": - $ref: "#/components/responses/NotFound" - "429": - $ref: "#/components/responses/RateLimited" - - /api/v1/agents/{namespace}/{slug}/activity: - get: - operationId: listAgentActivity - summary: Public activity feed for an agent - description: > - Returns a chronological feed of lifecycle events for the given - agent (creation, publish, deprecation, visibility changes, etc.). - Actor identity is scrubbed — only a coarse role label is exposed. - Public, rate-limited. - tags: - - agents - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/LimitParam" - - $ref: "#/components/parameters/CursorParam" - responses: - "200": - description: Paginated list of public activity events - content: - application/json: - schema: - $ref: "#/components/schemas/PublicActivityEventList" - "404": - $ref: "#/components/responses/NotFound" - "429": - $ref: "#/components/responses/RateLimited" - - /api/v1/agents/{namespace}/{slug}/versions: - get: - operationId: listAgentVersions - summary: List versions of an agent - tags: - - agents - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "200": - description: List of versions - content: - application/json: - schema: - $ref: "#/components/schemas/AgentVersionList" - "404": - $ref: "#/components/responses/NotFound" - "429": - $ref: "#/components/responses/RateLimited" - post: - operationId: createAgentVersion - summary: Create a new version of an agent (admin only) - tags: - - agents - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/CreateAgentVersionRequest" - responses: - "201": - description: Version created - content: - application/json: - schema: - $ref: "#/components/schemas/AgentVersion" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - $ref: "#/components/responses/Conflict" - "422": - $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}/versions/{version}: - get: - operationId: getAgentVersion - summary: Get a specific version of an agent - tags: - - agents - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/VersionParam" - responses: - "200": - description: Version detail - content: - application/json: - schema: - $ref: "#/components/schemas/AgentVersion" - "404": - $ref: "#/components/responses/NotFound" - "429": - $ref: "#/components/responses/RateLimited" - - # ── Agent change-approval workflow ──────────────────────────────────────── - - /api/v1/agents/{namespace}/{slug}/versions/{version}/submit: - post: - operationId: submitAgentVersion - summary: Submit an agent version for review - description: > - The optional body carries the author's release intent: with - `request_public: true`, approving this submission also flips the - owning entry's visibility to public (atomically with the approval). - Withdrawing the submission drops the request; a resubmission states - it afresh. - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/VersionParam" - requestBody: - required: false - content: - application/json: - schema: - $ref: "#/components/schemas/SubmitVersionRequest" - responses: - "204": - description: submitted - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: review-state-mismatch | review-already-pending - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - - /api/v1/agents/{namespace}/{slug}/versions/{version}/withdraw: - post: - operationId: withdrawAgentVersion - summary: Withdraw a pending agent version back to draft - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/VersionParam" - responses: - "204": - description: withdrawn - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: review-state-mismatch (version is not in pending_review) - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - - /api/v1/agents/{namespace}/{slug}/versions/{version}/approve: - post: - operationId: approveAgentVersion - summary: Approve a pending agent version (reviewer) - description: > - Publishes the version. When the submission carried - `request_public: true`, the owning entry's visibility flips to - public in the same transaction. - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/VersionParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/ApproveRequest" - responses: - "204": - description: approved - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/ReviewForbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: review-state-mismatch | review-revision-mismatch | already-published - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - "422": - $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}/versions/{version}/reject: - post: - operationId: rejectAgentVersion - summary: Reject a pending agent version with a reason (reviewer) - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/VersionParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/RejectRequest" - responses: - "204": - description: rejected - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: review-state-mismatch | review-revision-mismatch - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - "422": - $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}/deletion-request: - post: - operationId: requestAgentDeletion - summary: Request deletion of an agent - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "202": - description: deletion request recorded - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: another deletion request is already pending - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - - /api/v1/agents/{namespace}/{slug}/deletion-request/approve: - post: - operationId: approveAgentDeletion - summary: Approve a pending agent deletion (reviewer) - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "204": - description: deleted (soft-delete) - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/ReviewForbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: no pending deletion request - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - - /api/v1/agents/{namespace}/{slug}/deletion-request/reject: - post: - operationId: rejectAgentDeletion - summary: Reject a pending agent deletion with a reason (reviewer) - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/RejectDeletionRequest" - responses: - "204": - description: rejected - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: no pending deletion request - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - "422": - $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}/change-request/approve: - post: - operationId: approveAgentChange - summary: Approve a pending agent entry change (reviewer) - description: > - Applies the pending entry-change request (visibility / deprecation / undeprecation / - metadata edit) on the agent. Requires the Reviewer role on the owning - publisher. - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/ApproveEntryChangeRequest" - responses: - "204": - description: change applied - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/ReviewForbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: no pending change, stale revision, or change no longer applicable - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - "422": - $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}/change-request/reject: - post: - operationId: rejectAgentChange - summary: Reject a pending agent entry change with a reason (reviewer) - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/RejectEntryChangeRequest" - responses: - "204": - description: change rejected - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: no pending change to reject, or stale revision - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - "422": - $ref: "#/components/responses/ValidationError" - - /api/v1/agents/{namespace}/{slug}/change-request/withdraw: - post: - operationId: withdrawAgentChange - summary: Withdraw the agent's pending change (Editor) - tags: - - agents - - review - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "204": - description: change withdrawn - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - description: no pending change to withdraw - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ReviewProblem" - - /api/v1/agents/{namespace}/{slug}/versions/{version}/publish: - post: - operationId: publishAgentVersion - summary: Publish an agent version (Reviewer) - description: > - Transitions the version from draft to published. Publishing takes a - version live, so it is an approver action: requires the Reviewer role - (Server Admin is the break-glass exception). Editors publish by - submitting for a Reviewer to approve. Published versions are immutable. - tags: - - agents - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/VersionParam" - responses: - "200": - description: Version published - content: - application/json: - schema: - type: object - properties: - status: - type: string - example: published - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "409": - $ref: "#/components/responses/Conflict" - - /api/v1/agents/{namespace}/{slug}/versions/{version}/status: - patch: - operationId: patchAgentVersionStatus - summary: Update agent version lifecycle status (admin only) - tags: - - agents - security: - - bearerAuth: [] - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - - $ref: "#/components/parameters/VersionParam" - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/PatchVersionStatusRequest" - responses: - "200": - description: Status updated; returns the updated version - content: - application/json: - schema: - $ref: "#/components/schemas/AgentVersion" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "422": - $ref: "#/components/responses/ValidationError" - - # ── Per-agent A2A card ──────────────────────────────────────────────────── - - /agents/{namespace}/{slug}/.well-known/agent-card.json: - get: - operationId: getAgentCard - summary: A2A Agent Card - description: Returns the Google A2A-compatible Agent Card for the given agent. - tags: - - agents - parameters: - - $ref: "#/components/parameters/NamespaceParam" - - $ref: "#/components/parameters/SlugParam" - responses: - "200": - description: A2A Agent Card - content: - application/json: - schema: - type: object - "404": - $ref: "#/components/responses/NotFound" - - # ── Stats & Audit ───────────────────────────────────────────────────────── - - /api/v1/public-stats: - get: - operationId: getPublicStats - summary: Public registry statistics (published entries only) - tags: - - system - responses: - "200": - description: Public counts for each resource type - content: - application/json: - schema: - $ref: "#/components/schemas/PublicStats" - "429": - $ref: "#/components/responses/RateLimited" - - /api/v1/changelog: - get: - operationId: getChangelog - summary: Recently published versions across MCP servers and agents - description: > - Aggregated timeline of version publications, newest first. Only - published versions of public, non-deleted entries are returned. - tags: - - system - parameters: - - name: limit - in: query - schema: - type: integer - minimum: 1 - maximum: 200 - default: 50 - responses: - "200": - description: Recent version publications across the registry - content: - application/json: - schema: - $ref: "#/components/schemas/ChangelogList" - "429": - $ref: "#/components/responses/RateLimited" - - /api/v1/stats: - get: - operationId: getStats - summary: Registry resource counts (admin only) - tags: - - system - security: - - bearerAuth: [] - responses: - "200": - description: Total counts for each resource type - content: - application/json: - schema: - $ref: "#/components/schemas/RegistryCounts" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - - /api/v1/audit: - get: - operationId: listAuditEvents - summary: List audit log events (admin only) - tags: - - audit - security: - - bearerAuth: [] - parameters: - - name: resource_type - in: query - description: Filter by resource type (mcp_server, agent, publisher) - schema: - type: string - - name: resource_id - in: query - description: Filter by resource ULID - schema: - type: string - - name: actor - in: query - description: Filter by Keycloak subject UUID - schema: - type: string - - $ref: "#/components/parameters/LimitParam" - - $ref: "#/components/parameters/CursorParam" - responses: - "200": - description: Paginated list of audit events - content: - application/json: - schema: - $ref: "#/components/schemas/AuditEventList" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - - /api/v1/reports: - post: - operationId: createReport - summary: File a community issue report - description: > - Public, rate-limited endpoint for anyone to report problems with a - registry entry (broken packaging, misleading description, spam, - security concern, etc.). Admins triage reports via the admin queue. - tags: - - reports - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/CreateReportRequest" - responses: - "201": - description: Report accepted - content: - application/json: - schema: - $ref: "#/components/schemas/Report" - "422": - $ref: "#/components/responses/ValidationError" - "429": - $ref: "#/components/responses/RateLimited" - get: - operationId: listReports - summary: List community issue reports (admin only) - tags: - - reports - security: - - bearerAuth: [] - parameters: - - name: status - in: query - description: Filter by status - schema: - type: string - enum: - - pending - - reviewed - - dismissed - - name: limit - in: query - schema: - type: integer - minimum: 1 - maximum: 200 - default: 50 - responses: - "200": - description: List of reports - content: - application/json: - schema: - $ref: "#/components/schemas/ReportList" - "401": - $ref: "#/components/responses/Unauthorized" - "403": - $ref: "#/components/responses/Forbidden" - - /api/v1/reports/{id}: - patch: - operationId: updateReportStatus - summary: Update a report's status (admin only) - tags: - - reports - security: - - bearerAuth: [] - parameters: - - name: id - in: path - required: true - schema: - type: string - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/UpdateReportStatusRequest" - responses: - "200": - description: Updated - content: - application/json: - schema: - type: object - properties: - status: - type: string - enum: - - pending - - reviewed - - dismissed + type: object + properties: + status: + type: string + enum: + - pending + - reviewed + - dismissed "401": $ref: "#/components/responses/Unauthorized" "403": @@ -3996,19 +3049,14 @@ components: type: object required: - mcp_servers - - agents - publishers properties: mcp_servers: type: integer - agents: - type: integer publishers: type: integer mcp_status_breakdown: $ref: "#/components/schemas/StatusBreakdown" - agent_status_breakdown: - $ref: "#/components/schemas/StatusBreakdown" MemberRoles: type: object @@ -4038,14 +3086,11 @@ components: soft-deleted entries; breakdowns cover the three live statuses. required: - mcp_servers - - agents - members - pending_review properties: mcp_servers: type: integer - agents: - type: integer members: type: integer description: Distinct principals holding a grant scoped to this publisher. @@ -4054,8 +3099,6 @@ components: description: Items awaiting an approver (submitted versions + requested deletions). mcp_status_breakdown: $ref: "#/components/schemas/StatusBreakdown" - agent_status_breakdown: - $ref: "#/components/schemas/StatusBreakdown" member_roles: $ref: "#/components/schemas/MemberRoles" @@ -4063,27 +3106,19 @@ components: type: object required: - mcp_servers - - agents - publishers - new_mcp_servers_this_week - - new_agents_this_week - new_publishers_this_week properties: mcp_servers: type: integer description: Total public published MCP servers - agents: - type: integer - description: Total public published agents publishers: type: integer description: Total publishers with at least one public entry new_mcp_servers_this_week: type: integer description: MCP servers published in the last 7 days - new_agents_this_week: - type: integer - description: Agents published in the last 7 days new_publishers_this_week: type: integer description: Publishers with at least one public entry that were created in the last 7 days @@ -4211,431 +3246,134 @@ components: minimum: 1 description: | Optimistic-concurrency token from the queue item; the approve fails - with 409 review-revision-mismatch if it no longer matches. - - RejectEntryChangeRequest: - type: object - required: - - revision - - reason - properties: - revision: - type: integer - minimum: 1 - reason: - type: string - minLength: 1 - description: Free-text reason, captured in the audit log. - - EntryChangeAccepted: - type: object - required: - - status - - change_id - properties: - status: - type: string - enum: - - pending_review - change_id: - type: string - description: ULID of the created entry-change request. - - PendingEntryChange: - type: object - required: - - change_id - - action - - revision - - submitted_at - description: | - Summary of an entry's single pending change, attached to the detail - response for callers who can view private detail. - properties: - change_id: - type: string - action: - type: string - enum: - - visibility - - deprecation - - undeprecation - - metadata_edit - revision: - type: integer - submitted_at: - type: string - format: date-time - submitted_by_email: - type: string - payload: - type: object - additionalProperties: true - - ReviewQueueItem: - type: object - required: - - kind - - publisher_slug - - entry_slug - - entry_id - - submitted_at - properties: - kind: - type: string - enum: - - mcp_version - - agent_version - - mcp_deletion - - agent_deletion - - mcp_change - - agent_change - publisher_slug: - type: string - entry_slug: - type: string - entry_id: - type: string - description: ULID of the entry - version: - type: string - description: | - Present on `*_version` items, absent on `*_deletion` / `*_change` items. - revision: - type: integer - description: | - Present on `*_version` and `*_change` items (the optimistic- - concurrency token passed back on approve/reject). - request_public: - type: boolean - description: | - Present on `*_version` items only — the author asked for the - entry to be made public when this submission is approved. - submitted_at: - type: string - format: date-time - submitted_by: - type: string - description: JWT subject of the submitter (UUID). - submitted_by_email: - type: string - description: Email captured at submission time. - change_id: - type: string - description: | - Present on `*_change` items only — the entry-change-request ULID. - action: - type: string - enum: - - visibility - - deprecation - - undeprecation - - metadata_edit - description: | - Present on `*_change` items only — the entry-level mutation the - request will apply on approval. - payload: - type: object - additionalProperties: true - description: | - Present on `*_change` items only — the proposed mutation (e.g. the - new visibility, or the edited metadata fields) for diff display. - - ReviewQueueList: - type: object - required: - - items - properties: - items: - type: array - items: - $ref: "#/components/schemas/ReviewQueueItem" - next_cursor: - type: string - - ReviewProblem: - description: | - RFC 7807 problem detail returned by the change-approval - workflow. Inspect `type` to discriminate the case: - .../errors/self-approval-forbidden (403) - .../errors/not-found (404) - .../errors/review-state-mismatch (409) - .../errors/review-revision-mismatch (409) - .../errors/review-already-pending (409) - .../errors/already-published (409) - .../errors/change-already-pending (409) - .../errors/change-not-applicable (409) - type: object - required: - - type - - title - - status - properties: - type: - type: string - format: uri - title: - type: string - status: - type: integer - detail: - type: string - instance: - type: string - - # ── MCP Servers ───────────────────────────────────────────────────────── - - PackageTransport: - type: object - required: - - type - properties: - type: - type: string - enum: - - stdio - - http - - sse - - streamable_http - url: - type: string - - PackageEntry: - type: object - required: - - registryType - - identifier - - version - - transport - properties: - registryType: - type: string - registryBaseUrl: - type: string - identifier: - type: string - version: - type: string - transport: - $ref: "#/components/schemas/PackageTransport" - - RemoteEntry: - type: object - description: > - A directly reachable endpoint for a hosted (remote) MCP server, - mirroring the `remotes` array of the MCP registry server.json. Unlike - a package there is no installable artifact — clients connect straight - to the URL using the given transport. - required: - - type - - url - properties: - type: - type: string - enum: - - http - - sse - - streamable_http - url: - type: string - format: uri - - MCPTool: - type: object - description: > - Publisher-declared tool exposed by an MCP server. This is a registry - extension — the MCP spec itself returns the live tool list at runtime - via the `tools/list` method. Storing the declared list here lets the - UI show tool counts and descriptions without connecting to a running - server. Structural requirements: `name` is required and unique within - the enclosing array; `input_schema`, if present, must be a JSON - Schema object. + with 409 review-revision-mismatch if it no longer matches. + + RejectEntryChangeRequest: + type: object required: - - name + - revision + - reason properties: - name: - type: string - description: Unique tool name within the server - description: + revision: + type: integer + minimum: 1 + reason: type: string - description: Human-readable tool description - input_schema: - type: object - additionalProperties: true - description: JSON Schema describing the tool's input arguments - annotations: - type: object - additionalProperties: true - description: MCP spec tool annotations (e.g. destructive, idempotent) + minLength: 1 + description: Free-text reason, captured in the audit log. - CreateMCPToolDiscoveryRequest: + EntryChangeAccepted: type: object required: - - namespace - - url - - transport + - status + - change_id properties: - namespace: - type: string - description: Publisher the discovery is made for; the caller needs Editor on it. - url: - type: string - format: uri - maxLength: 2048 - description: The remote URL as declared on the version. - transport: + status: type: string enum: - - http - - sse - - streamable_http - description: The declared transport, the only one used. `http` means `streamable_http`. + - pending_review + change_id: + type: string + description: ULID of the created entry-change request. - MCPToolDiscoveryAttempt: + PendingEntryChange: type: object required: - - url - - transport - - status + - change_id + - action + - revision + - submitted_at + description: | + Summary of an entry's single pending change, attached to the detail + response for callers who can view private detail. properties: - url: + change_id: type: string - format: uri - transport: + action: type: string enum: - - sse - - streamable_http - status: + - visibility + - deprecation + - undeprecation + - metadata_edit + revision: type: integer - description: HTTP status of the first response, 0 when none arrived. - error: + submitted_at: type: string - description: > - Why the attempt failed, with the underlying cause (an HTTP status, - a TLS or DNS error, the MCP handshake error); absent on the attempt - that succeeded. - - MCPToolDiscoveryProblem: - description: > - A failed tool discovery. `detail` names the cause of each failed - attempt; `attempts` lists them, in order, when any connection was tried. - allOf: - - $ref: "#/components/schemas/Problem" - - type: object - properties: - attempts: - type: array - items: - $ref: "#/components/schemas/MCPToolDiscoveryAttempt" - - MCPToolDiscovery: - type: object - required: - - endpoint - - attempts - - protocol_version - - supported_protocol_versions - - tools - properties: - endpoint: - type: object - description: The endpoint that answered, the declared URL without its fragment. - required: - - url - - transport - properties: - url: - type: string - format: uri - transport: - type: string - enum: - - sse - - streamable_http - attempts: - type: array - description: The single attempt made against the declared endpoint. - items: - $ref: "#/components/schemas/MCPToolDiscoveryAttempt" - server_info: - type: object - required: - - name - properties: - name: - type: string - version: - type: string - protocol_version: + format: date-time + submitted_by_email: type: string - description: The revision negotiated by the discovery handshake. - supported_protocol_versions: - type: array - description: > - Revisions (YYYY-MM-DD) the server accepted when offered one at a - time, newest first. Empty when every probe failed. - items: - type: string - format: date - tools: - type: array - items: - $ref: "#/components/schemas/MCPTool" + payload: + type: object + additionalProperties: true - InstanceTag: + ReviewQueueItem: type: object required: - - slug - - name - - active - - created_at - - updated_at + - kind + - publisher_slug + - entry_slug + - entry_id + - submitted_at properties: - slug: + kind: type: string - description: > - Immutable identifier, referenced by version `tags` arrays - (lowercase letters, digits, and hyphens). - name: + enum: + - mcp_version + - mcp_deletion + - mcp_change + publisher_slug: type: string - description: Display name (e.g. "Early Access") - description: + entry_slug: type: string - color: + entry_id: type: string - description: UI badge color hint - enum: - - gray - - red - - orange - - yellow - - green - - teal - - blue - - indigo - - purple - - pink - active: - type: boolean - description: > - Deactivated tags cannot be ticked on new versions but remain - visible on versions that already carry them. - managed: + description: ULID of the entry + version: + type: string + description: | + Present on `*_version` items, absent on `*_deletion` / `*_change` items. + revision: + type: integer + description: | + Present on `*_version` and `*_change` items (the optimistic- + concurrency token passed back on approve/reject). + request_public: type: boolean - description: > - True when the tag is reconciled from the server configuration - (`INSTANCE_TAGS` env / `instance_tags` config key) at startup. - Managed tags are read-only via the API — PATCH and DELETE answer - 409; change the configuration instead. - created_at: + description: | + Present on `*_version` items only — the author asked for the + entry to be made public when this submission is approved. + submitted_at: type: string format: date-time - updated_at: + submitted_by: type: string - format: date-time + description: JWT subject of the submitter (UUID). + submitted_by_email: + type: string + description: Email captured at submission time. + change_id: + type: string + description: | + Present on `*_change` items only — the entry-change-request ULID. + action: + type: string + enum: + - visibility + - deprecation + - undeprecation + - metadata_edit + description: | + Present on `*_change` items only — the entry-level mutation the + request will apply on approval. + payload: + type: object + additionalProperties: true + description: | + Present on `*_change` items only — the proposed mutation (e.g. the + new visibility, or the edited metadata fields) for diff display. - InstanceTagList: + ReviewQueueList: type: object required: - items @@ -4643,382 +3381,354 @@ components: items: type: array items: - $ref: "#/components/schemas/InstanceTag" + $ref: "#/components/schemas/ReviewQueueItem" + next_cursor: + type: string - CreateInstanceTagRequest: + ReviewProblem: + description: | + RFC 7807 problem detail returned by the change-approval + workflow. Inspect `type` to discriminate the case: + .../errors/self-approval-forbidden (403) + .../errors/not-found (404) + .../errors/review-state-mismatch (409) + .../errors/review-revision-mismatch (409) + .../errors/review-already-pending (409) + .../errors/already-published (409) + .../errors/change-already-pending (409) + .../errors/change-not-applicable (409) type: object required: - - slug - - name + - type + - title + - status properties: - slug: + type: type: string - pattern: "^[a-z0-9-]+$" - name: + format: uri + title: type: string - description: + status: + type: integer + detail: type: string - color: + instance: type: string - enum: - - gray - - red - - orange - - yellow - - green - - teal - - blue - - indigo - - purple - - pink - default: gray - UpdateInstanceTagRequest: + # ── MCP Servers ───────────────────────────────────────────────────────── + + PackageTransport: type: object + required: + - type properties: - name: - type: string - description: - type: string - color: + type: type: string enum: - - gray - - red - - orange - - yellow - - green - - teal - - blue - - indigo - - purple - - pink - active: - type: boolean + - stdio + - http + - sse + - streamable_http + url: + type: string - MCPServerLatestVersion: + PackageEntry: type: object required: + - registryType + - identifier - version - - runtime - - protocol_versions + - transport properties: + registryType: + type: string + registryBaseUrl: + type: string + identifier: + type: string version: type: string - runtime: + transport: + $ref: "#/components/schemas/PackageTransport" + + RemoteEntry: + type: object + description: > + A directly reachable endpoint for a hosted (remote) MCP server, + mirroring the `remotes` array of the MCP registry server.json. Unlike + a package there is no installable artifact — clients connect straight + to the URL using the given transport. + required: + - type + - url + properties: + type: type: string enum: - - stdio - http - sse - streamable_http - protocol_versions: - type: array - description: MCP protocol revisions (YYYY-MM-DD) the server supports, newest first. - minItems: 1 - uniqueItems: true - items: - type: string - format: date - packages: - type: array - items: - $ref: "#/components/schemas/PackageEntry" - remotes: - type: array - description: Remote endpoints for hosted deployments of this server. - items: - $ref: "#/components/schemas/RemoteEntry" - capabilities: - type: object - additionalProperties: true - description: > - MCP capability-negotiation object (e.g. `{tools:{listChanged:true}}`). - NOT a list of tools — see the `tools` field for that. - tools: - type: array - description: Publisher-declared list of tools this server exposes. - items: - $ref: "#/components/schemas/MCPTool" - tags: - type: array - description: Instance-tag slugs ticked on this version. - items: - type: string - published_at: + url: type: string - format: date-time + format: uri - MCPServer: + MCPTool: type: object + description: > + Publisher-declared tool exposed by an MCP server. This is a registry + extension — the MCP spec itself returns the live tool list at runtime + via the `tools/list` method. Storing the declared list here lets the + UI show tool counts and descriptions without connecting to a running + server. Structural requirements: `name` is required and unique within + the enclosing array; `input_schema`, if present, must be a JSON + Schema object. required: - - id - - namespace - - slug - name - - visibility - - status - - created_at - - updated_at properties: - id: - type: string - namespace: - type: string - slug: - type: string name: type: string + description: Unique tool name within the server description: type: string - pending_change: - $ref: "#/components/schemas/PendingEntryChange" - homepage_url: - type: string - repo_url: - type: string - license: - type: string - visibility: - type: string - enum: - - private - - public - status: - type: string - # MCPServer.status mirrors the lifecycle column on the row: - # `draft` (never published), `published` (at least one version - # active), `deprecated` (all versions superseded), or `deleted` - # (soft-deleted tombstone). Public list responses exclude - # `deleted`; admin reads and detail by namespace/slug can - # still surface a deleted parent. - enum: - - draft - - published - - deprecated - - deleted - created_at: - type: string - format: date-time - updated_at: - type: string - format: date-time - featured: - type: boolean - default: false - verified: - type: boolean - default: false - tags: - type: array - description: > - Instance-tag slugs of the latest published version (tags are - ticked per version from the Server-Admin-curated vocabulary; - see GET /api/v1/tags). Empty until a version is published. - items: - type: string - readme: - type: string - description: Long-form README content (Markdown) - usage_markdown: - type: string - description: > - Publisher-written Markdown shown on the Usage tab in place of the - generated usage instructions; empty means none. At most 20000 - characters. Clients substitute these placeholders when rendering: - `{{name}}`, `{{namespace}}`, `{{slug}}`, `{{version}}` (latest - published version), `{{run_command}}` (run command of the first - local package) and `{{endpoint_url}}` (URL of the first remote - endpoint). Unknown placeholders are left as written. - view_count: - type: integer - description: Number of times this server has been viewed - copy_count: - type: integer - description: Number of times this server's config has been copied - latest_version: - $ref: "#/components/schemas/MCPServerLatestVersion" + description: Human-readable tool description + input_schema: + type: object + additionalProperties: true + description: JSON Schema describing the tool's input arguments + annotations: + type: object + additionalProperties: true + description: MCP spec tool annotations (e.g. destructive, idempotent) - CreateMCPServerRequest: + CreateMCPToolDiscoveryRequest: type: object required: - namespace - - slug - - name + - url + - transport properties: namespace: type: string - slug: - type: string - pattern: "^[a-z0-9-]+$" - name: - type: string - description: - type: string - homepage_url: - type: string - format: uri - maxLength: 2048 - description: Absolute http(s) URL; other schemes are rejected. - repo_url: + description: Publisher the discovery is made for; the caller needs Editor on it. + url: type: string format: uri maxLength: 2048 - description: Absolute http(s) URL; other schemes are rejected. - license: + description: The remote URL as declared on the version. + transport: type: string + enum: + - http + - sse + - streamable_http + description: The declared transport, the only one used. `http` means `streamable_http`. - MCPServerList: + MCPToolDiscoveryAttempt: type: object required: - - items + - url + - transport + - status properties: - items: - type: array - items: - $ref: "#/components/schemas/MCPServer" - next_cursor: + url: type: string - total_count: + format: uri + transport: + type: string + enum: + - sse + - streamable_http + status: type: integer + description: HTTP status of the first response, 0 when none arrived. + error: + type: string + description: > + Why the attempt failed, with the underlying cause (an HTTP status, + a TLS or DNS error, the MCP handshake error); absent on the attempt + that succeeded. - MCPServerVersion: + MCPToolDiscoveryProblem: + description: > + A failed tool discovery. `detail` names the cause of each failed + attempt; `attempts` lists them, in order, when any connection was tried. + allOf: + - $ref: "#/components/schemas/Problem" + - type: object + properties: + attempts: + type: array + items: + $ref: "#/components/schemas/MCPToolDiscoveryAttempt" + + MCPToolDiscovery: type: object required: - - id - - version - - runtime - - protocol_versions - - status - - created_at - - updated_at + - endpoint + - attempts + - protocol_version + - supported_protocol_versions + - tools properties: - id: - type: string - description: ULID - version: - type: string - description: Semver string (e.g. 1.2.3) - runtime: + endpoint: + type: object + description: The endpoint that answered, the declared URL without its fragment. + required: + - url + - transport + properties: + url: + type: string + format: uri + transport: + type: string + enum: + - sse + - streamable_http + attempts: + type: array + description: The single attempt made against the declared endpoint. + items: + $ref: "#/components/schemas/MCPToolDiscoveryAttempt" + server_info: + type: object + required: + - name + properties: + name: + type: string + version: + type: string + protocol_version: type: string - enum: - - stdio - - http - - sse - - streamable_http - protocol_versions: + description: The revision negotiated by the discovery handshake. + supported_protocol_versions: type: array - description: MCP protocol revisions (YYYY-MM-DD) the server supports, newest first. - minItems: 1 - uniqueItems: true + description: > + Revisions (YYYY-MM-DD) the server accepted when offered one at a + time, newest first. Empty when every probe failed. items: type: string format: date - packages: - type: array - items: - $ref: "#/components/schemas/PackageEntry" - remotes: - type: array - description: Remote endpoints for hosted deployments of this server. - items: - $ref: "#/components/schemas/RemoteEntry" - capabilities: - type: object - additionalProperties: true tools: type: array - description: Publisher-declared list of tools this server exposes. items: $ref: "#/components/schemas/MCPTool" - tags: - type: array + + InstanceTag: + type: object + required: + - slug + - name + - active + - created_at + - updated_at + properties: + slug: + type: string description: > - Instance-tag slugs ticked on this version (immutable once - published). Resolve display name/color via GET /api/v1/tags. - items: - type: string - checksum: + Immutable identifier, referenced by version `tags` arrays + (lowercase letters, digits, and hyphens). + name: type: string - signature: + description: Display name (e.g. "Early Access") + description: type: string - status: + color: type: string - # MCPServerVersion lifecycle is orthogonal to MCPServer.status: - # a version becomes `active` when published, `deprecated` when - # superseded, or `deleted` when withdrawn. Draft / pending / - # rejected states live on `review_state`, not here. + description: UI badge color hint enum: - - active - - deprecated - - deleted - published_at: + - gray + - red + - orange + - yellow + - green + - teal + - blue + - indigo + - purple + - pink + active: + type: boolean + description: > + Deactivated tags cannot be ticked on new versions but remain + visible on versions that already carry them. + managed: + type: boolean + description: > + True when the tag is reconciled from the server configuration + (`INSTANCE_TAGS` env / `instance_tags` config key) at startup. + Managed tags are read-only via the API — PATCH and DELETE answer + 409; change the configuration instead. + created_at: type: string format: date-time - review_state: - type: string - enum: - - none - - pending_review - - rejected - description: | - Change-approval workflow state, orthogonal to `status` and - `published_at`. Omitted on rows that have never been part of - the workflow (review_state='none' before any submit). - revision: - type: integer - minimum: 1 - description: | - Revision counter the reviewer must echo back when calling - approve/reject; bumps on every content edit. - submitted_at: + updated_at: type: string format: date-time - submitted_by: - type: string - description: JWT subject (UUID) of the submitter. - submitted_by_email: - type: string - description: Email captured at submission time. - reviewed_at: + + InstanceTagList: + type: object + required: + - items + properties: + items: + type: array + items: + $ref: "#/components/schemas/InstanceTag" + + CreateInstanceTagRequest: + type: object + required: + - slug + - name + properties: + slug: type: string - format: date-time - reviewed_by: + pattern: "^[a-z0-9-]+$" + name: type: string - reviewed_by_email: + description: type: string - review_decision: + color: type: string enum: - - approved - - rejected - rejection_reason: - type: string - description: Free-text reason persisted on the rejected version row. - request_public: - type: boolean - description: > - Author's release intent for the in-flight submission — approval - also makes the owning entry public. Set on submit, cleared on - withdraw. - created_at: - type: string - format: date-time - updated_at: - type: string - format: date-time + - gray + - red + - orange + - yellow + - green + - teal + - blue + - indigo + - purple + - pink + default: gray - MCPServerVersionList: + UpdateInstanceTagRequest: type: object - required: - - items properties: - items: - type: array - items: - $ref: "#/components/schemas/MCPServerVersion" + name: + type: string + description: + type: string + color: + type: string + enum: + - gray + - red + - orange + - yellow + - green + - teal + - blue + - indigo + - purple + - pink + active: + type: boolean - CreateMCPServerVersionRequest: + MCPServerLatestVersion: type: object required: - version @@ -5027,7 +3737,6 @@ components: properties: version: type: string - description: Semver string (e.g. 1.2.3) runtime: type: string enum: @@ -5055,77 +3764,14 @@ components: capabilities: type: object additionalProperties: true + description: > + MCP capability-negotiation object (e.g. `{tools:{listChanged:true}}`). + NOT a list of tools — see the `tools` field for that. tools: type: array description: Publisher-declared list of tools this server exposes. items: $ref: "#/components/schemas/MCPTool" - checksum: - type: string - signature: - type: string - tags: - type: array - description: > - Instance-tag slugs to tick on this version. Each must be an - active tag from GET /api/v1/tags (422 otherwise). Frozen with - the version at publish. - items: - type: string - - # ── Agents ────────────────────────────────────────────────────────────── - - AgentSkill: - type: object - required: - - id - - name - - description - - tags - properties: - id: - type: string - name: - type: string - description: - type: string - tags: - type: array - items: - type: string - examples: - type: array - items: - type: string - - AgentLatestVersion: - type: object - required: - - version - - endpoint_url - properties: - version: - type: string - endpoint_url: - type: string - skills: - type: array - items: - $ref: "#/components/schemas/AgentSkill" - default_input_modes: - type: array - items: - type: string - default_output_modes: - type: array - items: - type: string - authentication: - type: array - items: - type: object - protocol_version: - type: string tags: type: array description: Instance-tag slugs ticked on this version. @@ -5135,7 +3781,7 @@ components: type: string format: date-time - Agent: + MCPServer: type: object required: - id @@ -5159,6 +3805,12 @@ components: type: string pending_change: $ref: "#/components/schemas/PendingEntryChange" + homepage_url: + type: string + repo_url: + type: string + license: + type: string visibility: type: string enum: @@ -5166,7 +3818,7 @@ components: - public status: type: string - # Agent.status mirrors the lifecycle column on the row: + # MCPServer.status mirrors the lifecycle column on the row: # `draft` (never published), `published` (at least one version # active), `deprecated` (all versions superseded), or `deleted` # (soft-deleted tombstone). Public list responses exclude @@ -5200,16 +3852,26 @@ components: readme: type: string description: Long-form README content (Markdown) + usage_markdown: + type: string + description: > + Publisher-written Markdown shown on the Usage tab in place of the + generated usage instructions; empty means none. At most 20000 + characters. Clients substitute these placeholders when rendering: + `{{name}}`, `{{namespace}}`, `{{slug}}`, `{{version}}` (latest + published version), `{{run_command}}` (run command of the first + local package) and `{{endpoint_url}}` (URL of the first remote + endpoint). Unknown placeholders are left as written. view_count: type: integer - description: Number of times this agent has been viewed + description: Number of times this server has been viewed copy_count: type: integer - description: Number of times this agent's config has been copied + description: Number of times this server's config has been copied latest_version: - $ref: "#/components/schemas/AgentLatestVersion" + $ref: "#/components/schemas/MCPServerLatestVersion" - CreateAgentRequest: + CreateMCPServerRequest: type: object required: - namespace @@ -5225,8 +3887,20 @@ components: type: string description: type: string + homepage_url: + type: string + format: uri + maxLength: 2048 + description: Absolute http(s) URL; other schemes are rejected. + repo_url: + type: string + format: uri + maxLength: 2048 + description: Absolute http(s) URL; other schemes are rejected. + license: + type: string - AgentList: + MCPServerList: type: object required: - items @@ -5234,18 +3908,19 @@ components: items: type: array items: - $ref: "#/components/schemas/Agent" + $ref: "#/components/schemas/MCPServer" next_cursor: type: string total_count: type: integer - AgentVersion: + MCPServerVersion: type: object required: - id - version - - endpoint_url + - runtime + - protocol_versions - status - created_at - updated_at @@ -5255,36 +3930,39 @@ components: description: ULID version: type: string - endpoint_url: + description: Semver string (e.g. 1.2.3) + runtime: type: string - skills: - type: array - items: - $ref: "#/components/schemas/AgentSkill" - capabilities: - type: object - additionalProperties: true - authentication: + enum: + - stdio + - http + - sse + - streamable_http + protocol_versions: type: array + description: MCP protocol revisions (YYYY-MM-DD) the server supports, newest first. + minItems: 1 + uniqueItems: true items: - type: object - default_input_modes: + type: string + format: date + packages: type: array items: - type: string - default_output_modes: + $ref: "#/components/schemas/PackageEntry" + remotes: type: array + description: Remote endpoints for hosted deployments of this server. items: - type: string - provider: + $ref: "#/components/schemas/RemoteEntry" + capabilities: type: object additionalProperties: true - documentation_url: - type: string - icon_url: - type: string - protocol_version: - type: string + tools: + type: array + description: Publisher-declared list of tools this server exposes. + items: + $ref: "#/components/schemas/MCPTool" tags: type: array description: > @@ -5292,18 +3970,20 @@ components: published). Resolve display name/color via GET /api/v1/tags. items: type: string + checksum: + type: string + signature: + type: string status: type: string - # AgentVersion lifecycle mirrors MCPServerVersion: a version - # becomes `active` on publish, `deprecated` when superseded, - # `deleted` when withdrawn. Pre-publish / pending / rejected - # states live on `review_state`. + # MCPServerVersion lifecycle is orthogonal to MCPServer.status: + # a version becomes `active` when published, `deprecated` when + # superseded, or `deleted` when withdrawn. Draft / pending / + # rejected states live on `review_state`, not here. enum: - active - deprecated - deleted - status_message: - type: string published_at: type: string format: date-time @@ -5313,16 +3993,25 @@ components: - none - pending_review - rejected + description: | + Change-approval workflow state, orthogonal to `status` and + `published_at`. Omitted on rows that have never been part of + the workflow (review_state='none' before any submit). revision: type: integer minimum: 1 + description: | + Revision counter the reviewer must echo back when calling + approve/reject; bumps on every content edit. submitted_at: type: string format: date-time submitted_by: type: string + description: JWT subject (UUID) of the submitter. submitted_by_email: type: string + description: Email captured at submission time. reviewed_at: type: string format: date-time @@ -5337,6 +4026,7 @@ components: - rejected rejection_reason: type: string + description: Free-text reason persisted on the rejected version row. request_public: type: boolean description: > @@ -5350,7 +4040,7 @@ components: type: string format: date-time - AgentVersionList: + MCPServerVersionList: type: object required: - items @@ -5358,55 +4048,53 @@ components: items: type: array items: - $ref: "#/components/schemas/AgentVersion" + $ref: "#/components/schemas/MCPServerVersion" - CreateAgentVersionRequest: + CreateMCPServerVersionRequest: type: object required: - version - - endpoint_url + - runtime + - protocol_versions properties: version: type: string - endpoint_url: + description: Semver string (e.g. 1.2.3) + runtime: type: string - format: uri - maxLength: 2048 - description: Absolute http(s) URL; other schemes are rejected. - skills: - type: array - items: - $ref: "#/components/schemas/AgentSkill" - capabilities: - type: object - additionalProperties: true - authentication: + enum: + - stdio + - http + - sse + - streamable_http + protocol_versions: type: array + description: MCP protocol revisions (YYYY-MM-DD) the server supports, newest first. + minItems: 1 + uniqueItems: true items: - type: object - default_input_modes: + type: string + format: date + packages: type: array items: - type: string - default_output_modes: + $ref: "#/components/schemas/PackageEntry" + remotes: type: array + description: Remote endpoints for hosted deployments of this server. items: - type: string - provider: - description: A2A provider object; its `url`, when set, must be an absolute http(s) URL. + $ref: "#/components/schemas/RemoteEntry" + capabilities: type: object additionalProperties: true - documentation_url: - type: string - format: uri - maxLength: 2048 - description: Absolute http(s) URL; other schemes are rejected. - icon_url: + tools: + type: array + description: Publisher-declared list of tools this server exposes. + items: + $ref: "#/components/schemas/MCPTool" + checksum: type: string - format: uri - maxLength: 2048 - description: Absolute http(s) URL; other schemes are rejected. - protocol_version: + signature: type: string tags: type: array @@ -5417,21 +4105,6 @@ components: items: type: string - PatchVersionStatusRequest: - type: object - required: - - status - properties: - status: - type: string - enum: - - active - - deprecated - - deleted - statusMessage: - type: string - description: Required when status is deprecated or deleted; must be absent when active. - SetVisibilityRequest: type: object required: @@ -5566,7 +4239,7 @@ components: description: Normalized action key (e.g. mcp_server_version.published) resource_type: type: string - description: Either mcp_server or agent + description: Type of the affected resource (e.g. mcp_server) resource_slug: type: string description: Slug of the affected entry within the publisher @@ -5612,7 +4285,6 @@ components: type: string enum: - mcp_server - - agent namespace: type: string slug: @@ -5653,7 +4325,6 @@ components: type: string enum: - mcp_server - - agent resource_id: type: string description: ULID of the reported resource @@ -5729,7 +4400,6 @@ components: type: string enum: - mcp_server - - agent resource_id: type: string issue_type: diff --git a/server/api/spec.go b/server/api/spec.go index 860c4ead..8e32a470 100644 --- a/server/api/spec.go +++ b/server/api/spec.go @@ -1,18 +1,8 @@ -// Package api embeds the OpenAPI 3.1 specification for serving at /openapi.yaml, -// plus the pinned A2A Agent Card JSON Schema used by conformance tests. -// The canonical sources are server/api/openapi.yaml and -// server/api/a2a-agent-card.schema.json — edit those files directly. +// Package api embeds the OpenAPI 3.1 specification for serving at /openapi.yaml. +// The canonical source is server/api/openapi.yaml — edit that file directly. package api import _ "embed" //go:embed openapi.yaml var Spec []byte - -// A2AAgentCardSchema is the JSON Schema for the A2A Agent Card document shape, -// pinned to the A2A specification as of June 2025 -// (https://github.com/a2aproject/A2A). Consumed by internal/http/handlers tests to assert that every -// card the registry emits (per-agent and global) conforms to the spec. -// -//go:embed a2a-agent-card.schema.json -var A2AAgentCardSchema []byte diff --git a/server/go.mod b/server/go.mod index aadb6fbb..d94b5251 100644 --- a/server/go.mod +++ b/server/go.mod @@ -12,7 +12,6 @@ require ( github.com/modelcontextprotocol/go-sdk v1.8.0 github.com/oklog/ulid/v2 v2.1.2 github.com/prometheus/client_golang v1.24.1 - github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 github.com/testcontainers/testcontainers-go v0.44.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 diff --git a/server/go.sum b/server/go.sum index 1277ed87..fca31a70 100644 --- a/server/go.sum +++ b/server/go.sum @@ -140,8 +140,6 @@ github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0o github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 h1:lZUw3E0/J3roVtGQ+SCrUrg3ON6NgVqpn3+iol9aGu4= -github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY= github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= diff --git a/server/internal/agents/card.go b/server/internal/agents/card.go deleted file mode 100644 index 41baa656..00000000 --- a/server/internal/agents/card.go +++ /dev/null @@ -1,217 +0,0 @@ -// Package agents implements A2A Agent Card generation. -// -// Targets the A2A protocol specification as of June 2025: -// https://github.com/a2aproject/a2a (commit-stable shape at that date) -// -// AgentCard fields: -// -// name, description, version, url, provider, iconUrl, documentationUrl, -// capabilities (streaming, pushNotifications, stateTransitionHistory, extendedAgentCard), -// defaultInputModes, defaultOutputModes, -// skills[] (id, name, description, tags[], examples[], inputModes[], outputModes[]), -// securitySchemes (Bearer | ApiKey | OAuth2 | OpenIdConnect) -package agents - -import ( - "encoding/json" - "fmt" - - "github.com/haibread/ai-registry/internal/domain" - "github.com/haibread/ai-registry/internal/store" -) - -// AgentCard is the A2A-compatible agent card document. -// Ref: https://github.com/a2aproject/a2a/blob/main/docs/specification.md §2.1 -type AgentCard struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Version string `json:"version"` - URL string `json:"url"` - Provider *AgentProvider `json:"provider,omitempty"` - IconURL string `json:"iconUrl,omitempty"` - DocumentationURL string `json:"documentationUrl,omitempty"` - Capabilities AgentCapabilities `json:"capabilities"` - DefaultInputModes []string `json:"defaultInputModes"` - DefaultOutputModes []string `json:"defaultOutputModes"` - Skills []AgentSkill `json:"skills"` - SecuritySchemes map[string]any `json:"securitySchemes,omitempty"` -} - -// AgentProvider describes the organisation that owns the agent. -type AgentProvider struct { - Organization string `json:"organization"` - URL string `json:"url,omitempty"` -} - -// AgentCapabilities lists the optional A2A features the agent supports. -type AgentCapabilities struct { - Streaming bool `json:"streaming,omitempty"` - PushNotifications bool `json:"pushNotifications,omitempty"` - StateTransitionHistory bool `json:"stateTransitionHistory,omitempty"` - ExtendedAgentCard bool `json:"extendedAgentCard,omitempty"` -} - -// AgentSkill is one skill entry in the A2A AgentCard skills array. -type AgentSkill struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Tags []string `json:"tags"` - Examples []string `json:"examples,omitempty"` - InputModes []string `json:"inputModes,omitempty"` - OutputModes []string `json:"outputModes,omitempty"` -} - -// GenerateCard produces an A2A-compatible AgentCard from an AgentRow and its -// latest published AgentVersion. Returns an error if the version's stored JSON -// fields cannot be decoded. -func GenerateCard(agent store.AgentRow, ver *domain.AgentVersion) (*AgentCard, error) { - if ver == nil { - return nil, fmt.Errorf("agent %s/%s has no published version", agent.Namespace, agent.Slug) - } - - // Decode skills. - var skills []AgentSkill - if err := json.Unmarshal(ver.Skills, &skills); err != nil { - return nil, fmt.Errorf("decoding skills: %w", err) - } - if skills == nil { - skills = []AgentSkill{} - } - - // Decode capabilities. - var caps AgentCapabilities - if len(ver.Capabilities) > 0 && string(ver.Capabilities) != "null" { - if err := json.Unmarshal(ver.Capabilities, &caps); err != nil { - return nil, fmt.Errorf("decoding capabilities: %w", err) - } - } - - // Decode provider. - var provider *AgentProvider - if len(ver.Provider) > 0 && string(ver.Provider) != "null" { - if err := json.Unmarshal(ver.Provider, &provider); err != nil { - return nil, fmt.Errorf("decoding provider: %w", err) - } - } - - // Build security schemes map from authentication array. - securitySchemes, err := buildSecuritySchemes(ver.Authentication) - if err != nil { - return nil, fmt.Errorf("building security schemes: %w", err) - } - - inputModes := ver.DefaultInputModes - if len(inputModes) == 0 { - inputModes = []string{"text/plain"} - } - outputModes := ver.DefaultOutputModes - if len(outputModes) == 0 { - outputModes = []string{"text/plain"} - } - - card := &AgentCard{ - Name: agent.Name, - Description: agent.Description, - Version: ver.Version, - URL: ver.EndpointURL, - Provider: provider, - IconURL: ver.IconURL, - DocumentationURL: ver.DocumentationURL, - Capabilities: caps, - DefaultInputModes: inputModes, - DefaultOutputModes: outputModes, - Skills: skills, - SecuritySchemes: securitySchemes, - } - - return card, nil -} - -// buildSecuritySchemes converts the stored authentication JSON array into the -// A2A securitySchemes map shape. -// -// Input: [{"scheme":"Bearer"}, {"scheme":"OAuth2","tokenUrl":"https://..."}] -// Output: {"bearer": {"type":"http","scheme":"bearer"}, "oauth2": {...}} -func buildSecuritySchemes(raw json.RawMessage) (map[string]any, error) { - if len(raw) == 0 || string(raw) == "null" || string(raw) == "[]" { - return nil, nil - } - - var entries []map[string]any - if err := json.Unmarshal(raw, &entries); err != nil { - return nil, fmt.Errorf("decoding authentication: %w", err) - } - - schemes := make(map[string]any, len(entries)) - for _, e := range entries { - scheme, _ := e["scheme"].(string) - switch scheme { - case "Bearer": - schemes["bearer"] = map[string]any{ - "type": "http", - "scheme": "bearer", - } - case "ApiKey": - s := map[string]any{"type": "apiKey"} - if in, ok := e["in"].(string); ok { - s["in"] = in - } else { - s["in"] = "header" - } - if name, ok := e["name"].(string); ok { - s["name"] = name - } else { - s["name"] = "X-API-Key" - } - schemes["apiKey"] = s - case "OAuth2": - s := map[string]any{"type": "oauth2"} - if flows, ok := e["flows"]; ok { - s["flows"] = flows - } - schemes["oauth2"] = s - case "OpenIdConnect": - s := map[string]any{"type": "openIdConnect"} - if url, ok := e["openIdConnectUrl"].(string); ok { - s["openIdConnectUrl"] = url - } - schemes["openIdConnect"] = s - } - } - - if len(schemes) == 0 { - return nil, nil - } - return schemes, nil -} - -// RegistryCard builds the global AgentCard for the registry itself, making it -// a first-class A2A citizen discoverable at /.well-known/agent-card.json. -func RegistryCard(baseURL string) *AgentCard { - return &AgentCard{ - Name: "AI Registry", - Description: "Centralized registry for MCP servers and AI agents. Discover, publish, and manage AI ecosystem artifacts.", - Version: "0.1.0", - URL: baseURL + "/api/v1", - Capabilities: AgentCapabilities{ - ExtendedAgentCard: false, - }, - DefaultInputModes: []string{"application/json"}, - DefaultOutputModes: []string{"application/json"}, - Skills: []AgentSkill{ - { - ID: "mcp-registry", - Name: "MCP Server Registry", - Description: "Discover and manage Model Context Protocol servers.", - Tags: []string{"mcp", "registry", "discovery"}, - }, - { - ID: "agent-registry", - Name: "AI Agent Registry", - Description: "Discover and manage AI agents with A2A-compatible agent cards.", - Tags: []string{"a2a", "agents", "registry", "discovery"}, - }, - }, - } -} diff --git a/server/internal/agents/card_test.go b/server/internal/agents/card_test.go deleted file mode 100644 index 2524dee7..00000000 --- a/server/internal/agents/card_test.go +++ /dev/null @@ -1,273 +0,0 @@ -package agents_test - -import ( - "encoding/json" - "testing" - "time" - - "github.com/haibread/ai-registry/internal/agents" - "github.com/haibread/ai-registry/internal/domain" - "github.com/haibread/ai-registry/internal/store" -) - -func makeAgentRow(ns, slug, name string) store.AgentRow { - return store.AgentRow{ - Agent: domain.Agent{ - ID: "01HZ000000000000000000000A", - PublisherID: "01HZ000000000000000000000B", - Namespace: ns, - Slug: slug, - Name: name, - Description: "Test agent description", - Visibility: domain.VisibilityPublic, - Status: domain.StatusPublished, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }, - } -} - -func makeAgentVersion(version, endpoint string) *domain.AgentVersion { - now := time.Now() - return &domain.AgentVersion{ - ID: "01HZ000000000000000000000C", - AgentID: "01HZ000000000000000000000A", - Version: version, - EndpointURL: endpoint, - Skills: json.RawMessage(`[{"id":"s1","name":"Skill 1","description":"Does something","tags":["tag1"]}]`), - Capabilities: json.RawMessage(`{"streaming":true,"pushNotifications":false}`), - Authentication: json.RawMessage(`[{"scheme":"Bearer"}]`), - DefaultInputModes: []string{"text/plain"}, - DefaultOutputModes: []string{"text/plain"}, - Provider: json.RawMessage(`{"organization":"Test Org","url":"https://example.com"}`), - DocumentationURL: "https://docs.example.com", - IconURL: "https://icon.example.com/icon.png", - ProtocolVersion: domain.A2AProtocolVersion, - PublishedAt: &now, - CreatedAt: now, - UpdatedAt: now, - } -} - -func TestGenerateCard_Basic(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - - if card.Name != "My Agent" { - t.Errorf("Name = %q, want %q", card.Name, "My Agent") - } - if card.Version != "1.0.0" { - t.Errorf("Version = %q, want %q", card.Version, "1.0.0") - } - if card.URL != "https://agent.example.com/api" { - t.Errorf("URL = %q, want %q", card.URL, "https://agent.example.com/api") - } - if card.DocumentationURL != "https://docs.example.com" { - t.Errorf("DocumentationURL = %q", card.DocumentationURL) - } - if card.IconURL != "https://icon.example.com/icon.png" { - t.Errorf("IconURL = %q", card.IconURL) - } -} - -func TestGenerateCard_Skills(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - - if len(card.Skills) != 1 { - t.Fatalf("Skills len = %d, want 1", len(card.Skills)) - } - if card.Skills[0].ID != "s1" { - t.Errorf("Skills[0].ID = %q, want %q", card.Skills[0].ID, "s1") - } -} - -func TestGenerateCard_EmptySkillsBecomesEmptyArray(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.Skills = json.RawMessage(`[]`) - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - if card.Skills == nil { - t.Error("Skills should be an empty slice, not nil") - } - if len(card.Skills) != 0 { - t.Errorf("Skills len = %d, want 0", len(card.Skills)) - } -} - -func TestGenerateCard_Capabilities(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.Capabilities = json.RawMessage(`{"streaming":true,"pushNotifications":true}`) - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - if !card.Capabilities.Streaming { - t.Error("Capabilities.Streaming should be true") - } - if !card.Capabilities.PushNotifications { - t.Error("Capabilities.PushNotifications should be true") - } -} - -func TestGenerateCard_Provider(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - if card.Provider == nil { - t.Fatal("Provider should not be nil") - } - if card.Provider.Organization != "Test Org" { - t.Errorf("Provider.Organization = %q, want %q", card.Provider.Organization, "Test Org") - } -} - -func TestGenerateCard_DefaultModesWhenEmpty(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.DefaultInputModes = nil - ver.DefaultOutputModes = nil - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - if len(card.DefaultInputModes) == 0 || card.DefaultInputModes[0] != "text/plain" { - t.Errorf("DefaultInputModes = %v, want [text/plain]", card.DefaultInputModes) - } - if len(card.DefaultOutputModes) == 0 || card.DefaultOutputModes[0] != "text/plain" { - t.Errorf("DefaultOutputModes = %v, want [text/plain]", card.DefaultOutputModes) - } -} - -func TestGenerateCard_SecuritySchemes(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.Authentication = json.RawMessage(`[{"scheme":"Bearer"},{"scheme":"ApiKey","in":"header","name":"X-API-Key"}]`) - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - if _, ok := card.SecuritySchemes["bearer"]; !ok { - t.Error("SecuritySchemes should contain 'bearer'") - } - if _, ok := card.SecuritySchemes["apiKey"]; !ok { - t.Error("SecuritySchemes should contain 'apiKey'") - } -} - -func TestGenerateCard_NoAuthentication(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.Authentication = json.RawMessage(`[]`) - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - if card.SecuritySchemes != nil { - t.Errorf("SecuritySchemes should be nil for empty auth, got %v", card.SecuritySchemes) - } -} - -func TestGenerateCard_NilVersion(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - - _, err := agents.GenerateCard(agent, nil) - if err == nil { - t.Error("GenerateCard() with nil version should return error") - } -} - -func TestGenerateCard_InvalidSkillsJSON(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.Skills = json.RawMessage(`{bad json}`) - - _, err := agents.GenerateCard(agent, ver) - if err == nil { - t.Error("GenerateCard() with invalid skills JSON should return error") - } -} - -func TestRegistryCard(t *testing.T) { - card := agents.RegistryCard("https://registry.example.com") - - if card.Name != "AI Registry" { - t.Errorf("Name = %q, want %q", card.Name, "AI Registry") - } - if card.URL != "https://registry.example.com/api/v1" { - t.Errorf("URL = %q, want %q", card.URL, "https://registry.example.com/api/v1") - } - if len(card.Skills) < 2 { - t.Errorf("Skills len = %d, want >= 2", len(card.Skills)) - } - if len(card.DefaultInputModes) == 0 { - t.Error("DefaultInputModes should not be empty") - } - if len(card.DefaultOutputModes) == 0 { - t.Error("DefaultOutputModes should not be empty") - } -} - -func TestBuildSecuritySchemes_OAuth2(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.Authentication = json.RawMessage(`[{"scheme":"OAuth2","flows":{"clientCredentials":{"tokenUrl":"https://auth.example.com/token","scopes":{}}}}]`) - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - s, ok := card.SecuritySchemes["oauth2"] - if !ok { - t.Fatal("SecuritySchemes should contain 'oauth2'") - } - m, ok := s.(map[string]any) - if !ok { - t.Fatalf("oauth2 scheme is not a map, got %T", s) - } - if m["type"] != "oauth2" { - t.Errorf("oauth2 scheme type = %v, want oauth2", m["type"]) - } -} - -func TestBuildSecuritySchemes_OpenIdConnect(t *testing.T) { - agent := makeAgentRow("acme", "my-agent", "My Agent") - ver := makeAgentVersion("1.0.0", "https://agent.example.com/api") - ver.Authentication = json.RawMessage(`[{"scheme":"OpenIdConnect","openIdConnectUrl":"https://auth.example.com/.well-known/openid-configuration"}]`) - - card, err := agents.GenerateCard(agent, ver) - if err != nil { - t.Fatalf("GenerateCard() error = %v", err) - } - s, ok := card.SecuritySchemes["openIdConnect"] - if !ok { - t.Fatal("SecuritySchemes should contain 'openIdConnect'") - } - m := s.(map[string]any) - if m["openIdConnectUrl"] != "https://auth.example.com/.well-known/openid-configuration" { - t.Errorf("openIdConnectUrl = %v", m["openIdConnectUrl"]) - } -} diff --git a/server/internal/bootstrap/bootstrap.go b/server/internal/bootstrap/bootstrap.go index 1ceed3e9..deae3491 100644 --- a/server/internal/bootstrap/bootstrap.go +++ b/server/internal/bootstrap/bootstrap.go @@ -127,23 +127,11 @@ func Run(ctx context.Context, db *store.DB, spec *Spec, logger *slog.Logger) err } } - // ── Agents ──────────────────────────────────────────────────────────────── - for _, a := range spec.Agents { - pubID, ok := pubIDs[a.Publisher] - if !ok { - return fmt.Errorf("bootstrap: agent %q references unknown publisher %q", a.Slug, a.Publisher) - } - if err := upsertAgent(ctx, db, pubID, a.Publisher, a, logger); err != nil { - return fmt.Errorf("bootstrap: agent %q: %w", a.Slug, err) - } - } - logger.Info("bootstrap: complete", slog.Int("publishers", len(spec.Publishers)), slog.Int("groups", len(spec.Groups)), slog.Int("grants", len(spec.Grants)), slog.Int("mcp_servers", len(spec.MCPServers)), - slog.Int("agents", len(spec.Agents)), ) return nil } @@ -165,9 +153,6 @@ func ensureInstanceTags(ctx context.Context, db *store.DB, spec *Spec, logger *s for _, s := range spec.MCPServers { collect(s.Tags) } - for _, a := range spec.Agents { - collect(a.Tags) - } for _, slug := range slugs { if err := domain.ValidateSlug(slug); err != nil { @@ -558,195 +543,6 @@ func upsertMCPVersion(ctx context.Context, db *store.DB, serverID, publisherSlug return nil } -// ── agents ──────────────────────────────────────────────────────────────────── - -func upsertAgent(ctx context.Context, db *store.DB, publisherID, publisherSlug string, a AgentSpec, logger *slog.Logger) error { - var agentID string - created := false - err := db.Pool.QueryRow(ctx, - `SELECT id FROM agents WHERE publisher_id = $1 AND slug = $2`, - publisherID, a.Slug, - ).Scan(&agentID) - - if err != nil { - // Row not found — create it. - ag, createErr := db.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: publisherID, - Slug: a.Slug, - Name: a.Name, - Description: a.Description, - }) - if createErr != nil { - return fmt.Errorf("creating agent: %w", createErr) - } - agentID = ag.ID - created = true - - logBootstrapAudit(ctx, db, domain.AuditEvent{ - Action: domain.ActionAgentCreated, - ResourceType: "agent", - ResourceID: agentID, - ResourceNS: publisherSlug, - ResourceSlug: a.Slug, - Metadata: map[string]any{ - "name": a.Name, - }, - }) - - vis := domain.VisibilityPrivate - if a.Public { - vis = domain.VisibilityPublic - } - if err := db.SetAgentVisibility(ctx, agentID, vis); err != nil { - return fmt.Errorf("setting visibility: %w", err) - } - if a.Public { - logBootstrapAudit(ctx, db, domain.AuditEvent{ - Action: domain.ActionAgentVisibility, - ResourceType: "agent", - ResourceID: agentID, - ResourceNS: publisherSlug, - ResourceSlug: a.Slug, - Metadata: map[string]any{ - "from": string(domain.VisibilityPrivate), - "to": string(domain.VisibilityPublic), - }, - }) - } - // CreateAgent does not take featured / verified / readme, so they are - // set with direct SQL. Tags live on version rows and are applied - // per version below. - if a.Featured || a.Verified || a.Readme != "" { - if _, err := db.Pool.Exec(ctx, - `UPDATE agents - SET featured=$1, verified=$2, readme=$3, updated_at=now() - WHERE id=$4`, - a.Featured, a.Verified, a.Readme, agentID, - ); err != nil { - return fmt.Errorf("setting agent metadata: %w", err) - } - } - logger.Info("bootstrap: created agent", slog.String("slug", a.Slug)) - } else { - logger.Info("bootstrap: agent already exists, skipping", slog.String("slug", a.Slug)) - } - - // Apply versions (idempotent per-version check inside). The entry-level - // spec tags ride along — tags live on version rows. - for _, v := range a.Versions { - if err := upsertAgentVersion(ctx, db, agentID, publisherSlug, a.Slug, v, a.Tags, logger); err != nil { - return fmt.Errorf("version %q: %w", v.Version, err) - } - } - - // Only apply agent-level status mutations for newly created agents. - // Existing agents keep whatever status they already have. - if created && a.Status == "deprecated" { - if err := db.DeprecateAgent(ctx, agentID); err != nil { - return fmt.Errorf("deprecating agent: %w", err) - } - logBootstrapAudit(ctx, db, domain.AuditEvent{ - Action: domain.ActionAgentDeprecated, - ResourceType: "agent", - ResourceID: agentID, - ResourceNS: publisherSlug, - ResourceSlug: a.Slug, - }) - } - - return nil -} - -func upsertAgentVersion(ctx context.Context, db *store.DB, agentID, publisherSlug, agentSlug string, v AgentVersionSpec, entryTags []string, logger *slog.Logger) error { - var exists bool - _ = db.Pool.QueryRow(ctx, - `SELECT EXISTS(SELECT 1 FROM agent_versions WHERE agent_id = $1 AND version = $2)`, - agentID, v.Version, - ).Scan(&exists) - if exists { - logger.Info("bootstrap: agent version already exists, skipping", - slog.String("agent", agentID), slog.String("version", v.Version)) - return nil - } - - skills, err := json.Marshal(v.Skills) - if err != nil { - return fmt.Errorf("marshalling skills: %w", err) - } - auth, err := json.Marshal(v.Authentication) - if err != nil { - return fmt.Errorf("marshalling authentication: %w", err) - } - - protocolVersion := v.ProtocolVersion - if protocolVersion == "" { - protocolVersion = domain.A2AProtocolVersion - } - - ver, err := db.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agentID, - Version: v.Version, - EndpointURL: v.EndpointURL, - Skills: skills, - Authentication: auth, - DefaultInputModes: v.DefaultInputModes, - DefaultOutputModes: v.DefaultOutputModes, - DocumentationURL: v.DocumentationURL, - IconURL: v.IconURL, - Tags: domain.NormalizeVersionTags(entryTags), - ProtocolVersion: protocolVersion, - }) - if err != nil { - return fmt.Errorf("creating version: %w", err) - } - - logBootstrapAudit(ctx, db, domain.AuditEvent{ - Action: domain.ActionAgentVersionCreated, - ResourceType: "agent", - ResourceID: agentID, - ResourceNS: publisherSlug, - ResourceSlug: agentSlug, - Metadata: map[string]any{ - "version": ver.Version, - }, - }) - - status := strings.ToLower(v.Status) - switch status { - case "published", "deprecated": - if err := db.PublishAgentVersion(ctx, agentID, ver.Version); err != nil { - return fmt.Errorf("publishing version: %w", err) - } - logBootstrapAudit(ctx, db, domain.AuditEvent{ - Action: domain.ActionAgentVersionPublished, - ResourceType: "agent", - ResourceID: agentID, - ResourceNS: publisherSlug, - ResourceSlug: agentSlug, - Metadata: map[string]any{ - "version": ver.Version, - }, - }) - if status == "deprecated" { - if err := db.SetAgentVersionStatus(ctx, agentID, ver.Version, - domain.VersionStatusDeprecated, v.StatusMessage); err != nil { - return fmt.Errorf("deprecating version: %w", err) - } - } - case "draft", "": - // nothing - default: - return fmt.Errorf("unknown version status %q (want draft|published|deprecated)", v.Status) - } - - logger.Info("bootstrap: created agent version", - slog.String("agent", agentID), - slog.String("version", v.Version), - slog.String("status", status), - ) - return nil -} - // ── helpers ─────────────────────────────────────────────────────────────────── // isEmptyJSONArray returns true if raw is JSON-equivalent to an empty array. @@ -872,32 +668,6 @@ func validateSpec(s *Spec) error { } } - for i, ag := range s.Agents { - prefix := fmt.Sprintf("agents[%d](%s)", i, ag.Slug) - if ag.Publisher == "" { - errs = append(errs, prefix+": publisher is required") - } else if !pubSlugs[ag.Publisher] { - errs = append(errs, prefix+fmt.Sprintf(": publisher %q not found in publishers list", ag.Publisher)) - } - if ag.Slug == "" { - errs = append(errs, prefix+": slug is required") - } - if ag.Name == "" { - errs = append(errs, prefix+": name is required") - } - for j, v := range ag.Versions { - if v.Version == "" { - errs = append(errs, fmt.Sprintf("%s.versions[%d]: version is required", prefix, j)) - } - if v.EndpointURL == "" { - errs = append(errs, fmt.Sprintf("%s.versions[%d]: endpoint_url is required", prefix, j)) - } - if err := domain.ValidateAgentVersionURLs(v.EndpointURL, v.DocumentationURL, v.IconURL, nil); err != nil { - errs = append(errs, fmt.Sprintf("%s.versions[%d]: %s", prefix, j, err)) - } - } - } - if len(errs) > 0 { return errors.New(strings.Join(errs, "; ")) } diff --git a/server/internal/bootstrap/bootstrap_test.go b/server/internal/bootstrap/bootstrap_test.go index c10bb82e..7b75efa4 100644 --- a/server/internal/bootstrap/bootstrap_test.go +++ b/server/internal/bootstrap/bootstrap_test.go @@ -60,7 +60,7 @@ func TestMain(m *testing.M) { func resetDB(t *testing.T) { t.Helper() _, err := sharedDB.Pool.Exec(context.Background(), - `TRUNCATE agent_versions, agents, mcp_server_versions, mcp_servers, publishers, + `TRUNCATE mcp_server_versions, mcp_servers, publishers, role_grants, group_members, groups, users, audit_log, instance_tags RESTART IDENTITY CASCADE`) if err != nil { t.Fatalf("truncating tables: %v", err) @@ -103,24 +103,6 @@ mcp_servers: version: "1.0.0" transport: type: "stdio" - -agents: - - publisher: "acme" - slug: "my-agent" - name: "My Agent" - description: "A test agent" - public: true - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://agents.acme.com/my-agent" - skills: - - id: "do-thing" - name: "Do Thing" - description: "Does the thing" - tags: ["thing"] - authentication: - - scheme: "Bearer" `) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -151,9 +133,6 @@ agents: if srv.Versions[0].Packages[0].RegistryType != "npm" { t.Errorf("registry_type = %q, want npm", srv.Versions[0].Packages[0].RegistryType) } - if len(spec.Agents) != 1 { - t.Errorf("agents len = %d, want 1", len(spec.Agents)) - } } func TestLoadSpec_JSON(t *testing.T) { @@ -169,8 +148,7 @@ func TestLoadSpec_JSON(t *testing.T) { "status": "published", "packages": [{"registryType": "npm", "identifier": "pkg", "version": "1.0.0", "transport": {"type": "stdio"}}] }] - }], - "agents": [] + }] }`) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -305,9 +283,6 @@ func TestLoadSpec_ExampleYAML(t *testing.T) { if len(spec.MCPServers) == 0 { t.Error("example has zero MCP servers; expected at least one") } - if len(spec.Agents) == 0 { - t.Error("example has zero agents; expected at least one") - } // Sanity-check that at least one entry exercises each optional metadata // field, otherwise the example isn't demonstrating them. var featured, tagged, withReadme, withCaps bool @@ -406,26 +381,6 @@ mcp_servers: version: "2.0.0" transport: type: "stdio" - -agents: - - publisher: "acme" - slug: "my-agent" - name: "My Agent" - description: "Test agent" - public: true - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://agents.acme.com/my-agent" - default_input_modes: ["text/plain"] - default_output_modes: ["text/plain"] - skills: - - id: "do-thing" - name: "Do Thing" - description: "Does the thing" - tags: ["thing"] - authentication: - - scheme: "Bearer" `) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -459,15 +414,6 @@ agents: if len(versions) != 2 { t.Fatalf("version count = %d, want 2", len(versions)) } - - // Verify agent exists. - agent, err := sharedDB.GetAgent(ctx, "acme", "my-agent", false) - if err != nil { - t.Fatalf("GetAgent() error = %v", err) - } - if agent.Visibility != "public" { - t.Errorf("agent visibility = %q, want public", agent.Visibility) - } } func TestLoadSpec_GrantValidation(t *testing.T) { @@ -607,7 +553,6 @@ mcp_servers: version: "1.0.0" transport: type: "stdio" -agents: [] `) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -665,7 +610,6 @@ mcp_servers: version: "1.0.0" transport: type: "stdio" -agents: [] `) s1, err := bootstrap.LoadSpec(specV1) if err != nil { @@ -709,7 +653,6 @@ mcp_servers: description: "Read a file" - name: "write_file" description: "Write a file" -agents: [] `) s2, err := bootstrap.LoadSpec(specV2) if err != nil { @@ -786,28 +729,6 @@ mcp_servers: version: "1.0.0" transport: type: "stdio" - -agents: - - publisher: "acme" - slug: "fancy-agent" - name: "Fancy Agent" - description: "showcase agent" - public: true - featured: true - verified: true - tags: ["demo", "a2a"] - readme: "# Fancy Agent\n\nA showcase of the v0.2 fields." - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://agents.acme.com/fancy" - skills: - - id: "do-thing" - name: "Do Thing" - description: "Does a thing" - tags: ["demo"] - authentication: - - scheme: "Bearer" `) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -841,7 +762,7 @@ agents: for _, tag := range vocab { seenSlugs[tag.Slug] = true } - for _, want := range []string{"official", "featured", "demo", "a2a"} { + for _, want := range []string{"official", "featured"} { if !seenSlugs[want] { t.Errorf("instance tag %q not auto-created by bootstrap", want) } @@ -862,28 +783,11 @@ agents: if caps == "" || caps == "{}" { t.Errorf("version capabilities = %q, want non-empty JSON", caps) } - - agent, err := sharedDB.GetAgent(ctx, "acme", "fancy-agent", false) - if err != nil { - t.Fatalf("GetAgent() error = %v", err) - } - if !agent.Featured { - t.Error("agent featured = false, want true") - } - if !agent.Verified { - t.Error("agent verified = false, want true") - } - if len(agent.Tags) != 2 || agent.Tags[0] != "a2a" || agent.Tags[1] != "demo" { - t.Errorf("agent tags = %v, want [a2a demo]", agent.Tags) - } - if agent.Readme == "" { - t.Error("agent readme is empty, want non-empty markdown") - } } // TestRun_V02Fields_IdempotentPreservesAdminEdits verifies that re-running // bootstrap does NOT overwrite admin edits to the metadata fields. This is -// the whole point of the `if created` guard in upsertMCPServer/upsertAgent: +// the whole point of the `if created` guard in upsertMCPServer: // bootstrap seeds the initial state, but after that it must be hands-off. func TestRun_V02Fields_IdempotentPreservesAdminEdits(t *testing.T) { resetDB(t) @@ -913,28 +817,6 @@ mcp_servers: version: "1.0.0" transport: type: "stdio" - -agents: - - publisher: "acme" - slug: "fancy-agent" - name: "Fancy Agent" - description: "showcase" - public: true - featured: true - verified: true - tags: ["bootstrap-tag"] - readme: "bootstrap readme" - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://agents.acme.com/fancy" - skills: - - id: "do" - name: "Do" - description: "do it" - tags: ["x"] - authentication: - - scheme: "Bearer" `) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -958,17 +840,6 @@ agents: t.Fatalf("admin update (mcp): %v", err) } - agent, err := sharedDB.GetAgent(ctx, "acme", "fancy-agent", false) - if err != nil { - t.Fatalf("GetAgent() error = %v", err) - } - if _, err := sharedDB.Pool.Exec(ctx, - `UPDATE agents SET featured=false, verified=false, readme=$1 WHERE id=$2`, - "admin readme", agent.ID, - ); err != nil { - t.Fatalf("admin update (agent): %v", err) - } - // Re-run bootstrap. The existing rows must be left untouched. if err := bootstrap.Run(ctx, sharedDB, spec, nil); err != nil { t.Fatalf("second Run() error = %v", err) @@ -992,23 +863,6 @@ agents: if srvAfter.Readme != "admin readme" { t.Errorf("mcp server: readme = %q, want %q", srvAfter.Readme, "admin readme") } - - agentAfter, err := sharedDB.GetAgent(ctx, "acme", "fancy-agent", false) - if err != nil { - t.Fatalf("GetAgent() after: %v", err) - } - if agentAfter.Featured { - t.Error("agent: bootstrap clobbered admin featured=false") - } - if agentAfter.Verified { - t.Error("agent: bootstrap clobbered admin verified=false") - } - if len(agentAfter.Tags) != 1 || agentAfter.Tags[0] != "bootstrap-tag" { - t.Errorf("agent: tags = %v, want [bootstrap-tag]", agentAfter.Tags) - } - if agentAfter.Readme != "admin readme" { - t.Errorf("agent: readme = %q, want %q", agentAfter.Readme, "admin readme") - } } func TestRun_DeprecatedServerAndVersion(t *testing.T) { @@ -1036,7 +890,6 @@ mcp_servers: version: "1.0.0" transport: type: "stdio" -agents: [] `) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -1095,24 +948,6 @@ mcp_servers: version: "1.0.0" transport: type: "stdio" - -agents: - - publisher: "acme" - slug: "audit-agent" - name: "Audit Agent" - description: "seeded" - public: true - versions: - - version: "1.0.0" - status: "published" - endpoint_url: "https://agents.acme.com/audit" - skills: - - id: "s1" - name: "S1" - description: "skill" - tags: ["x"] - authentication: - - scheme: "Bearer" `) spec, err := bootstrap.LoadSpec(path) if err != nil { @@ -1130,15 +965,11 @@ agents: // Expected event counts per action for a single run of the spec above. want := map[domain.AuditAction]int{ - domain.ActionPublisherCreated: 1, - domain.ActionMCPServerCreated: 1, - domain.ActionMCPServerVisibility: 1, // flipped public on create - domain.ActionMCPVersionCreated: 1, - domain.ActionMCPVersionPublished: 1, - domain.ActionAgentCreated: 1, - domain.ActionAgentVisibility: 1, - domain.ActionAgentVersionCreated: 1, - domain.ActionAgentVersionPublished: 1, + domain.ActionPublisherCreated: 1, + domain.ActionMCPServerCreated: 1, + domain.ActionMCPServerVisibility: 1, // flipped public on create + domain.ActionMCPVersionCreated: 1, + domain.ActionMCPVersionPublished: 1, } gotCounts := map[domain.AuditAction]int{} @@ -1250,23 +1081,6 @@ mcp_servers: remotes: - type: "sse" url: "data:text/html,x" -`, - }, - { - name: "agent icon", - wantField: "icon_url", - spec: ` -publishers: - - slug: "acme" - name: "Acme Corp" -agents: - - publisher: "acme" - slug: "agent" - name: "Agent" - versions: - - version: "1.0.0" - endpoint_url: "https://agent.example.com" - icon_url: "javascript:alert(1)" `, }, } diff --git a/server/internal/bootstrap/spec.go b/server/internal/bootstrap/spec.go index 65f0571b..eab4b49f 100644 --- a/server/internal/bootstrap/spec.go +++ b/server/internal/bootstrap/spec.go @@ -9,7 +9,6 @@ type Spec struct { Groups []GroupSpec `yaml:"groups" json:"groups"` Grants []GrantSpec `yaml:"grants" json:"grants"` MCPServers []MCPServerSpec `yaml:"mcp_servers" json:"mcp_servers"` - Agents []AgentSpec `yaml:"agents" json:"agents"` } // PublisherSpec describes a publisher entry. @@ -137,57 +136,3 @@ type RemoteSpec struct { Type string `yaml:"type" json:"type"` URL string `yaml:"url" json:"url"` } - -// AgentSpec describes an agent and all its versions. -type AgentSpec struct { - // Publisher is the slug of the publisher that owns this agent. - Publisher string `yaml:"publisher" json:"publisher"` - Slug string `yaml:"slug" json:"slug"` - Name string `yaml:"name" json:"name"` - Description string `yaml:"description" json:"description"` - // Public controls whether the agent is visible to unauthenticated users. - Public bool `yaml:"public" json:"public"` - // Status of the agent itself: "draft" | "published" | "deprecated". - Status string `yaml:"status" json:"status"` - // Featured flags an agent for the home page "featured" carousel. - Featured bool `yaml:"featured" json:"featured"` - // Verified marks the agent as officially vetted by the registry. - Verified bool `yaml:"verified" json:"verified"` - // Tags are instance-tag slugs applied to every version this spec - // creates (tags live on version rows since migration 000022). Slugs - // missing from the vocabulary are created on the fly (unmanaged, - // name = slug) so seeded data always resolves. - Tags []string `yaml:"tags" json:"tags"` - // Readme is long-form markdown content rendered on the detail page. - Readme string `yaml:"readme" json:"readme"` - Versions []AgentVersionSpec `yaml:"versions" json:"versions"` -} - -// AgentVersionSpec describes a single version of an agent. -type AgentVersionSpec struct { - Version string `yaml:"version" json:"version"` - // Status: "draft" | "published" | "deprecated". Defaults to "draft". - Status string `yaml:"status" json:"status"` - StatusMessage string `yaml:"status_message" json:"status_message"` - EndpointURL string `yaml:"endpoint_url" json:"endpoint_url"` - ProtocolVersion string `yaml:"protocol_version" json:"protocol_version"` - DefaultInputModes []string `yaml:"default_input_modes" json:"default_input_modes"` - DefaultOutputModes []string `yaml:"default_output_modes" json:"default_output_modes"` - DocumentationURL string `yaml:"documentation_url" json:"documentation_url"` - IconURL string `yaml:"icon_url" json:"icon_url"` - Skills []SkillSpec `yaml:"skills" json:"skills"` - Authentication []AuthSpec `yaml:"authentication" json:"authentication"` -} - -// SkillSpec describes a single skill exposed by an agent version. -type SkillSpec struct { - ID string `yaml:"id" json:"id"` - Name string `yaml:"name" json:"name"` - Description string `yaml:"description" json:"description"` - Tags []string `yaml:"tags" json:"tags"` -} - -// AuthSpec describes an authentication scheme accepted by an agent version. -type AuthSpec struct { - Scheme string `yaml:"scheme" json:"scheme"` -} diff --git a/server/internal/config/config.go b/server/internal/config/config.go index 9e49ec1c..36e4b87a 100644 --- a/server/internal/config/config.go +++ b/server/internal/config/config.go @@ -31,7 +31,7 @@ type Config struct { ToolDiscovery ToolDiscoveryConfig // BootstrapFile is the optional path to a YAML/JSON file containing - // initial registry data (publishers, MCP servers, agents) + // initial registry data (publishers, MCP servers) // that the server upserts on startup before accepting traffic. Empty // disables bootstrap loading. Settable via env (BOOTSTRAP_FILE), YAML // (top-level `bootstrap_file`), or the `--bootstrap-file` CLI flag — @@ -229,12 +229,10 @@ type HTTPConfig struct { // reads on /api/v1, expressed in requests per minute. Defaults to 1000, // which a browser SPA and the e2e suite stay under in normal use. PublicRateLimitRPM int - // PublicBaseURL is the externally reachable URL of this deployment. - // Surfaced in the A2A global agent card (`/.well-known/agent-card.json`), - // used as the access-token issuer and to derive the OIDC callback and + // PublicBaseURL is the externally reachable URL of this deployment. It + // is used as the access-token issuer and to derive the OIDC callback and // post-login/logout redirects. Must be the address clients use, not an - // internal docker hostname. The global agent card returns 500 when this - // is empty rather than silently advertising localhost. + // internal docker hostname. PublicBaseURL string // ShutdownDrainDelay is how long the server keeps serving after SIGTERM, // with /readyz failing, before it stops accepting connections. It gives diff --git a/server/internal/domain/agent.go b/server/internal/domain/agent.go deleted file mode 100644 index 620e1013..00000000 --- a/server/internal/domain/agent.go +++ /dev/null @@ -1,190 +0,0 @@ -package domain - -import ( - "encoding/json" - "fmt" - "time" -) - -// A2AProtocolVersion is the A2A spec version this implementation targets. -// Ref: https://github.com/a2aproject/a2a (June 2025 shape) -const A2AProtocolVersion = "0.2.1" - -// validAuthSchemes is the allowlist of authentication scheme types. -var validAuthSchemes = map[string]bool{ - "Bearer": true, - "ApiKey": true, - "OAuth2": true, - "OpenIdConnect": true, -} - -// Agent is the top-level entity for an AI agent in the registry. -type Agent struct { - ID string - PublisherID string - Namespace string // publisher slug - Slug string - Name string - Description string - Visibility Visibility - Status ServerStatus - Featured bool - Verified bool - Readme string - ViewCount int - CopyCount int - Tags []string - CreatedAt time.Time - UpdatedAt time.Time -} - -// AgentVersion is an immutable versioned release of an Agent. -// Once published_at is set, no fields may be mutated. -// -// The JSON tags are the wire format used by the versions list/detail -// endpoints — they must stay in sync with the AgentVersion schema in -// server/api/openapi.yaml, and with the frontend VersionHistory component -// which reads these snake_case keys. -type AgentVersion struct { - ID string `json:"id"` - AgentID string `json:"agent_id"` - Version string `json:"version"` // semver - EndpointURL string `json:"endpoint_url"` - Skills json.RawMessage `json:"skills,omitempty"` // []AgentSkill - Capabilities json.RawMessage `json:"capabilities,omitempty"` // AgentCapabilities - Authentication json.RawMessage `json:"authentication,omitempty"` // []AuthScheme - DefaultInputModes []string `json:"default_input_modes,omitempty"` - DefaultOutputModes []string `json:"default_output_modes,omitempty"` - Provider json.RawMessage `json:"provider,omitempty"` // AgentProvider - DocumentationURL string `json:"documentation_url,omitempty"` - IconURL string `json:"icon_url,omitempty"` - Tags []string `json:"tags"` // instance-tag slugs ticked on this version - ProtocolVersion string `json:"protocol_version"` - Status VersionStatus `json:"status"` // active | deprecated | deleted - StatusMessage string `json:"status_message,omitempty"` - StatusChangedAt time.Time `json:"status_changed_at"` - PublishedAt *time.Time `json:"published_at,omitempty"` - // Change-approval workflow fields. See domain.MCPServerVersion for - // the equivalent commentary; both version tables share the same - // review schema. - ReviewState ReviewState `json:"review_state,omitempty"` - Revision int `json:"revision,omitempty"` - SubmittedAt *time.Time `json:"submitted_at,omitempty"` - SubmittedBy string `json:"submitted_by,omitempty"` - SubmittedByEmail string `json:"submitted_by_email,omitempty"` - ReviewedAt *time.Time `json:"reviewed_at,omitempty"` - ReviewedBy string `json:"reviewed_by,omitempty"` - ReviewedByEmail string `json:"reviewed_by_email,omitempty"` - ReviewDecision ReviewDecision `json:"review_decision,omitempty"` - RejectionReason string `json:"rejection_reason,omitempty"` - // RequestPublic records the author's release intent for the in-flight - // submission: approval also flips the owning entry's visibility to - // public. Set on submit, cleared on withdraw. - RequestPublic bool `json:"request_public,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// IsPublished reports whether this version has been published. -func (v *AgentVersion) IsPublished() bool { return v.PublishedAt != nil } - -// ── Validation types ───────────────────────────────────────────────────────── - -// AgentSkill mirrors the A2A AgentSkill object. -type AgentSkill struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Tags []string `json:"tags"` - Examples []string `json:"examples,omitempty"` - InputModes []string `json:"inputModes,omitempty"` - OutputModes []string `json:"outputModes,omitempty"` -} - -// AuthScheme is one entry in the authentication array. -type AuthScheme struct { - Scheme string `json:"scheme"` // Bearer | ApiKey | OAuth2 | OpenIdConnect -} - -// ValidateSkills checks that the skills JSONB is a valid array and that each -// entry satisfies the structural requirements of the A2A AgentSkill schema. -func ValidateSkills(raw json.RawMessage) error { - if len(raw) == 0 { - return fmt.Errorf("skills must not be empty") - } - var skills []AgentSkill - if err := json.Unmarshal(raw, &skills); err != nil { - return fmt.Errorf("skills must be a JSON array: %w", err) - } - if len(skills) == 0 { - return fmt.Errorf("skills must contain at least one entry") - } - for i, s := range skills { - if s.ID == "" { - return fmt.Errorf("skills[%d].id is required", i) - } - if s.Name == "" { - return fmt.Errorf("skills[%d].name is required", i) - } - if s.Description == "" { - return fmt.Errorf("skills[%d].description is required", i) - } - if s.Tags == nil { - return fmt.Errorf("skills[%d].tags is required (may be an empty array)", i) - } - for j, tag := range s.Tags { - if tag == "" { - return fmt.Errorf("skills[%d].tags[%d] must not be an empty string", i, j) - } - } - } - return nil -} - -// ValidateAuthentication checks that each authentication entry uses an -// allowed scheme from the registry allowlist. -func ValidateAuthentication(raw json.RawMessage) error { - if len(raw) == 0 || string(raw) == "null" || string(raw) == "[]" { - return nil // empty is allowed (public agent) - } - var schemes []AuthScheme - if err := json.Unmarshal(raw, &schemes); err != nil { - return fmt.Errorf("authentication must be a JSON array: %w", err) - } - for i, s := range schemes { - if s.Scheme == "" { - return fmt.Errorf("authentication[%d].scheme is required", i) - } - if !validAuthSchemes[s.Scheme] { - return fmt.Errorf( - "authentication[%d].scheme %q is not allowed (valid: Bearer, ApiKey, OAuth2, OpenIdConnect)", - i, s.Scheme, - ) - } - } - return nil -} - -// ValidateAgentVersionURLs checks the URL fields of an agent version, -// including provider.url. endpoint_url required-ness is the caller's concern. -func ValidateAgentVersionURLs(endpointURL, documentationURL, iconURL string, provider json.RawMessage) error { - for _, f := range []struct{ name, value string }{ - {"endpoint_url", endpointURL}, - {"documentation_url", documentationURL}, - {"icon_url", iconURL}, - } { - if err := ValidateHTTPURL(f.name, f.value); err != nil { - return err - } - } - if len(provider) == 0 || string(provider) == "null" { - return nil - } - var p struct { - URL string `json:"url"` - } - if err := json.Unmarshal(provider, &p); err != nil { - return fmt.Errorf("provider must be a JSON object: %w", err) - } - return ValidateHTTPURL("provider.url", p.URL) -} diff --git a/server/internal/domain/agent_test.go b/server/internal/domain/agent_test.go deleted file mode 100644 index fc26bde9..00000000 --- a/server/internal/domain/agent_test.go +++ /dev/null @@ -1,190 +0,0 @@ -package domain_test - -import ( - "encoding/json" - "testing" - "time" - - "github.com/haibread/ai-registry/internal/domain" -) - -// TestAgentVersion_JSONShape locks in the snake_case wire format. See the -// MCP counterpart in mcp_test.go for background. -func TestAgentVersion_JSONShape(t *testing.T) { - published := time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) - v := domain.AgentVersion{ - ID: "01J", - AgentID: "01A", - Version: "1.0.0", - EndpointURL: "https://example.com/a2a", - ProtocolVersion: "0.2.1", - Status: domain.VersionStatusActive, - PublishedAt: &published, - } - b, err := json.Marshal(v) - if err != nil { - t.Fatalf("marshal: %v", err) - } - var out map[string]any - if err := json.Unmarshal(b, &out); err != nil { - t.Fatalf("unmarshal: %v", err) - } - for _, key := range []string{ - "id", "agent_id", "version", "endpoint_url", "protocol_version", - "status", "published_at", "created_at", "updated_at", - } { - if _, ok := out[key]; !ok { - t.Errorf("missing JSON key %q; got %s", key, string(b)) - } - } - for _, bad := range []string{"ID", "AgentID", "Version", "EndpointURL", "PublishedAt"} { - if _, ok := out[bad]; ok { - t.Errorf("unexpected PascalCase JSON key %q", bad) - } - } -} - -func TestAgentVersion_JSONShape_Draft(t *testing.T) { - v := domain.AgentVersion{ID: "01J", Version: "0.1.0"} - b, err := json.Marshal(v) - if err != nil { - t.Fatalf("marshal: %v", err) - } - var out map[string]any - if err := json.Unmarshal(b, &out); err != nil { - t.Fatalf("unmarshal: %v", err) - } - if _, ok := out["published_at"]; ok { - t.Errorf("published_at should be omitted for draft versions; got %s", string(b)) - } -} - -func TestValidateSkills(t *testing.T) { - tests := []struct { - name string - input string - wantErr bool - }{ - { - name: "valid single skill", - input: `[{"id":"search","name":"Search","description":"Searches the web","tags":["search"]}]`, - }, - { - name: "valid skill with optional fields", - input: `[{"id":"search","name":"Search","description":"Searches","tags":["search","web"],"examples":["search foo"],"inputModes":["text/plain"],"outputModes":["text/plain"]}]`, - }, - { - name: "valid skill with empty tags array", - input: `[{"id":"search","name":"Search","description":"Searches","tags":[]}]`, - }, - { - name: "valid multiple skills", - input: `[{"id":"a","name":"A","description":"Skill A","tags":[]},{"id":"b","name":"B","description":"Skill B","tags":["x"]}]`, - }, - { - name: "empty raw input", - input: ``, - wantErr: true, - }, - { - name: "empty array", - input: `[]`, - wantErr: true, - }, - { - name: "not an array", - input: `{"id":"search"}`, - wantErr: true, - }, - { - name: "missing id", - input: `[{"name":"Search","description":"Searches","tags":[]}]`, - wantErr: true, - }, - { - name: "missing name", - input: `[{"id":"search","description":"Searches","tags":[]}]`, - wantErr: true, - }, - { - name: "missing description", - input: `[{"id":"search","name":"Search","tags":[]}]`, - wantErr: true, - }, - { - name: "missing tags field", - input: `[{"id":"search","name":"Search","description":"Searches"}]`, - wantErr: true, - }, - { - name: "empty string in tags", - input: `[{"id":"search","name":"Search","description":"Searches","tags":[""]}]`, - wantErr: true, - }, - { - name: "invalid JSON", - input: `[{bad}]`, - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := domain.ValidateSkills(json.RawMessage(tt.input)) - if (err != nil) != tt.wantErr { - t.Errorf("ValidateSkills() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func TestValidateAuthentication(t *testing.T) { - tests := []struct { - name string - input string - wantErr bool - }{ - {name: "empty is ok (public agent)", input: ``}, - {name: "null is ok", input: `null`}, - {name: "empty array is ok", input: `[]`}, - {name: "Bearer scheme", input: `[{"scheme":"Bearer"}]`}, - {name: "ApiKey scheme", input: `[{"scheme":"ApiKey"}]`}, - {name: "OAuth2 scheme", input: `[{"scheme":"OAuth2"}]`}, - {name: "OpenIdConnect scheme", input: `[{"scheme":"OpenIdConnect"}]`}, - {name: "multiple valid schemes", input: `[{"scheme":"Bearer"},{"scheme":"OAuth2"}]`}, - { - name: "unknown scheme", - input: `[{"scheme":"Basic"}]`, - wantErr: true, - }, - { - name: "empty scheme string", - input: `[{"scheme":""}]`, - wantErr: true, - }, - { - name: "missing scheme field", - input: `[{}]`, - wantErr: true, - }, - { - name: "invalid JSON", - input: `[{bad}]`, - wantErr: true, - }, - { - name: "not an array", - input: `{"scheme":"Bearer"}`, - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := domain.ValidateAuthentication(json.RawMessage(tt.input)) - if (err != nil) != tt.wantErr { - t.Errorf("ValidateAuthentication() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} diff --git a/server/internal/domain/audit.go b/server/internal/domain/audit.go index 61eba8d0..0a48f1ea 100644 --- a/server/internal/domain/audit.go +++ b/server/internal/domain/audit.go @@ -14,22 +14,10 @@ const ( ActionMCPServerUndeprecated AuditAction = "mcp_server.undeprecated" ActionMCPServerVisibility AuditAction = "mcp_server.visibility_changed" - // Agent actions - ActionAgentCreated AuditAction = "agent.created" - ActionAgentVersionCreated AuditAction = "agent_version.created" - ActionAgentVersionPublished AuditAction = "agent_version.published" - ActionAgentDeprecated AuditAction = "agent.deprecated" - ActionAgentUndeprecated AuditAction = "agent.undeprecated" - ActionAgentVisibility AuditAction = "agent.visibility_changed" - // MCP server update/delete actions ActionMCPServerUpdated AuditAction = "mcp_server.updated" ActionMCPServerDeleted AuditAction = "mcp_server.deleted" - // Agent update/delete actions - ActionAgentUpdated AuditAction = "agent.updated" - ActionAgentDeleted AuditAction = "agent.deleted" - // Publisher actions ActionPublisherCreated AuditAction = "publisher.created" ActionPublisherUpdated AuditAction = "publisher.updated" @@ -49,14 +37,6 @@ const ( ActionMCPDeletionApproved AuditAction = "mcp_server.deletion_approved" ActionMCPDeletionRejected AuditAction = "mcp_server.deletion_rejected" - ActionAgentVersionSubmitted AuditAction = "agent_version.submitted" - ActionAgentVersionWithdrawn AuditAction = "agent_version.withdrawn" - ActionAgentVersionApproved AuditAction = "agent_version.approved" - ActionAgentVersionRejected AuditAction = "agent_version.rejected" - ActionAgentDeletionRequested AuditAction = "agent.deletion_requested" - ActionAgentDeletionApproved AuditAction = "agent.deletion_approved" - ActionAgentDeletionRejected AuditAction = "agent.deletion_rejected" - // Entry-change workflow actions. An Editor's visibility / deprecate / // metadata-edit request is now queued instead of applied immediately; a // Reviewer approves or rejects it. The concrete action and payload live in @@ -68,11 +48,6 @@ const ( ActionMCPChangeRejected AuditAction = "mcp_server.change_rejected" ActionMCPChangeWithdrawn AuditAction = "mcp_server.change_withdrawn" - ActionAgentChangeRequested AuditAction = "agent.change_requested" - ActionAgentChangeApproved AuditAction = "agent.change_approved" - ActionAgentChangeRejected AuditAction = "agent.change_rejected" - ActionAgentChangeWithdrawn AuditAction = "agent.change_withdrawn" - // RBAC actions. The security-sensitive mutations capture the // target principal / grant in the event metadata so "who granted whom what, // and when" is answerable from the log. @@ -94,7 +69,7 @@ type AuditEvent struct { ActorSubject string // Keycloak subject UUID ActorEmail string // human-readable identity Action AuditAction - ResourceType string // "mcp_server" | "agent" | "publisher" + ResourceType string // "mcp_server" | "publisher" ResourceID string // ULID of the mutated resource ResourceNS string // publisher slug ResourceSlug string // resource slug diff --git a/server/internal/domain/entrychange.go b/server/internal/domain/entrychange.go index c1a231a4..74489768 100644 --- a/server/internal/domain/entrychange.go +++ b/server/internal/domain/entrychange.go @@ -9,7 +9,6 @@ type EntryResourceType string const ( EntryResourceMCPServer EntryResourceType = "mcp_server" - EntryResourceAgent EntryResourceType = "agent" ) // EntryChangeAction names the entry-level mutation a change request will apply diff --git a/server/internal/domain/report.go b/server/internal/domain/report.go index 43811034..342f24a2 100644 --- a/server/internal/domain/report.go +++ b/server/internal/domain/report.go @@ -14,7 +14,7 @@ const ( // Report is a community-submitted issue report against a registry entry. type Report struct { ID string - ResourceType string // "mcp_server" | "agent" + ResourceType string // "mcp_server" ResourceID string // ResourceNS / ResourceSlug / ResourceName identify the reported entry in // human terms. Populated on admin list reads (joined from the entry diff --git a/server/internal/domain/url_test.go b/server/internal/domain/url_test.go index d403294e..61ed3d62 100644 --- a/server/internal/domain/url_test.go +++ b/server/internal/domain/url_test.go @@ -1,7 +1,6 @@ package domain_test import ( - "encoding/json" "strings" "testing" @@ -16,7 +15,7 @@ func TestValidateHTTPURL(t *testing.T) { }{ {name: "empty", input: ""}, {name: "https", input: "https://example.com/repo"}, - {name: "http with port", input: "http://localhost:8080/a2a"}, + {name: "http with port", input: "http://localhost:8080/mcp"}, {name: "uppercase scheme", input: "HTTPS://example.com"}, {name: "at max length", input: "https://example.com/" + strings.Repeat("a", domain.MaxURLLength-20)}, {name: "javascript", input: "javascript:alert(1)", wantErr: true}, @@ -44,43 +43,6 @@ func TestValidateHTTPURL(t *testing.T) { } } -func TestValidateAgentVersionURLs(t *testing.T) { - const ok = "https://example.com" - tests := []struct { - name string - endpoint, doc, icon string - provider string - wantField string - }{ - {name: "all valid", endpoint: ok, doc: ok, icon: ok, provider: `{"organization":"Acme","url":"https://acme.example"}`}, - {name: "optional empty", endpoint: ok}, - {name: "null provider", endpoint: ok, provider: `null`}, - {name: "bad endpoint", endpoint: "javascript:alert(1)", wantField: "endpoint_url"}, - {name: "bad documentation", endpoint: ok, doc: "data:text/html,x", wantField: "documentation_url"}, - {name: "bad icon", endpoint: ok, icon: "ftp://example.com/i.png", wantField: "icon_url"}, - {name: "bad provider url", endpoint: ok, provider: `{"url":"javascript:alert(1)"}`, wantField: "provider.url"}, - {name: "provider not an object", endpoint: ok, provider: `"acme"`, wantField: "provider"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var provider json.RawMessage - if tt.provider != "" { - provider = json.RawMessage(tt.provider) - } - err := domain.ValidateAgentVersionURLs(tt.endpoint, tt.doc, tt.icon, provider) - if tt.wantField == "" { - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - return - } - if err == nil || !strings.HasPrefix(err.Error(), tt.wantField+" ") { - t.Fatalf("error = %v, want one naming %s", err, tt.wantField) - } - }) - } -} - func TestValidateMCPServerURLs(t *testing.T) { if err := domain.ValidateMCPServerURLs("", ""); err != nil { t.Fatalf("empty links: %v", err) diff --git a/server/internal/http/handlers/activity.go b/server/internal/http/handlers/activity.go index 9fd09a34..f5e65478 100644 --- a/server/internal/http/handlers/activity.go +++ b/server/internal/http/handlers/activity.go @@ -1,7 +1,7 @@ // Package handlers — public per-resource activity feed. // -// These handlers power the public "Activity" tab on MCP server and agent -// detail pages. They return a privacy-scrubbed view of the underlying audit +// These handlers power the public "Activity" tab on MCP server detail +// pages. They return a privacy-scrubbed view of the underlying audit // log: actor identity (subject, email) is NEVER exposed, metadata is // whitelisted, and draft-only events are filtered out. // @@ -30,18 +30,11 @@ import ( // not leak their existence). .deleted is also excluded because a soft-deleted // resource returns 404 from the parent endpoint, so the event is unreachable. var publicActionWhitelist = map[domain.AuditAction]struct{}{ - // MCP domain.ActionMCPServerCreated: {}, domain.ActionMCPVersionPublished: {}, domain.ActionMCPServerDeprecated: {}, domain.ActionMCPServerVisibility: {}, domain.ActionMCPServerUpdated: {}, - // Agents - domain.ActionAgentCreated: {}, - domain.ActionAgentVersionPublished: {}, - domain.ActionAgentDeprecated: {}, - domain.ActionAgentVisibility: {}, - domain.ActionAgentUpdated: {}, } // publicMetadataAllowlist lists metadata keys that are safe to echo back on @@ -110,38 +103,18 @@ func (h *MCPHandlers) ListMCPServerActivity(w http.ResponseWriter, r *http.Reque return } - writePublicActivity(w, r, h.db, srv.ID, "mcp_server") + writePublicActivity(w, r, h.db, srv.ID) } -// ListAgentActivity handles GET /api/v1/agents/{namespace}/{slug}/activity. -func (h *AgentHandlers) ListAgentActivity(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - publicOnly := !canViewPrivate(r.Context(), h.db, ns) - ag, err := h.db.GetAgent(r.Context(), ns, slug, publicOnly) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - writePublicActivity(w, r, h.db, ag.ID, "agent") -} - -// writePublicActivity is the shared core of both activity endpoints. It pages -// through the audit_log filtered by resource ID, applies the action whitelist -// + metadata scrub, and emits PublicActivityEvent objects. +// writePublicActivity pages through the audit_log filtered by resource ID, +// applies the action whitelist + metadata scrub, and emits +// PublicActivityEvent objects. // // Because the whitelist can drop rows inside a page, we may deliver fewer than // `limit` items even when more rows exist upstream. That's fine — the cursor // reflects the last raw row scanned, so pagination is still consistent; the // client just needs to follow next_cursor if it wants more. -func writePublicActivity(w http.ResponseWriter, r *http.Request, db *store.DB, resourceID, resourceType string) { +func writePublicActivity(w http.ResponseWriter, r *http.Request, db *store.DB, resourceID string) { limit := int32(25) if l := r.URL.Query().Get("limit"); l != "" { if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 100 { @@ -150,7 +123,7 @@ func writePublicActivity(w http.ResponseWriter, r *http.Request, db *store.DB, r } p := store.ListAuditParams{ - ResourceType: resourceType, + ResourceType: "mcp_server", ResourceID: resourceID, Limit: limit + 1, // fetch one extra to detect next page Cursor: r.URL.Query().Get("cursor"), diff --git a/server/internal/http/handlers/activity_test.go b/server/internal/http/handlers/activity_test.go index d7e20ca4..ac65bcfd 100644 --- a/server/internal/http/handlers/activity_test.go +++ b/server/internal/http/handlers/activity_test.go @@ -15,15 +15,13 @@ import ( "github.com/haibread/ai-registry/internal/store" ) -// newActivityRouter builds a chi router wired for the public activity -// endpoints on both MCP and agents. Tests exercise the full handler +// newActivityRouter builds a chi router wired for the public MCP server +// activity endpoint. Tests exercise the full handler // behaviour (404 on missing resource, whitelist, scrub, pagination). func newActivityRouter() *chi.Mux { mcpH := handlers.NewMCPHandlers(testDB, testDB, nil) - agH := handlers.NewAgentHandlers(testDB, testDB, nil) r := chi.NewRouter() r.Get("/api/v1/mcp/servers/{namespace}/{slug}/activity", mcpH.ListMCPServerActivity) - r.Get("/api/v1/agents/{namespace}/{slug}/activity", agH.ListAgentActivity) return r } @@ -61,16 +59,6 @@ func resolveMCPServerID(t *testing.T, ns, slug string) string { return srv.ID } -// resolveAgentID looks up the ULID of a seeded agent. -func resolveAgentID(t *testing.T, ns, slug string) string { - t.Helper() - ag, err := testDB.GetAgent(context.Background(), ns, slug, false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - return ag.ID -} - // ─── MCP activity ─────────────────────────────────────────────────────────── func TestActivity_MCP_404_WhenServerDoesNotExist(t *testing.T) { @@ -316,81 +304,6 @@ func TestActivity_MCP_ScopedToResource(t *testing.T) { } } -// ─── Agent activity ───────────────────────────────────────────────────────── - -func TestActivity_Agent_404_WhenAgentDoesNotExist(t *testing.T) { - resetTables(t) - - req := httptest.NewRequest(http.MethodGet, - "/api/v1/agents/nope/missing/activity", nil) - rec := httptest.NewRecorder() - newActivityRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404", rec.Code) - } -} - -func TestActivity_Agent_ReturnsWhitelistedActions(t *testing.T) { - resetTables(t) - seedAgentPublic(t, "pub-ag", "ag-feed") - agID := resolveAgentID(t, "pub-ag", "ag-feed") - - logEventFor(t, "agent", agID, domain.ActionAgentCreated, nil) - logEventFor(t, "agent", agID, domain.ActionAgentVersionPublished, - map[string]any{"version": "0.1.0"}) - // Not whitelisted - logEventFor(t, "agent", agID, domain.ActionAgentVersionCreated, nil) - - req := httptest.NewRequest(http.MethodGet, - "/api/v1/agents/pub-ag/ag-feed/activity", nil) - rec := httptest.NewRecorder() - newActivityRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", rec.Code) - } - var body struct { - Items []struct { - Action string `json:"action"` - ActorRole string `json:"actor_role"` - Version string `json:"version"` - } `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 2 { - t.Fatalf("got %d whitelisted items, want 2", len(body.Items)) - } - for _, it := range body.Items { - if it.ActorRole != "admin" && it.ActorRole != "publisher" { - t.Errorf("actor_role = %q, want 'admin' or 'publisher'", it.ActorRole) - } - } -} - -func TestActivity_Agent_PrivacyScrub(t *testing.T) { - resetTables(t) - seedAgentPublic(t, "pub-agsc", "ag-sc") - agID := resolveAgentID(t, "pub-agsc", "ag-sc") - - logEventFor(t, "agent", agID, domain.ActionAgentCreated, nil) - - req := httptest.NewRequest(http.MethodGet, - "/api/v1/agents/pub-agsc/ag-sc/activity", nil) - rec := httptest.NewRecorder() - newActivityRouter().ServeHTTP(rec, req) - - raw := rec.Body.String() - for _, needle := range []string{ - "privileged@internal.example", "kc-subject-XYZ", - "actor_email", "actor_subject", - } { - if strings.Contains(raw, needle) { - t.Errorf("response leaked %q", needle) - } - } -} - // ─── Regression: list method signature ────────────────────────────────────── func TestActivity_ListAuditParams_WiresResourceFilter(t *testing.T) { diff --git a/server/internal/http/handlers/agent.go b/server/internal/http/handlers/agent.go deleted file mode 100644 index 56cb0773..00000000 --- a/server/internal/http/handlers/agent.go +++ /dev/null @@ -1,807 +0,0 @@ -package handlers - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/go-chi/chi/v5" - - "github.com/haibread/ai-registry/internal/auth" - "github.com/haibread/ai-registry/internal/domain" - "github.com/haibread/ai-registry/internal/observability" - "github.com/haibread/ai-registry/internal/problem" - "github.com/haibread/ai-registry/internal/store" -) - -// AgentHandlers holds dependencies for agent registry HTTP handlers. -type AgentHandlers struct { - db *store.DB - audit store.AuditLogger - metrics *observability.Metrics -} - -// NewAgentHandlers creates AgentHandlers with the given store, audit logger, and metrics. -func NewAgentHandlers(db *store.DB, audit store.AuditLogger, metrics *observability.Metrics) *AgentHandlers { - return &AgentHandlers{db: db, audit: audit, metrics: metrics} -} - -// ── GET /api/v1/agents ──────────────────────────────────────────────────── - -func (h *AgentHandlers) ListAgents(w http.ResponseWriter, r *http.Request) { - limit := int32(20) - if l := r.URL.Query().Get("limit"); l != "" { - n, err := strconv.Atoi(l) - if err == nil && n > 0 && n <= 100 { - limit = int32(n) - } - } - - // Validate optional enum filters — silently ignore unknown values. - status := r.URL.Query().Get("status") - if status != "draft" && status != "published" && status != "deprecated" { - status = "" - } - visibility := r.URL.Query().Get("visibility") - if visibility != "public" && visibility != "private" { - visibility = "" - } - sort := r.URL.Query().Get("sort") - if sort != "created_at_desc" && sort != "updated_at_desc" && sort != "published_at_desc" && sort != "name_asc" && sort != "name_desc" { - sort = "" - } - - var featured *bool - if fv := r.URL.Query().Get("featured"); fv == "true" { - t := true - featured = &t - } else if fv == "false" { - f := false - featured = &f - } - - var publishedSince *time.Time - if ps := r.URL.Query().Get("published_since"); ps != "" { - if t, err := time.Parse(time.RFC3339, ps); err == nil { - publishedSince = &t - } - } - - // mine=true scopes the listing to resources the caller can manage - // see ListServers for the full rationale. - publicOnly := !auth.IsAdminFromContext(r.Context()) - var publisherIDs []string - if r.URL.Query().Get("mine") == "true" { - ids, all, authed, err := mineScope(r.Context(), h.db) - if err != nil { - internalError(w, r, err) - return - } - if !authed { - problem.Write(w, http.StatusUnauthorized, "unauthorized", - "Authentication is required for mine=true.", r.URL.Path) - return - } - publicOnly = false - if !all { - if len(ids) == 0 { - writeJSON(w, r, http.StatusOK, map[string]any{ - "items": []map[string]any{}, "next_cursor": "", "total_count": 0, - }) - return - } - publisherIDs = ids - } - } - - rows, total, err := h.db.ListAgents(r.Context(), store.ListAgentsParams{ - PublicOnly: publicOnly, - PublisherIDs: publisherIDs, - Namespace: r.URL.Query().Get("namespace"), - Status: status, - Visibility: visibility, - Query: r.URL.Query().Get("q"), - Limit: limit + 1, - Cursor: r.URL.Query().Get("cursor"), - Sort: sort, - Featured: featured, - Tag: r.URL.Query().Get("tag"), - PublishedSince: publishedSince, - }) - if errors.Is(err, store.ErrInvalidCursor) { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", "invalid cursor", r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - var nextCursor string - if int32(len(rows)) > limit { - rows = rows[:limit] - last := rows[len(rows)-1] - cursorTime := last.CreatedAt - switch sort { - case "updated_at_desc": - cursorTime = last.UpdatedAt - case "published_at_desc": - if last.LatestVersion != nil && last.LatestVersion.PublishedAt != nil { - cursorTime = *last.LatestVersion.PublishedAt - } - } - nextCursor = store.EncodeCursor(cursorTime, last.ID) - } - - items := make([]map[string]any, 0, len(rows)) - for i := range rows { - items = append(items, agentToResponse(&rows[i])) - } - - writeJSON(w, r, http.StatusOK, map[string]any{ - "items": items, - "next_cursor": nextCursor, - "total_count": total, - }) -} - -// ── GET /api/v1/agents/{namespace}/{slug} ───────────────────────────────── - -func (h *AgentHandlers) GetAgent(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - publicOnly := !canViewPrivate(r.Context(), h.db, ns) - - agent, err := h.db.GetAgent(r.Context(), ns, slug, publicOnly) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - resp := agentToResponse(agent) - if !publicOnly { - if pc, ok := pendingChangeInfo(r.Context(), h.db, domain.EntryResourceAgent, agent.ID); ok { - resp["pending_change"] = pc - } - } - writeJSON(w, r, http.StatusOK, resp) -} - -// ── POST /api/v1/agents ─────────────────────────────────────────────────── - -func (h *AgentHandlers) CreateAgent(w http.ResponseWriter, r *http.Request) { - // Publisher-scoped authorization; the target publisher is in the - // body, so the role check is in-handler. Reject anonymous callers up front. - if !auth.IsAuthenticated(r.Context()) { - problem.Write(w, http.StatusUnauthorized, "unauthorized", - "Missing or invalid bearer token", r.URL.Path) - return - } - var body struct { - Namespace string `json:"namespace"` - Slug string `json:"slug"` - Name string `json:"name"` - Description string `json:"description"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Namespace == "" || body.Slug == "" || body.Name == "" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "namespace, slug, and name are required", r.URL.Path) - return - } - if err := domain.ValidateSlug(body.Namespace); err != nil { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - fmt.Sprintf("namespace: %s", err), r.URL.Path) - return - } - if err := domain.ValidateSlug(body.Slug); err != nil { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - fmt.Sprintf("slug: %s", err), r.URL.Path) - return - } - publisherID, err := h.db.GetPublisherBySlug(r.Context(), body.Namespace) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - fmt.Sprintf("publisher '%s' does not exist", body.Namespace), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - // Authoring requires Editor on the owning publisher (Admin / Server Admin - // satisfy it). New agents are created private + draft, so the approval gate - // (publish + admin visibility flip) stays intact. - ok, _, err := auth.CheckPublisherRole(r.Context(), h.db, publisherID, domain.RoleEditor) - if err != nil { - internalError(w, r, err) - return - } - if !ok { - problem.Write(w, http.StatusForbidden, "forbidden", - "Insufficient role on this publisher: editor required to author resources.", r.URL.Path) - return - } - - agent, err := h.db.CreateAgent(r.Context(), store.CreateAgentParams{ - PublisherID: publisherID, - Slug: body.Slug, - Name: body.Name, - Description: body.Description, - }) - if errors.Is(err, store.ErrConflict) { - problem.Write(w, http.StatusConflict, "conflict", - fmt.Sprintf("agent '%s/%s' already exists", body.Namespace, body.Slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentCreated, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: body.Namespace, ResourceSlug: body.Slug, - }) - if h.metrics != nil { - h.metrics.AgentsTotal.Add(r.Context(), 1) - } - writeJSON(w, r, http.StatusCreated, agent) -} - -// ── GET /api/v1/agents/{namespace}/{slug}/versions ──────────────────────── - -func (h *AgentHandlers) ListVersions(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - publicOnly := !canViewPrivate(r.Context(), h.db, ns) - - agent, err := h.db.GetAgent(r.Context(), ns, slug, publicOnly) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - versions, err := h.db.ListAgentVersions(r.Context(), agent.ID, publicOnly) - if err != nil { - internalError(w, r, err) - return - } - writeJSON(w, r, http.StatusOK, map[string]any{"items": versions}) -} - -// ── GET /api/v1/agents/{namespace}/{slug}/versions/{version} ────────────── - -func (h *AgentHandlers) GetVersion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ver := chi.URLParam(r, "version") - publicOnly := !canViewPrivate(r.Context(), h.db, ns) - - agent, err := h.db.GetAgent(r.Context(), ns, slug, publicOnly) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - v, err := h.db.GetAgentVersion(r.Context(), agent.ID, ver, publicOnly) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("version '%s' does not exist for %s/%s", ver, ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - writeJSON(w, r, http.StatusOK, v) -} - -// ── POST /api/v1/agents/{namespace}/{slug}/versions ─────────────────────── - -func (h *AgentHandlers) CreateVersion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - var body struct { - Version string `json:"version"` - EndpointURL string `json:"endpoint_url"` - Skills json.RawMessage `json:"skills"` - Capabilities json.RawMessage `json:"capabilities"` - Authentication json.RawMessage `json:"authentication"` - DefaultInputModes []string `json:"default_input_modes"` - DefaultOutputModes []string `json:"default_output_modes"` - Provider json.RawMessage `json:"provider"` - DocumentationURL string `json:"documentation_url"` - IconURL string `json:"icon_url"` - Tags []string `json:"tags"` - ProtocolVersion string `json:"protocol_version"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Version == "" || body.EndpointURL == "" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "version and endpoint_url are required", r.URL.Path) - return - } - if err := domain.ValidateAgentVersionURLs(body.EndpointURL, body.DocumentationURL, body.IconURL, body.Provider); err != nil { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", err.Error(), r.URL.Path) - return - } - if body.ProtocolVersion == "" { - body.ProtocolVersion = domain.A2AProtocolVersion - } - // skills is optional (see CreateAgentVersionRequest in openapi.yaml); only - // validate its structure when the caller actually supplied entries, mirroring - // how capabilities and authentication treat absent input as valid. - if len(body.Skills) > 0 { - if err := domain.ValidateSkills(body.Skills); err != nil { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", err.Error(), r.URL.Path) - return - } - } - if err := domain.ValidateAuthentication(body.Authentication); err != nil { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", err.Error(), r.URL.Path) - return - } - tags, ok := validateVersionTags(w, r, h.db, body.Tags) - if !ok { - return - } - - v, err := h.db.CreateAgentVersion(r.Context(), store.CreateAgentVersionParams{ - AgentID: agent.ID, - Version: body.Version, - EndpointURL: body.EndpointURL, - Skills: body.Skills, - Capabilities: body.Capabilities, - Authentication: body.Authentication, - DefaultInputModes: body.DefaultInputModes, - DefaultOutputModes: body.DefaultOutputModes, - Provider: body.Provider, - DocumentationURL: body.DocumentationURL, - IconURL: body.IconURL, - Tags: tags, - ProtocolVersion: body.ProtocolVersion, - }) - if errors.Is(err, store.ErrConflict) { - problem.Write(w, http.StatusConflict, "conflict", - fmt.Sprintf("version '%s' already exists for %s/%s", body.Version, ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentVersionCreated, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"version": body.Version}, - }) - writeJSON(w, r, http.StatusCreated, v) -} - -// ── POST /api/v1/agents/{namespace}/{slug}/versions/{version}/publish ───── - -func (h *AgentHandlers) PublishVersion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ver := chi.URLParam(r, "version") - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - if err := h.db.PublishAgentVersion(r.Context(), agent.ID, ver); errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("version '%s' does not exist", ver), r.URL.Path) - return - } else if errors.Is(err, store.ErrImmutable) { - problem.Write(w, http.StatusConflict, "immutable", - fmt.Sprintf("version '%s' is already published", ver), r.URL.Path) - return - } else if err != nil { - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentVersionPublished, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"version": ver}, - }) - writeJSON(w, r, http.StatusOK, map[string]string{"status": "published"}) -} - -// ── POST /api/v1/agents/{namespace}/{slug}/deprecate ────────────────────── - -func (h *AgentHandlers) DeprecateAgent(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - // Only a published entry can be deprecated; fail fast on both paths. - if agent.Status != domain.StatusPublished { - problem.Write(w, http.StatusConflict, "conflict", - fmt.Sprintf("agent '%s/%s' is not in published status", ns, slug), r.URL.Path) - return - } - - // Editors enqueue the deprecation for review; Server Admins apply immediately. - if !auth.IsServerAdminFromContext(r.Context()) { - enqueueEntryChange(w, r, h.db, h.audit, domain.EntryResourceAgent, agent.ID, ns, slug, - domain.EntryChangeDeprecation, map[string]any{}, domain.ActionAgentChangeRequested) - return - } - - if err := h.db.DeprecateAgent(r.Context(), agent.ID); errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusConflict, "conflict", - fmt.Sprintf("agent '%s/%s' is not in published status", ns, slug), r.URL.Path) - return - } else if err != nil { - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentDeprecated, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: ns, ResourceSlug: slug, - }) - writeJSON(w, r, http.StatusOK, map[string]string{"status": "deprecated"}) -} - -// ── POST /api/v1/agents/{namespace}/{slug}:undeprecate ─────────────────── - -func (h *AgentHandlers) UndeprecateAgent(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - // Only a deprecated entry can be republished; fail fast on both paths. - if agent.Status != domain.StatusDeprecated { - problem.Write(w, http.StatusConflict, "conflict", - fmt.Sprintf("agent '%s/%s' is not in deprecated status", ns, slug), r.URL.Path) - return - } - - // Editors enqueue the republish for review; Server Admins apply immediately. - if !auth.IsServerAdminFromContext(r.Context()) { - enqueueEntryChange(w, r, h.db, h.audit, domain.EntryResourceAgent, agent.ID, ns, slug, - domain.EntryChangeUndeprecation, map[string]any{}, domain.ActionAgentChangeRequested) - return - } - - if err := h.db.UndeprecateAgent(r.Context(), agent.ID); errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusConflict, "conflict", - fmt.Sprintf("agent '%s/%s' is not in deprecated status", ns, slug), r.URL.Path) - return - } else if err != nil { - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentUndeprecated, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: ns, ResourceSlug: slug, - }) - writeJSON(w, r, http.StatusOK, map[string]string{"status": "published"}) -} - -// ── PATCH /api/v1/agents/{namespace}/{slug} ─────────────────────────────── - -func (h *AgentHandlers) PatchAgent(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - var body struct { - Name *string `json:"name"` - Description *string `json:"description"` - } - if !decodeJSON(w, r, &body) { - return - } - - p := store.UpdateAgentParams{ - Name: agent.Name, - Description: agent.Description, - } - if body.Name != nil { - p.Name = *body.Name - } - if body.Description != nil { - p.Description = *body.Description - } - - if p.Name == "" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "name is required", r.URL.Path) - return - } - - // Editors enqueue the metadata edit for review; Server Admins apply now. - if !auth.IsServerAdminFromContext(r.Context()) { - enqueueEntryChange(w, r, h.db, h.audit, domain.EntryResourceAgent, agent.ID, ns, slug, - domain.EntryChangeMetadataEdit, p, domain.ActionAgentChangeRequested) - return - } - - updated, err := h.db.UpdateAgent(r.Context(), agent.ID, p) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentUpdated, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: ns, ResourceSlug: slug, - }) - writeJSON(w, r, http.StatusOK, agentToResponse(updated)) -} - -// ── DELETE /api/v1/agents/{namespace}/{slug} ────────────────────────────── - -func (h *AgentHandlers) DeleteAgent(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - if err := h.db.DeleteAgent(r.Context(), agent.ID); errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } else if err != nil { - internalError(w, r, err) - return - } - - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentDeleted, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: ns, ResourceSlug: slug, - }) - // Mirror the +1 in CreateAgent so the registry.agents.total - // UpDownCounter tracks the live count rather than monotonically inflating. - if h.metrics != nil { - h.metrics.AgentsTotal.Add(r.Context(), -1) - } - w.WriteHeader(http.StatusNoContent) -} - -// ── PATCH /api/v1/agents/{namespace}/{slug}/versions/{version}/status ──────── - -// PatchVersionStatus updates the lifecycle status of a specific agent version. -// Body: { "status": "active"|"deprecated"|"deleted", "statusMessage": "..." } -func (h *AgentHandlers) PatchVersionStatus(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ver := chi.URLParam(r, "version") - - var body struct { - Status string `json:"status"` - StatusMessage string `json:"statusMessage"` - } - if !decodeJSON(w, r, &body) { - return - } - - validStatuses := map[string]bool{"active": true, "deprecated": true, "deleted": true} - if !validStatuses[body.Status] { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "status must be one of: active, deprecated, deleted", r.URL.Path) - return - } - if body.Status == "active" && body.StatusMessage != "" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "statusMessage must not be set when status is active", r.URL.Path) - return - } - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - domainStatus := domain.VersionStatus(body.Status) - if err := h.db.SetAgentVersionStatus(r.Context(), agent.ID, ver, domainStatus, body.StatusMessage); errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("version '%s' does not exist", ver), r.URL.Path) - return - } else if err != nil { - internalError(w, r, err) - return - } - - // Admin-only handler: pass publicOnly=false so the read sees pending / - // non-published rows the admin just touched via PatchVersionStatus. - v, err := h.db.GetAgentVersion(r.Context(), agent.ID, ver, false) - if err != nil { - internalError(w, r, err) - return - } - - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentVersionPublished, ResourceType: "agent", - ResourceID: agent.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"version": ver, "status": body.Status}, - }) - writeJSON(w, r, http.StatusOK, v) -} - -// ── POST /api/v1/agents/{namespace}/{slug}/view ────────────────────────── - -func (h *AgentHandlers) RecordView(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - if err := h.db.IncrementAgentViewCount(r.Context(), ns, slug); err != nil { - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - internalError(w, r, err) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// ── POST /api/v1/agents/{namespace}/{slug}/copy ───────────────────────── - -func (h *AgentHandlers) RecordCopy(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - if err := h.db.IncrementAgentCopyCount(r.Context(), ns, slug); err != nil { - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - internalError(w, r, err) - return - } - w.WriteHeader(http.StatusNoContent) -} - -// ── helper ──────────────────────────────────────────────────────────────── - -func agentToResponse(a *store.AgentRow) map[string]any { - m := map[string]any{ - "id": a.ID, - "namespace": a.Namespace, - "slug": a.Slug, - "name": a.Name, - "description": a.Description, - "visibility": string(a.Visibility), - "status": string(a.Status), - "featured": a.Featured, - "verified": a.Verified, - "tags": a.Tags, - "readme": a.Readme, - "view_count": a.ViewCount, - "copy_count": a.CopyCount, - "created_at": a.CreatedAt.Format("2006-01-02T15:04:05Z07:00"), - "updated_at": a.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"), - } - if lv := a.LatestVersion; lv != nil { - // Never emit JSON null for an array field. - lvTags := lv.Tags - if lvTags == nil { - lvTags = []string{} - } - m["latest_version"] = map[string]any{ - "version": lv.Version, - "endpoint_url": lv.EndpointURL, - "skills": lv.Skills, - "default_input_modes": lv.DefaultInputModes, - "default_output_modes": lv.DefaultOutputModes, - "authentication": lv.Authentication, - "protocol_version": lv.ProtocolVersion, - "tags": lvTags, - "published_at": lv.PublishedAt, - } - } - return m -} diff --git a/server/internal/http/handlers/agent_test.go b/server/internal/http/handlers/agent_test.go deleted file mode 100644 index 797f17e2..00000000 --- a/server/internal/http/handlers/agent_test.go +++ /dev/null @@ -1,1067 +0,0 @@ -package handlers_test - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-chi/chi/v5" - - "github.com/haibread/ai-registry/internal/auth" - "github.com/haibread/ai-registry/internal/http/handlers" - "github.com/haibread/ai-registry/internal/store" -) - -// validSkills is a well-formed skills JSON used in agent version tests. -var validSkills = json.RawMessage(`[{"id":"s1","name":"Search","description":"Searches things","tags":["search"]}]`) - -func newAgentRouter() *chi.Mux { - h := handlers.NewAgentHandlers(testDB, testDB, nil) - r := chi.NewRouter() - r.Get("/api/v1/agents", h.ListAgents) - r.Post("/api/v1/agents", h.CreateAgent) - r.Get("/api/v1/agents/{namespace}/{slug}", h.GetAgent) - r.Patch("/api/v1/agents/{namespace}/{slug}", h.PatchAgent) - r.Delete("/api/v1/agents/{namespace}/{slug}", h.DeleteAgent) - r.Get("/api/v1/agents/{namespace}/{slug}/versions", h.ListVersions) - r.Post("/api/v1/agents/{namespace}/{slug}/versions", h.CreateVersion) - r.Get("/api/v1/agents/{namespace}/{slug}/versions/{version}", h.GetVersion) - r.Post("/api/v1/agents/{namespace}/{slug}/versions/{version}/publish", h.PublishVersion) - r.Patch("/api/v1/agents/{namespace}/{slug}/versions/{version}/status", h.PatchVersionStatus) - r.Post("/api/v1/agents/{namespace}/{slug}/deprecate", h.DeprecateAgent) - r.Post("/api/v1/agents/{namespace}/{slug}/visibility", h.SetVisibility) - r.Post("/api/v1/agents/{namespace}/{slug}/view", h.RecordView) - r.Post("/api/v1/agents/{namespace}/{slug}/copy", h.RecordCopy) - return r -} - -// adminAgentCtx returns a context with a Server Admin principal for agent tests. -func adminAgentCtx() context.Context { - return auth.ContextWithPrincipal(context.Background(), &auth.Principal{IsServerAdmin: true}) -} - -// seedAgent creates a publisher + agent row and returns the agent. -func seedAgent(t *testing.T, ns, slug string) { - t.Helper() - pubID := seedPublisher(t, ns, ns) - _, err := testDB.CreateAgent(context.Background(), store.CreateAgentParams{ - PublisherID: pubID, - Slug: slug, - Name: slug, - }) - if err != nil { - t.Fatalf("seedAgent(%q/%q): %v", ns, slug, err) - } -} - -// seedAgentPublic creates a public agent. -func seedAgentPublic(t *testing.T, ns, slug string) { - t.Helper() - seedAgent(t, ns, slug) - ag, err := testDB.GetAgent(context.Background(), ns, slug, false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if err := testDB.SetAgentVisibility(context.Background(), ag.ID, "public"); err != nil { - t.Fatalf("SetAgentVisibility: %v", err) - } -} - -// createAgentVersion inserts a draft agent version. -func createAgentVersion(t *testing.T, ns, slug, ver string) { - t.Helper() - ag, err := testDB.GetAgent(context.Background(), ns, slug, false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - _, err = testDB.CreateAgentVersion(context.Background(), store.CreateAgentVersionParams{ - AgentID: ag.ID, - Version: ver, - EndpointURL: "https://example.com/agent", - Skills: validSkills, - }) - if err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } -} - -// ─── ListAgents ───────────────────────────────────────────────────────────── - -func TestAgentHandler_ListAgents_EmptyList(t *testing.T) { - resetTables(t) - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", rec.Code) - } - var body struct { - Items []any `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if body.Items == nil { - t.Error("items should be empty array, not null") - } - if len(body.Items) != 0 { - t.Errorf("expected 0 items, got %d", len(body.Items)) - } -} - -func TestAgentHandler_ListAgents_WithAgents(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-pub", "agent-a") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", rec.Code) - } - var body struct { - Items []struct { - Slug string `json:"slug"` - } `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 1 { - t.Errorf("expected 1 item, got %d", len(body.Items)) - } -} - -func TestAgentHandler_ListAgents_PublicOnlyFilter(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-vis1", "private-ag") // private by default - seedAgentPublic(t, "ag-vis2", "public-ag") - - // Unauthenticated — sees only public - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - var body struct { - Items []struct { - Slug string `json:"slug"` - } `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 1 { - t.Errorf("public-only: expected 1 item, got %d", len(body.Items)) - } - if body.Items[0].Slug != "public-ag" { - t.Errorf("expected public-ag, got %q", body.Items[0].Slug) - } - - // Admin — sees all - req = httptest.NewRequest(http.MethodGet, "/api/v1/agents", nil) - req = req.WithContext(adminAgentCtx()) - rec = httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 2 { - t.Errorf("admin: expected 2 items, got %d", len(body.Items)) - } -} - -// ─── GetAgent ─────────────────────────────────────────────────────────────── - -func TestAgentHandler_GetAgent_Found(t *testing.T) { - resetTables(t) - seedAgentPublic(t, "ag-get", "my-agent") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-get/my-agent", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body struct { - Slug string `json:"slug"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if body.Slug != "my-agent" { - t.Errorf("slug = %q, want my-agent", body.Slug) - } -} - -func TestAgentHandler_GetAgent_NotFound(t *testing.T) { - resetTables(t) - seedPublisher(t, "ag-nf", "ag-nf") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-nf/nope", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -func TestAgentHandler_GetAgent_PrivateHiddenFromPublic(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-priv", "hidden-ag") // private by default - - // Unauthenticated - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-priv/hidden-ag", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNotFound { - t.Errorf("unauthenticated: status = %d, want 404", rec.Code) - } - - // Admin can see it - req = httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-priv/hidden-ag", nil) - req = req.WithContext(adminAgentCtx()) - rec = httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Errorf("admin: status = %d, want 200", rec.Code) - } -} - -// ─── CreateAgent ──────────────────────────────────────────────────────────── - -func TestAgentHandler_CreateAgent_Valid(t *testing.T) { - resetTables(t) - seedPublisher(t, "ag-create-ns", "Create NS") - - payload := `{"namespace":"ag-create-ns","slug":"new-ag","name":"New Agent"}` - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents", - bytes.NewBufferString(payload)).WithContext(adminCtx()) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusCreated { - t.Fatalf("status = %d, want 201; body: %s", rec.Code, rec.Body.String()) - } - var body struct { - ID string `json:"id"` - Slug string `json:"slug"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if body.ID == "" { - t.Error("expected non-empty id") - } - if body.Slug != "new-ag" { - t.Errorf("slug = %q, want new-ag", body.Slug) - } -} - -func TestAgentHandler_CreateAgent_MissingFields(t *testing.T) { - resetTables(t) - - tests := []struct { - name string - payload string - }{ - {"missing namespace", `{"slug":"s","name":"N"}`}, - {"missing slug", `{"namespace":"ns","name":"N"}`}, - {"missing name", `{"namespace":"ns","slug":"s"}`}, - {"invalid JSON", `{bad}`}, - } - - r := newAgentRouter() - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents", - bytes.NewBufferString(tt.payload)).WithContext(adminCtx()) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - r.ServeHTTP(rec, req) - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("status = %d, want 422", rec.Code) - } - }) - } -} - -// TestAgentHandler_CreateAgent_ForbiddenWithoutEditor verifies an authenticated -// caller with no Editor role on the target publisher gets 403. -func TestAgentHandler_CreateAgent_ForbiddenWithoutEditor(t *testing.T) { - resetTables(t) - seedPublisher(t, "ag-locked-ns", "Locked NS") - - ctx := auth.ContextWithClaims(context.Background(), &auth.OIDCClaims{ - Groups: []string{"randos"}, - }) - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents", - bytes.NewBufferString(`{"namespace":"ag-locked-ns","slug":"nope","name":"Nope"}`)).WithContext(ctx) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusForbidden { - t.Errorf("status = %d, want 403; body: %s", rec.Code, rec.Body.String()) - } -} - -func TestAgentHandler_CreateAgent_DuplicateSlug(t *testing.T) { - resetTables(t) - seedPublisher(t, "ag-dup-ns", "Dup NS") - - payload := `{"namespace":"ag-dup-ns","slug":"dup-ag","name":"Dup"}` - post := func() int { - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents", - bytes.NewBufferString(payload)).WithContext(adminCtx()) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - return rec.Code - } - - if code := post(); code != http.StatusCreated { - t.Fatalf("first create: %d", code) - } - if code := post(); code != http.StatusConflict { - t.Errorf("duplicate: %d, want 409", code) - } -} - -// ─── ListVersions ─────────────────────────────────────────────────────────── - -func TestAgentHandler_ListVersions_Empty(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-lv", "ag-lv") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-lv/ag-lv/versions", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", rec.Code) - } - var body struct { - Items []any `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 0 { - t.Errorf("expected 0 versions, got %d", len(body.Items)) - } -} - -func TestAgentHandler_ListVersions_WithVersions(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-lvv", "ag-lvv") - createAgentVersion(t, "ag-lvv", "ag-lvv", "1.0.0") - createAgentVersion(t, "ag-lvv", "ag-lvv", "2.0.0") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-lvv/ag-lvv/versions", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", rec.Code) - } - var body struct { - Items []struct { - Version string `json:"version"` - } `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 2 { - t.Errorf("expected 2 versions, got %d", len(body.Items)) - } -} - -// ─── GetVersion ───────────────────────────────────────────────────────────── - -func TestAgentHandler_GetVersion_Found(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-gv", "ag-gv") - createAgentVersion(t, "ag-gv", "ag-gv", "1.0.0") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-gv/ag-gv/versions/1.0.0", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body struct { - Version string `json:"version"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if body.Version != "1.0.0" { - t.Errorf("version = %q, want 1.0.0", body.Version) - } -} - -func TestAgentHandler_GetVersion_NotFound(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-gvnf", "ag-gvnf") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/ag-gvnf/ag-gvnf/versions/99.0.0", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -// ─── CreateVersion ────────────────────────────────────────────────────────── - -func TestAgentHandler_CreateVersion_Valid(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-cv", "ag-cv") - - body := map[string]any{ - "version": "1.0.0", - "endpoint_url": "https://example.com/agent", - "skills": validSkills, - } - b, _ := json.Marshal(body) - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-cv/ag-cv/versions", - bytes.NewBuffer(b)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusCreated { - t.Fatalf("status = %d, want 201; body: %s", rec.Code, rec.Body.String()) - } - var resp struct { - Version string `json:"version"` - } - json.NewDecoder(rec.Body).Decode(&resp) //nolint:errcheck - if resp.Version != "1.0.0" { - t.Errorf("version = %q, want 1.0.0", resp.Version) - } -} - -// TestAgentHandler_CreateVersion_NoSkills verifies that skills is optional: -// a version created without any skill entries (e.g. via the admin "new agent" -// form with the skill section left blank) succeeds rather than failing 422. -// Regression test for the "Agent created, but version creation failed" bug. -func TestAgentHandler_CreateVersion_NoSkills(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-cvns", "ag-cvns") - - body := map[string]any{ - "version": "1.0.0", - "endpoint_url": "https://example.com/agent", - } - b, _ := json.Marshal(body) - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-cvns/ag-cvns/versions", - bytes.NewBuffer(b)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusCreated { - t.Fatalf("status = %d, want 201; body: %s", rec.Code, rec.Body.String()) - } -} - -func TestAgentHandler_CreateVersion_MissingFields(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-cvmf", "ag-cvmf") - - tests := []struct { - name string - payload string - }{ - {"missing version", `{"endpoint_url":"https://example.com","skills":[{"id":"s1","name":"S","description":"D","tags":[]}]}`}, - {"missing endpoint_url", `{"version":"1.0.0","skills":[{"id":"s1","name":"S","description":"D","tags":[]}]}`}, - } - - r := newAgentRouter() - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-cvmf/ag-cvmf/versions", - bytes.NewBufferString(tt.payload)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - r.ServeHTTP(rec, req) - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("%s: status = %d, want 422", tt.name, rec.Code) - } - }) - } -} - -func TestAgentHandler_CreateVersion_InvalidSkills(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-cvbs", "ag-cvbs") - - // Skills missing required fields - payload := `{"version":"1.0.0","endpoint_url":"https://example.com","skills":[{"id":"","name":"","description":"","tags":[]}]}` - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-cvbs/ag-cvbs/versions", - bytes.NewBufferString(payload)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("status = %d, want 422", rec.Code) - } -} - -func TestAgentHandler_CreateVersion_InvalidAuthentication(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-cvba", "ag-cvba") - - // Auth with invalid scheme - payload := `{"version":"1.0.0","endpoint_url":"https://example.com","skills":[{"id":"s1","name":"S","description":"D","tags":[]}],"authentication":[{"scheme":"UnknownScheme"}]}` - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-cvba/ag-cvba/versions", - bytes.NewBufferString(payload)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("status = %d, want 422", rec.Code) - } -} - -// ─── PublishVersion ───────────────────────────────────────────────────────── - -func TestAgentHandler_PublishVersion_Success(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-pv", "ag-pv") - createAgentVersion(t, "ag-pv", "ag-pv", "1.0.0") - - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-pv/ag-pv/versions/1.0.0/publish", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body map[string]string - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if body["status"] != "published" { - t.Errorf("status = %q, want published", body["status"]) - } -} - -func TestAgentHandler_PublishVersion_NotFound(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-pvnf", "ag-pvnf") - - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-pvnf/ag-pvnf/versions/99.0.0/publish", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -func TestAgentHandler_PublishVersion_AlreadyPublished(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-pvap", "ag-pvap") - createAgentVersion(t, "ag-pvap", "ag-pvap", "1.0.0") - - r := newAgentRouter() - - publish := func() int { - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-pvap/ag-pvap/versions/1.0.0/publish", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - r.ServeHTTP(rec, req) - return rec.Code - } - - if code := publish(); code != http.StatusOK { - t.Fatalf("first publish: %d", code) - } - if code := publish(); code != http.StatusConflict { - t.Errorf("second publish: %d, want 409", code) - } -} - -// ─── DeprecateAgent ───────────────────────────────────────────────────────── - -func TestAgentHandler_DeprecateAgent_Success(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-dep", "ag-dep") - createAgentVersion(t, "ag-dep", "ag-dep", "1.0.0") - - r := newAgentRouter() - - // Publish first - pubReq := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-dep/ag-dep/versions/1.0.0/publish", nil) - pubReq = pubReq.WithContext(adminAgentCtx()) - pubRec := httptest.NewRecorder() - r.ServeHTTP(pubRec, pubReq) - if pubRec.Code != http.StatusOK { - t.Fatalf("publish: status = %d", pubRec.Code) - } - - // Deprecate - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-dep/ag-dep/deprecate", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - r.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body map[string]string - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if body["status"] != "deprecated" { - t.Errorf("status = %q, want deprecated", body["status"]) - } -} - -func TestAgentHandler_DeprecateAgent_NotPublished(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-depnp", "ag-depnp") // draft, not published - - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/ag-depnp/ag-depnp/deprecate", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusConflict { - t.Errorf("status = %d, want 409", rec.Code) - } -} - -// ─── Status / Visibility filter tests ────────────────────────────────────── - -func TestAgentHandler_List_FilterByStatus(t *testing.T) { - resetTables(t) - - seedAgent(t, "agfst-ns1", "agfst-draft") - seedAgentPublished(t, "agfst-ns2", "agfst-pub-1") - seedAgentPublished(t, "agfst-ns3", "agfst-pub-2") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents?status=published", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body struct { - Items []struct { - Slug string `json:"slug"` - Status string `json:"status"` - } `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 2 { - t.Errorf("status=published: got %d items, want 2", len(body.Items)) - } - for _, item := range body.Items { - if item.Status != "published" { - t.Errorf("expected status=published, got %q for slug %q", item.Status, item.Slug) - } - } -} - -func TestAgentHandler_List_FilterByVisibility(t *testing.T) { - resetTables(t) - - seedAgent(t, "agfvis-ns1", "agfvis-private") - seedAgentPublic(t, "agfvis-ns2", "agfvis-public") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents?visibility=private", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body struct { - Items []struct { - Slug string `json:"slug"` - Visibility string `json:"visibility"` - } `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 1 { - t.Errorf("visibility=private: got %d items, want 1", len(body.Items)) - } - if len(body.Items) > 0 && body.Items[0].Slug != "agfvis-private" { - t.Errorf("visibility=private: slug=%q, want agfvis-private", body.Items[0].Slug) - } -} - -func TestAgentHandler_List_InvalidFilterIgnored(t *testing.T) { - resetTables(t) - seedAgent(t, "aginv-ns1", "aginv-ag-1") - seedAgent(t, "aginv-ns2", "aginv-ag-2") - - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents?status=badvalue&visibility=garbage", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body struct { - Items []any `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 2 { - t.Errorf("invalid filters ignored: got %d items, want 2", len(body.Items)) - } -} - -// seedAgentPublished creates an agent and promotes its status to published via SQL. -func seedAgentPublished(t *testing.T, ns, slug string) { - t.Helper() - seedAgent(t, ns, slug) - ag, err := testDB.GetAgent(context.Background(), ns, slug, false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if _, err := testDB.Pool.Exec(context.Background(), "UPDATE agents SET status=$1 WHERE id=$2", "published", ag.ID); err != nil { - t.Fatalf("seedAgentPublished: %v", err) - } -} - -func TestAgentHandler_ListAgents_TotalCount(t *testing.T) { - resetTables(t) - // Seed 3 agents under the same publisher. - pubID := seedPublisher(t, "atc-pub", "ATC Pub") - for i := range 3 { - _, err := testDB.CreateAgent(context.Background(), store.CreateAgentParams{ - PublisherID: pubID, - Slug: fmt.Sprintf("atc-ag-%d", i), - Name: fmt.Sprintf("ATC Agent %d", i), - }) - if err != nil { - t.Fatalf("creating agent %d: %v", i, err) - } - } - - // Ask for page of 2 — items should have 2, but total_count should be 3. - req := httptest.NewRequest(http.MethodGet, "/api/v1/agents?limit=2", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", rec.Code) - } - var body struct { - Items []any `json:"items"` - TotalCount int `json:"total_count"` - } - if err := json.NewDecoder(rec.Body).Decode(&body); err != nil { - t.Fatalf("decode: %v", err) - } - if len(body.Items) != 2 { - t.Errorf("items length: got %d, want 2", len(body.Items)) - } - if body.TotalCount != 3 { - t.Errorf("total_count: got %d, want 3", body.TotalCount) - } -} - -func TestAgentHandler_PatchAgent_Success(t *testing.T) { - resetTables(t) - seedAgent(t, "patch-ns", "patch-agent") - - payload := `{"name":"New Name","description":"New desc"}` - req := httptest.NewRequest(http.MethodPatch, "/api/v1/agents/patch-ns/patch-agent", - bytes.NewBufferString(payload)) - req = req.WithContext(adminAgentCtx()) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var ag struct { - Name string `json:"name"` - Description string `json:"description"` - } - if err := json.NewDecoder(rec.Body).Decode(&ag); err != nil { - t.Fatalf("decode: %v", err) - } - if ag.Name != "New Name" { - t.Errorf("name = %q, want %q", ag.Name, "New Name") - } -} - -func TestAgentHandler_PatchAgent_NotFound(t *testing.T) { - resetTables(t) - req := httptest.NewRequest(http.MethodPatch, "/api/v1/agents/ns/missing", - bytes.NewBufferString(`{"name":"X"}`)) - req = req.WithContext(adminAgentCtx()) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -func TestAgentHandler_PatchAgent_NameRequired(t *testing.T) { - resetTables(t) - seedAgent(t, "val-ns", "val-agent") - - req := httptest.NewRequest(http.MethodPatch, "/api/v1/agents/val-ns/val-agent", - bytes.NewBufferString(`{"name":""}`)) - req = req.WithContext(adminAgentCtx()) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("status = %d, want 422", rec.Code) - } -} - -func TestAgentHandler_DeleteAgent_Success(t *testing.T) { - resetTables(t) - seedAgent(t, "del-ns", "del-agent") - - req := httptest.NewRequest(http.MethodDelete, "/api/v1/agents/del-ns/del-agent", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNoContent { - t.Fatalf("status = %d, want 204; body: %s", rec.Code, rec.Body.String()) - } - - // No longer in public listing. - req = httptest.NewRequest(http.MethodGet, "/api/v1/agents", nil) - rec = httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - var body struct { - Items []any `json:"items"` - } - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if len(body.Items) != 0 { - t.Errorf("expected empty list after delete, got %d items", len(body.Items)) - } -} - -func TestAgentHandler_DeleteAgent_NotFound(t *testing.T) { - resetTables(t) - req := httptest.NewRequest(http.MethodDelete, "/api/v1/agents/ns/missing", nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -// ─── RecordView / RecordCopy ─────────────────────────────────────────────── - -func TestAgentHandler_RecordView_OK(t *testing.T) { - resetTables(t) - seedAgent(t, "rv-ag-ns", "rv-ag") - - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/rv-ag-ns/rv-ag/view", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNoContent { - t.Fatalf("status = %d, want 204; body: %s", rec.Code, rec.Body.String()) - } - - got, err := testDB.GetAgent(context.Background(), "rv-ag-ns", "rv-ag", false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if got.ViewCount != 1 { - t.Errorf("view_count = %d, want 1", got.ViewCount) - } - if got.CopyCount != 0 { - t.Errorf("copy_count = %d, want 0 (view must not touch copy)", got.CopyCount) - } -} - -func TestAgentHandler_RecordView_NotFound(t *testing.T) { - resetTables(t) - seedPublisher(t, "rv-ag-nf", "rv-ag-nf") - - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/rv-ag-nf/missing/view", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -func TestAgentHandler_RecordCopy_OK(t *testing.T) { - resetTables(t) - seedAgent(t, "rc-ag-ns", "rc-ag") - - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/rc-ag-ns/rc-ag/copy", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNoContent { - t.Fatalf("status = %d, want 204; body: %s", rec.Code, rec.Body.String()) - } - - got, err := testDB.GetAgent(context.Background(), "rc-ag-ns", "rc-ag", false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if got.CopyCount != 1 { - t.Errorf("copy_count = %d, want 1", got.CopyCount) - } - if got.ViewCount != 0 { - t.Errorf("view_count = %d, want 0 (copy must not touch view)", got.ViewCount) - } -} - -func TestAgentHandler_RecordCopy_NotFound(t *testing.T) { - resetTables(t) - - req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/nope/nope/copy", nil) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -// ─── PatchVersionStatus ──────────────────────────────────────────────────── - -// seedPublishedAgentVersion creates an agent, a draft version, and publishes it. -func seedPublishedAgentVersion(t *testing.T, ns, slug, ver string) { - t.Helper() - seedAgent(t, ns, slug) - createAgentVersion(t, ns, slug, ver) - - r := newAgentRouter() - url := fmt.Sprintf("/api/v1/agents/%s/%s/versions/%s/publish", ns, slug, ver) - req := httptest.NewRequest(http.MethodPost, url, nil) - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - r.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("seedPublishedAgentVersion publish: %d; body: %s", rec.Code, rec.Body.String()) - } -} - -func TestAgentHandler_PatchVersionStatus_Deprecate(t *testing.T) { - resetTables(t) - seedPublishedAgentVersion(t, "ag-pvs", "ag-pvs", "1.0.0") - - body, _ := json.Marshal(map[string]string{ - "status": "deprecated", - "statusMessage": "use 2.x", - }) - req := httptest.NewRequest(http.MethodPatch, - "/api/v1/agents/ag-pvs/ag-pvs/versions/1.0.0/status", - bytes.NewBuffer(body)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var resp struct { - Status string `json:"status"` - StatusMessage string `json:"status_message"` - } - if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { - t.Fatalf("decode: %v", err) - } - if resp.Status != "deprecated" { - t.Errorf("status = %q, want deprecated", resp.Status) - } - if resp.StatusMessage != "use 2.x" { - t.Errorf("status_message = %q, want %q", resp.StatusMessage, "use 2.x") - } -} - -func TestAgentHandler_PatchVersionStatus_InvalidStatus(t *testing.T) { - resetTables(t) - seedPublishedAgentVersion(t, "ag-pvs-inv", "ag-pvs-inv", "1.0.0") - - body, _ := json.Marshal(map[string]string{"status": "bogus"}) - req := httptest.NewRequest(http.MethodPatch, - "/api/v1/agents/ag-pvs-inv/ag-pvs-inv/versions/1.0.0/status", - bytes.NewBuffer(body)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("status = %d, want 422", rec.Code) - } -} - -func TestAgentHandler_PatchVersionStatus_ActiveWithMessageRejected(t *testing.T) { - resetTables(t) - seedPublishedAgentVersion(t, "ag-pvs-am", "ag-pvs-am", "1.0.0") - - body, _ := json.Marshal(map[string]string{ - "status": "active", - "statusMessage": "should not be set", - }) - req := httptest.NewRequest(http.MethodPatch, - "/api/v1/agents/ag-pvs-am/ag-pvs-am/versions/1.0.0/status", - bytes.NewBuffer(body)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("status = %d, want 422", rec.Code) - } -} - -func TestAgentHandler_PatchVersionStatus_VersionNotFound(t *testing.T) { - resetTables(t) - seedPublishedAgentVersion(t, "ag-pvs-nf", "ag-pvs-nf", "1.0.0") - - body, _ := json.Marshal(map[string]string{"status": "deprecated"}) - req := httptest.NewRequest(http.MethodPatch, - "/api/v1/agents/ag-pvs-nf/ag-pvs-nf/versions/9.9.9/status", - bytes.NewBuffer(body)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -func TestAgentHandler_PatchVersionStatus_AgentNotFound(t *testing.T) { - resetTables(t) - // No agent seeded at all. - - body, _ := json.Marshal(map[string]string{"status": "deprecated"}) - req := httptest.NewRequest(http.MethodPatch, - "/api/v1/agents/ghost-ns/ghost-ag/versions/1.0.0/status", - bytes.NewBuffer(body)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} diff --git a/server/internal/http/handlers/agentcard.go b/server/internal/http/handlers/agentcard.go deleted file mode 100644 index 41aa4ce3..00000000 --- a/server/internal/http/handlers/agentcard.go +++ /dev/null @@ -1,84 +0,0 @@ -package handlers - -import ( - "errors" - "fmt" - "log/slog" - "net/http" - - "github.com/go-chi/chi/v5" - - "github.com/haibread/ai-registry/internal/agents" - "github.com/haibread/ai-registry/internal/problem" - "github.com/haibread/ai-registry/internal/store" -) - -// AgentCardHandlers serves A2A Agent Card endpoints. -type AgentCardHandlers struct { - db *store.DB - logger *slog.Logger - publicBaseURL string -} - -// NewAgentCardHandlers creates AgentCardHandlers. publicBaseURL comes from -// the config layer (env + YAML + default per CLAUDE.md); empty triggers a -// 500 in GlobalAgentCard rather than silently advertising localhost. -func NewAgentCardHandlers(db *store.DB, logger *slog.Logger, publicBaseURL string) *AgentCardHandlers { - return &AgentCardHandlers{db: db, logger: logger, publicBaseURL: publicBaseURL} -} - -// PerAgentCard serves GET /agents/{namespace}/{slug}/.well-known/agent-card.json -// Returns the A2A-compatible agent card for the named agent's latest published version. -func (h *AgentCardHandlers) PerAgentCard(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - agent, err := h.db.GetAgent(r.Context(), ns, slug, true) // public only - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist or is not public", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - ver, err := h.db.GetLatestPublishedAgentVersion(r.Context(), agent.ID) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' has no published version", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - card, err := agents.GenerateCard(*agent, ver) - if err != nil { - internalError(w, r, err) - return - } - - writeJSON(w, r, http.StatusOK, card) -} - -// GlobalAgentCard serves GET /.well-known/agent-card.json for the registry itself. -// Makes the registry a first-class A2A citizen. -// -// PublicBaseURL (config layer: env + YAML + default) must be set in production. -// If it is empty, this handler returns HTTP 500 so misconfigured deployments -// fail loudly rather than silently advertising a localhost URL to external -// consumers. -func (h *AgentCardHandlers) GlobalAgentCard(w http.ResponseWriter, r *http.Request) { - if h.publicBaseURL == "" { - h.logger.ErrorContext(r.Context(), - "PUBLIC_BASE_URL is not set; cannot generate a valid global agent card", - ) - problem.Write(w, http.StatusInternalServerError, "misconfiguration", - "PUBLIC_BASE_URL is not set", r.URL.Path) - return - } - writeJSON(w, r, http.StatusOK, agents.RegistryCard(h.publicBaseURL)) -} diff --git a/server/internal/http/handlers/agentcard_test.go b/server/internal/http/handlers/agentcard_test.go deleted file mode 100644 index 7b05b107..00000000 --- a/server/internal/http/handlers/agentcard_test.go +++ /dev/null @@ -1,384 +0,0 @@ -package handlers_test - -import ( - "bytes" - "context" - "encoding/json" - "log/slog" - "net/http" - "net/http/httptest" - "strings" - "sync" - "testing" - - "github.com/go-chi/chi/v5" - "github.com/santhosh-tekuri/jsonschema/v5" - - "github.com/haibread/ai-registry/api" - "github.com/haibread/ai-registry/internal/http/handlers" - "github.com/haibread/ai-registry/internal/store" -) - -// newAgentCardRouter builds a router with a configurable publicBaseURL so -// individual tests can pin a deterministic value or pass "" to exercise the -// fail-loud branch. Replaces the older PUBLIC_BASE_URL env-var injection now -// that the handler reads from the config layer. -func newAgentCardRouter(publicBaseURL string) *chi.Mux { - h := handlers.NewAgentCardHandlers(testDB, slog.Default(), publicBaseURL) - r := chi.NewRouter() - r.Get("/agents/{namespace}/{slug}/.well-known/agent-card.json", h.PerAgentCard) - r.Get("/.well-known/agent-card.json", h.GlobalAgentCard) - return r -} - -// ─── A2A JSON Schema conformance ──────────────────────────────────────────── -// -// The A2A Agent Card shape is pinned to the A2A specification as of June -// 2025. The schema file at server/api/a2a-agent-card.schema.json is the -// machine-checkable version of that pin — any regression in -// internal/agents/card.go that drops a required field, mis-types a capability -// flag, or emits a security scheme outside the allowed four types will fail -// validation here. - -var ( - a2aSchemaOnce sync.Once - a2aSchema *jsonschema.Schema - a2aSchemaErr error -) - -// loadA2ASchema compiles the embedded A2A Agent Card JSON Schema exactly once -// per test binary. Compilation failures (malformed schema) are surfaced as a -// test failure on first use rather than at package init so a broken schema -// does not wedge unrelated tests. -func loadA2ASchema(t *testing.T) *jsonschema.Schema { - t.Helper() - a2aSchemaOnce.Do(func() { - compiler := jsonschema.NewCompiler() - const url = "a2a-agent-card.schema.json" - if err := compiler.AddResource(url, bytes.NewReader(api.A2AAgentCardSchema)); err != nil { - a2aSchemaErr = err - return - } - a2aSchema, a2aSchemaErr = compiler.Compile(url) - }) - if a2aSchemaErr != nil { - t.Fatalf("compiling embedded A2A schema: %v", a2aSchemaErr) - } - return a2aSchema -} - -// assertA2AConformant decodes body into a generic map and validates it against -// the pinned A2A Agent Card schema. On failure it reports the schema error -// alongside the body so test output is actionable without re-running with -v. -func assertA2AConformant(t *testing.T, body []byte) { - t.Helper() - schema := loadA2ASchema(t) - - var doc any - if err := json.Unmarshal(body, &doc); err != nil { - t.Fatalf("A2A card body is not valid JSON: %v\nbody: %s", err, string(body)) - } - if err := schema.Validate(doc); err != nil { - t.Fatalf("A2A schema violation:\n%v\nbody: %s", err, string(body)) - } -} - -// seedPublishedAgent creates a public, published agent with a version and returns its slug. -func seedPublishedAgent(t *testing.T, ns, slug string) { - t.Helper() - pubID := seedPublisher(t, ns, ns) - - ag, err := testDB.CreateAgent(context.Background(), store.CreateAgentParams{ - PublisherID: pubID, - Slug: slug, - Name: slug, - Description: "Test agent", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - - if err := testDB.SetAgentVisibility(context.Background(), ag.ID, "public"); err != nil { - t.Fatalf("SetAgentVisibility: %v", err) - } - - _, err = testDB.CreateAgentVersion(context.Background(), store.CreateAgentVersionParams{ - AgentID: ag.ID, - Version: "1.0.0", - EndpointURL: "https://example.com/agent", - Skills: validSkills, - }) - if err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } - - if err := testDB.PublishAgentVersion(context.Background(), ag.ID, "1.0.0"); err != nil { - t.Fatalf("PublishAgentVersion: %v", err) - } -} - -// ─── PerAgentCard ──────────────────────────────────────────────────────────── - -func TestAgentCardHandler_PerAgentCard_Found(t *testing.T) { - resetTables(t) - seedPublishedAgent(t, "card-ns", "card-ag") - - req := httptest.NewRequest(http.MethodGet, - "/agents/card-ns/card-ag/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("https://registry.example.test").ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - - var card struct { - Name string `json:"name"` - Version string `json:"version"` - URL string `json:"url"` - Skills []struct { - ID string `json:"id"` - } `json:"skills"` - } - if err := json.NewDecoder(rec.Body).Decode(&card); err != nil { - t.Fatalf("decode: %v", err) - } - if card.Name == "" { - t.Error("expected non-empty name") - } - if card.Version != "1.0.0" { - t.Errorf("version = %q, want 1.0.0", card.Version) - } - if card.URL == "" { - t.Error("expected non-empty url") - } - if len(card.Skills) == 0 { - t.Error("expected at least one skill") - } -} - -// Forensic leakage check: when an agent has a newer pending_review (or -// rejected) version, the per-agent card endpoint must keep emitting the -// latest *published* version's data. The card consumer caches what we -// publish, so silently advertising an unapproved version would be a -// real correctness bug. Pinned at the HTTP layer so a future change to -// the card builder can't quietly re-introduce the leak. -func TestAgentCardHandler_PerAgentCard_HidesPendingVersion(t *testing.T) { - resetTables(t) - pubID := seedPublisher(t, "card-leak-ns", "card-leak-ns") - - ag, err := testDB.CreateAgent(context.Background(), store.CreateAgentParams{ - PublisherID: pubID, Slug: "leak-ag", Name: "leak-ag", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if err := testDB.SetAgentVisibility(context.Background(), ag.ID, "public"); err != nil { - t.Fatalf("SetAgentVisibility: %v", err) - } - // 1.0.0 → published. - if _, err := testDB.CreateAgentVersion(context.Background(), store.CreateAgentVersionParams{ - AgentID: ag.ID, Version: "1.0.0", EndpointURL: "https://example.com/v1", Skills: validSkills, - }); err != nil { - t.Fatalf("CreateAgentVersion 1.0.0: %v", err) - } - if err := testDB.PublishAgentVersion(context.Background(), ag.ID, "1.0.0"); err != nil { - t.Fatalf("PublishAgentVersion: %v", err) - } - // 1.1.0 → pending_review (newer than published, but unapproved). - if _, err := testDB.CreateAgentVersion(context.Background(), store.CreateAgentVersionParams{ - AgentID: ag.ID, Version: "1.1.0", EndpointURL: "https://example.com/v2", Skills: validSkills, - }); err != nil { - t.Fatalf("CreateAgentVersion 1.1.0: %v", err) - } - if err := testDB.SubmitAgentVersion(context.Background(), ag.ID, "1.1.0", false, store.Actor{Subject: "a", Email: "a@x"}); err != nil { - t.Fatalf("SubmitAgentVersion: %v", err) - } - - req := httptest.NewRequest(http.MethodGet, - "/agents/card-leak-ns/leak-ag/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("https://registry.example.test").ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var card struct { - Version string `json:"version"` - URL string `json:"url"` - } - if err := json.NewDecoder(rec.Body).Decode(&card); err != nil { - t.Fatalf("decode: %v", err) - } - if card.Version != "1.0.0" { - t.Errorf("card version = %q, want 1.0.0 (pending 1.1.0 must not leak)", card.Version) - } - if card.URL != "https://example.com/v1" { - t.Errorf("card url = %q, want the published v1 endpoint (pending 1.1.0 must not leak)", card.URL) - } -} - -func TestAgentCardHandler_PerAgentCard_NotFound(t *testing.T) { - resetTables(t) - seedPublisher(t, "card-nf-ns", "card-nf-ns") - - req := httptest.NewRequest(http.MethodGet, - "/agents/card-nf-ns/nonexistent/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("https://registry.example.test").ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -func TestAgentCardHandler_PerAgentCard_PrivateAgent(t *testing.T) { - resetTables(t) - // Private agent (default) — card not accessible - seedAgent(t, "card-priv-ns", "priv-ag") - - req := httptest.NewRequest(http.MethodGet, - "/agents/card-priv-ns/priv-ag/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("https://registry.example.test").ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -func TestAgentCardHandler_PerAgentCard_NoPublishedVersion(t *testing.T) { - resetTables(t) - // Public agent but no published version - seedAgentPublic(t, "card-nover-ns", "nover-ag") - - req := httptest.NewRequest(http.MethodGet, - "/agents/card-nover-ns/nover-ag/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("https://registry.example.test").ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -// TestAgentCardHandler_PerAgentCard_A2AConformance drives a freshly-seeded -// published agent through the real handler and asserts the response body -// conforms to the pinned A2A JSON Schema. This is the test that catches the -// class of bug where GenerateCard drops a required field (e.g. defaultInputModes -// becomes nil and marshals as `null`) or silently mis-types a capability. -func TestAgentCardHandler_PerAgentCard_A2AConformance(t *testing.T) { - resetTables(t) - seedPublishedAgent(t, "conf-ns", "conf-ag") - - req := httptest.NewRequest(http.MethodGet, - "/agents/conf-ns/conf-ag/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("https://registry.example.test").ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - - assertA2AConformant(t, rec.Body.Bytes()) -} - -// ─── GlobalAgentCard ──────────────────────────────────────────────────────── - -// TestAgentCardHandler_GlobalAgentCard_A2AConformance proves the registry's -// own agent card (served at /.well-known/agent-card.json) is A2A-compliant -// too. The global card makes the registry a first-class A2A citizen — an invalid card here would break discovery -// clients that crawl the registry via A2A. -func TestAgentCardHandler_GlobalAgentCard_A2AConformance(t *testing.T) { - resetTables(t) - - req := httptest.NewRequest(http.MethodGet, "/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("https://registry.example.test").ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { - t.Errorf("Content-Type = %q, want application/json", ct) - } - - assertA2AConformant(t, rec.Body.Bytes()) - - // Also verify the URL field points at the registry we configured, not a - // stale default. A card that advertises the wrong URL is actively - // dangerous: it misroutes every A2A client that caches it. - var card map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &card); err != nil { - t.Fatalf("decode: %v", err) - } - wantPrefix := "https://registry.example.test/" - if url, _ := card["url"].(string); !strings.HasPrefix(url, wantPrefix) { - t.Errorf("global card url = %q, want prefix %q", url, wantPrefix) - } -} - -// TestAgentCardHandler_GlobalAgentCard_MisconfiguredReturns500 guards the -// documented behaviour that an unset PUBLIC_BASE_URL MUST fail loud rather -// than silently advertising a localhost URL to external consumers. The -// handler's comment explicitly promises this — if somebody changes it to fall -// back to "http://localhost:8081" the regression is invisible in prod until -// an external A2A crawler tries to dial it. -func TestAgentCardHandler_GlobalAgentCard_MisconfiguredReturns500(t *testing.T) { - resetTables(t) - // Empty publicBaseURL is the misconfiguration the handler must surface - // — replaced PUBLIC_BASE_URL env injection with direct constructor input - // now that the value is sourced from the config layer. - - req := httptest.NewRequest(http.MethodGet, "/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - newAgentCardRouter("").ServeHTTP(rec, req) - - if rec.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want 500; body: %s", rec.Code, rec.Body.String()) - } - // Problem+JSON response shape — the handler writes via problem.Write. - if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, "problem+json") { - t.Errorf("Content-Type = %q, want application/problem+json", ct) - } - var prob map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &prob); err != nil { - t.Fatalf("decode problem: %v", err) - } - // problem.Write puts the slug into the `type` URL and the caller-supplied - // message into `detail`; `title` is the generic HTTP status text. - typeField, _ := prob["type"].(string) - if !strings.Contains(typeField, "misconfiguration") { - t.Errorf("problem.type = %q, want it to contain 'misconfiguration'", typeField) - } - if detail, _ := prob["detail"].(string); !strings.Contains(detail, "PUBLIC_BASE_URL") { - t.Errorf("problem.detail = %q, want it to mention PUBLIC_BASE_URL", detail) - } - if status, _ := prob["status"].(float64); int(status) != http.StatusInternalServerError { - t.Errorf("problem.status = %v, want 500", status) - } -} - -// ─── Unit-level card generation conformance ───────────────────────────────── - -// TestRegistryCard_A2AConformance runs the unit-level RegistryCard constructor -// through the schema without going through the HTTP layer. This is a -// cheap-and-fast smoke test that lives alongside the handler tests because -// the schema loader is here; a failure here is a direct bug in -// internal/agents/card.go:RegistryCard. -func TestRegistryCard_A2AConformance(t *testing.T) { - // Import cycle avoidance: we reach RegistryCard via JSON-round-trip of - // the global endpoint in the handler-level test above, so this unit test - // just re-invokes the handler and asserts the same thing from a different - // entry point. Keeping it separate makes the failure message narrower - // when only the shape is wrong (no DB, no routing). - h := handlers.NewAgentCardHandlers(testDB, slog.Default(), "https://registry.example.test") - req := httptest.NewRequest(http.MethodGet, "/.well-known/agent-card.json", nil) - rec := httptest.NewRecorder() - h.GlobalAgentCard(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", rec.Code) - } - assertA2AConformant(t, rec.Body.Bytes()) -} diff --git a/server/internal/http/handlers/audit.go b/server/internal/http/handlers/audit.go index df02795e..273a5604 100644 --- a/server/internal/http/handlers/audit.go +++ b/server/internal/http/handlers/audit.go @@ -21,7 +21,7 @@ func NewAuditHandlers(db *store.DB) *AuditHandlers { // // Query params: // -// resource_type — filter by resource type ("mcp_server", "agent", "publisher") +// resource_type — filter by resource type ("mcp_server", "publisher") // resource_id — filter by resource ULID // actor — filter by Keycloak subject UUID // limit — page size (1-100, default 50) diff --git a/server/internal/http/handlers/audit_test.go b/server/internal/http/handlers/audit_test.go index 46db4e02..58186c9a 100644 --- a/server/internal/http/handlers/audit_test.go +++ b/server/internal/http/handlers/audit_test.go @@ -62,7 +62,7 @@ func TestAuditHandler_ListEvents_AfterLoggingEvents(t *testing.T) { resetTables(t) logAuditEvent(t, "mcp_server", "id-001", "mcp_server.created") - logAuditEvent(t, "agent", "id-002", "agent.created") + logAuditEvent(t, "publisher", "id-002", "publisher.created") req := httptest.NewRequest(http.MethodGet, "/api/v1/audit", nil) rec := httptest.NewRecorder() @@ -83,8 +83,8 @@ func TestAuditHandler_ListEvents_AfterLoggingEvents(t *testing.T) { t.Errorf("expected 2 items, got %d", len(body.Items)) } // Newest first - if body.Items[0].ResourceType != "agent" { - t.Errorf("first item resource_type = %q, want agent (newest first)", body.Items[0].ResourceType) + if body.Items[0].ResourceType != "publisher" { + t.Errorf("first item resource_type = %q, want publisher (newest first)", body.Items[0].ResourceType) } } @@ -93,7 +93,7 @@ func TestAuditHandler_ListEvents_ResourceTypeFilter(t *testing.T) { logAuditEvent(t, "mcp_server", "id-mcp1", "mcp_server.created") logAuditEvent(t, "mcp_server", "id-mcp2", "mcp_server.deprecated") - logAuditEvent(t, "agent", "id-ag1", "agent.created") + logAuditEvent(t, "publisher", "id-pub1", "publisher.created") req := httptest.NewRequest(http.MethodGet, "/api/v1/audit?resource_type=mcp_server", nil) rec := httptest.NewRecorder() diff --git a/server/internal/http/handlers/entrychange.go b/server/internal/http/handlers/entrychange.go index 12cbb369..765f4d2b 100644 --- a/server/internal/http/handlers/entrychange.go +++ b/server/internal/http/handlers/entrychange.go @@ -207,124 +207,9 @@ func (h *ReviewHandlers) WithdrawMCPChange(w http.ResponseWriter, r *http.Reques w.WriteHeader(http.StatusNoContent) } -// ── Agent entry-change review endpoints ────────────────────────────────────── - -// ApproveAgentChange: POST /api/v1/agents/{ns}/{slug}/change-request/approve -func (h *ReviewHandlers) ApproveAgentChange(w http.ResponseWriter, r *http.Request) { - ns, slug := chi.URLParam(r, "namespace"), chi.URLParam(r, "slug") - var body struct { - Revision int `json:"revision"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Revision <= 0 { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "revision is required and must be > 0", r.URL.Path) - return - } - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if !h.resolvedEntry(w, r, err, "agent", ns, slug) { - return - } - cr, ok := h.pendingChange(w, r, domain.EntryResourceAgent, ag.ID) - if !ok { - return - } - applied, err := h.db.ApproveEntryChangeRequest(r.Context(), cr.ID, body.Revision, reviewActor(r)) - if err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentChangeApproved, ResourceType: "agent", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"action": string(applied.Action), "change_id": applied.ID}, - }) - w.WriteHeader(http.StatusNoContent) -} - -// RejectAgentChange: POST .../change-request/reject -func (h *ReviewHandlers) RejectAgentChange(w http.ResponseWriter, r *http.Request) { - ns, slug := chi.URLParam(r, "namespace"), chi.URLParam(r, "slug") - var body struct { - Revision int `json:"revision"` - Reason string `json:"reason"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Revision <= 0 { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "revision is required and must be > 0", r.URL.Path) - return - } - if body.Reason == "" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "reason is required on reject", r.URL.Path) - return - } - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if !h.resolvedEntry(w, r, err, "agent", ns, slug) { - return - } - cr, ok := h.pendingChange(w, r, domain.EntryResourceAgent, ag.ID) - if !ok { - return - } - if err := h.db.RejectEntryChangeRequest(r.Context(), cr.ID, body.Revision, body.Reason, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentChangeRejected, ResourceType: "agent", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"action": string(cr.Action), "change_id": cr.ID, "reason": body.Reason}, - }) - w.WriteHeader(http.StatusNoContent) -} - -// WithdrawAgentChange: POST .../change-request/withdraw -func (h *ReviewHandlers) WithdrawAgentChange(w http.ResponseWriter, r *http.Request) { - ns, slug := chi.URLParam(r, "namespace"), chi.URLParam(r, "slug") - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if !h.resolvedEntry(w, r, err, "agent", ns, slug) { - return - } - cr, ok := h.pendingChange(w, r, domain.EntryResourceAgent, ag.ID) - if !ok { - return - } - if err := h.db.WithdrawEntryChangeRequest(r.Context(), cr.ID, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentChangeWithdrawn, ResourceType: "agent", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"action": string(cr.Action), "change_id": cr.ID}, - }) - w.WriteHeader(http.StatusNoContent) -} - // ── shared helpers ─────────────────────────────────────────────────────────── -// resolvedEntry maps a GetMCPServer/GetAgent lookup error to a 404/500 and +// resolvedEntry maps a GetMCPServer lookup error to a 404/500 and // returns false if the caller should stop. true means the entry was found. func (h *ReviewHandlers) resolvedEntry(w http.ResponseWriter, r *http.Request, err error, kind, ns, slug string) bool { if errors.Is(err, store.ErrNotFound) { diff --git a/server/internal/http/handlers/entrychange_test.go b/server/internal/http/handlers/entrychange_test.go index 7e4ead2d..a6dde354 100644 --- a/server/internal/http/handlers/entrychange_test.go +++ b/server/internal/http/handlers/entrychange_test.go @@ -21,12 +21,10 @@ import ( "github.com/haibread/ai-registry/internal/store" ) -// newEntryChangeRouter wires the MCP and agent enqueue endpoints plus the -// entry-change review endpoints onto one router so a test can drive the whole -// flow for both resource types. +// newEntryChangeRouter wires the MCP enqueue endpoints plus the entry-change +// review endpoints onto one router so a test can drive the whole flow. func newEntryChangeRouter() *chi.Mux { mcp := handlers.NewMCPHandlers(testDB, testDB, nil) - ag := handlers.NewAgentHandlers(testDB, testDB, nil) rev := handlers.NewReviewHandlers(testDB, testDB) r := chi.NewRouter() r.Post("/api/v1/mcp/servers/{namespace}/{slug}/visibility", mcp.SetVisibility) @@ -37,13 +35,6 @@ func newEntryChangeRouter() *chi.Mux { r.Post("/api/v1/mcp/servers/{namespace}/{slug}/change-request/approve", rev.ApproveMCPChange) r.Post("/api/v1/mcp/servers/{namespace}/{slug}/change-request/reject", rev.RejectMCPChange) r.Post("/api/v1/mcp/servers/{namespace}/{slug}/change-request/withdraw", rev.WithdrawMCPChange) - r.Post("/api/v1/agents/{namespace}/{slug}/visibility", ag.SetVisibility) - r.Post("/api/v1/agents/{namespace}/{slug}/deprecate", ag.DeprecateAgent) - r.Post("/api/v1/agents/{namespace}/{slug}/undeprecate", ag.UndeprecateAgent) - r.Patch("/api/v1/agents/{namespace}/{slug}", ag.PatchAgent) - r.Post("/api/v1/agents/{namespace}/{slug}/change-request/approve", rev.ApproveAgentChange) - r.Post("/api/v1/agents/{namespace}/{slug}/change-request/reject", rev.RejectAgentChange) - r.Post("/api/v1/agents/{namespace}/{slug}/change-request/withdraw", rev.WithdrawAgentChange) return r } @@ -71,24 +62,6 @@ func seedPublishedMCPForHandler(t *testing.T, ns, slug string) string { return srv.ID } -// seedPublishedAgentForHandler creates a publisher + agent flipped to published -// so visibility-to-public and deprecate preconditions hold. -func seedPublishedAgentForHandler(t *testing.T, ns, slug string) string { - t.Helper() - pubID := seedPublisher(t, ns, ns) - ag, err := testDB.CreateAgent(context.Background(), store.CreateAgentParams{ - PublisherID: pubID, Slug: slug, Name: slug, - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if _, err := testDB.Pool.Exec(context.Background(), - `UPDATE agents SET status='published' WHERE id=$1`, ag.ID); err != nil { - t.Fatalf("publish agent: %v", err) - } - return ag.ID -} - func fire(r http.Handler, ctx context.Context, method, path, body string) *httptest.ResponseRecorder { var req *http.Request if body == "" { @@ -286,33 +259,6 @@ func TestEntryChangeHandler_UndeprecateRoundTrip(t *testing.T) { } } -func TestEntryChangeHandler_AgentUndeprecate(t *testing.T) { - resetTables(t) - agID := seedPublishedAgentForHandler(t, "acme", "assistant") - r := newEntryChangeRouter() - - if rec := fire(r, adminCtx(), http.MethodPost, - "/api/v1/agents/acme/assistant/deprecate", ""); rec.Code != http.StatusOK { - t.Fatalf("deprecate: %d, body: %s", rec.Code, rec.Body.String()) - } - if rec := fire(r, editorCtx(), http.MethodPost, - "/api/v1/agents/acme/assistant/undeprecate", ""); rec.Code != http.StatusAccepted { - t.Fatalf("editor undeprecate = %d, want 202; body: %s", rec.Code, rec.Body.String()) - } - if rec := fire(r, adminCtx(), http.MethodPost, - "/api/v1/agents/acme/assistant/change-request/approve", `{"revision":1}`); rec.Code != http.StatusNoContent { - t.Fatalf("approve: %d, body: %s", rec.Code, rec.Body.String()) - } - var status string - if err := testDB.Pool.QueryRow(context.Background(), - `SELECT status FROM agents WHERE id=$1`, agID).Scan(&status); err != nil { - t.Fatalf("read: %v", err) - } - if status != "published" { - t.Errorf("status = %q, want published after approve", status) - } -} - // readStatusVis reads (visibility, status, name) for an MCP server row. func readStatusVis(t *testing.T, srvID string) (vis, status, name string) { t.Helper() @@ -323,86 +269,8 @@ func readStatusVis(t *testing.T, srvID string) (vis, status, name string) { return vis, status, name } -// ── agent endpoints: same review-routing contract as MCP ───────────────────── - -func TestEntryChangeHandler_AgentEditorEnqueuesAllMutations(t *testing.T) { - resetTables(t) - agID := seedPublishedAgentForHandler(t, "acme", "assistant") - r := newEntryChangeRouter() - - // Each editor mutation enqueues (202) and leaves the entry untouched; the - // pending slot is withdrawn between attempts so each path is exercised. - steps := []struct { - name, method, path, body string - }{ - {"patch", http.MethodPatch, "/api/v1/agents/acme/assistant", `{"description":"sneaky edit"}`}, - {"visibility", http.MethodPost, "/api/v1/agents/acme/assistant/visibility", `{"visibility":"public"}`}, - {"deprecate", http.MethodPost, "/api/v1/agents/acme/assistant/deprecate", ""}, - } - for _, s := range steps { - if rec := fire(r, editorCtx(), s.method, s.path, s.body); rec.Code != http.StatusAccepted { - t.Fatalf("%s: status = %d, want 202; body: %s", s.name, rec.Code, rec.Body.String()) - } - var status, vis, desc string - if err := testDB.Pool.QueryRow(context.Background(), - `SELECT status, visibility, description FROM agents WHERE id=$1`, agID).Scan(&status, &vis, &desc); err != nil { - t.Fatalf("%s: read: %v", s.name, err) - } - if status != "published" || vis != "private" || desc != "" { - t.Errorf("%s: agent mutated while pending: status=%q vis=%q desc=%q", s.name, status, vis, desc) - } - if rec := fire(r, editorCtx(), http.MethodPost, - "/api/v1/agents/acme/assistant/change-request/withdraw", ""); rec.Code != http.StatusNoContent { - t.Fatalf("%s: withdraw: %d, body: %s", s.name, rec.Code, rec.Body.String()) - } - } -} - -func TestEntryChangeHandler_AgentAdminAppliesImmediately(t *testing.T) { - resetTables(t) - agID := seedPublishedAgentForHandler(t, "acme", "assistant") - r := newEntryChangeRouter() - - rec := fire(r, adminCtx(), http.MethodPost, - "/api/v1/agents/acme/assistant/visibility", `{"visibility":"public"}`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var vis string - if err := testDB.Pool.QueryRow(context.Background(), - `SELECT visibility FROM agents WHERE id=$1`, agID).Scan(&vis); err != nil { - t.Fatalf("read: %v", err) - } - if vis != "public" { - t.Errorf("visibility = %q, want public (applied immediately)", vis) - } -} - -func TestEntryChangeHandler_AgentEnqueueThenApprove(t *testing.T) { - resetTables(t) - agID := seedPublishedAgentForHandler(t, "acme", "assistant") - r := newEntryChangeRouter() - - if rec := fire(r, editorCtx(), http.MethodPatch, - "/api/v1/agents/acme/assistant", `{"description":"reviewed edit"}`); rec.Code != http.StatusAccepted { - t.Fatalf("enqueue: %d, body: %s", rec.Code, rec.Body.String()) - } - if rec := fire(r, adminCtx(), http.MethodPost, - "/api/v1/agents/acme/assistant/change-request/approve", `{"revision":1}`); rec.Code != http.StatusNoContent { - t.Fatalf("approve: %d, body: %s", rec.Code, rec.Body.String()) - } - var desc string - if err := testDB.Pool.QueryRow(context.Background(), - `SELECT description FROM agents WHERE id=$1`, agID).Scan(&desc); err != nil { - t.Fatalf("read: %v", err) - } - if desc != "reviewed edit" { - t.Errorf("description = %q, want %q after approve", desc, "reviewed edit") - } -} - // TestEntryChangeHandler_SelfApprovalForbidden: the Editor who enqueued a -// change cannot approve it, for either resource type; another Reviewer can. +// change cannot approve it; another Reviewer can. func TestEntryChangeHandler_SelfApprovalForbidden(t *testing.T) { cases := []struct { name string @@ -416,12 +284,6 @@ func TestEntryChangeHandler_SelfApprovalForbidden(t *testing.T) { enqueue: "/api/v1/mcp/servers/acme/weather/visibility", approve: "/api/v1/mcp/servers/acme/weather/change-request/approve", }, - { - name: "agent", - seed: func(t *testing.T) { seedPublishedAgentForHandler(t, "acme", "assistant") }, - enqueue: "/api/v1/agents/acme/assistant/visibility", - approve: "/api/v1/agents/acme/assistant/change-request/approve", - }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/server/internal/http/handlers/publisher.go b/server/internal/http/handlers/publisher.go index 74cb4dc4..fa29b7cb 100644 --- a/server/internal/http/handlers/publisher.go +++ b/server/internal/http/handlers/publisher.go @@ -124,7 +124,7 @@ type PublisherActivityEvent struct { // GetPublisherActivity returns the publisher-scoped audit feed (newest first, // paginated). Gated to a publisher member (Viewer and up) or Server Admin in // the router. Filtered by resource_ns = the publisher's slug, so it covers the -// lifecycle of every MCP server and agent under the publisher. Metadata is run +// lifecycle of every MCP server under the publisher. Metadata is run // through the same scrub as the public feed; the actor's email is retained // because the audience is the publisher's own members. func (h *PublisherHandlers) GetPublisherActivity(w http.ResponseWriter, r *http.Request) { @@ -297,7 +297,7 @@ func (h *PublisherHandlers) DeletePublisher(w http.ResponseWriter, r *http.Reque return } - // Deleting a publisher cascades to all of its MCP servers, agents, their + // Deleting a publisher cascades to all of its MCP servers, their // versions, and any reports filed against them (see store.DeletePublisher); // owned resources never block the delete, so there is no 409 path here. if err := h.db.DeletePublisher(r.Context(), pub.ID); errors.Is(err, store.ErrNotFound) { diff --git a/server/internal/http/handlers/reports.go b/server/internal/http/handlers/reports.go index 3018e9be..fa42c029 100644 --- a/server/internal/http/handlers/reports.go +++ b/server/internal/http/handlers/reports.go @@ -43,11 +43,6 @@ var allowedIssueTypes = map[string]struct{}{ "other": {}, } -var allowedResourceTypes = map[string]struct{}{ - "mcp_server": {}, - "agent": {}, -} - // CreateReport handles POST /api/v1/reports. // // Body: { resource_type, resource_id, issue_type, description } @@ -71,9 +66,9 @@ func (h *ReportHandlers) CreateReport(w http.ResponseWriter, r *http.Request) { body.IssueType = strings.TrimSpace(body.IssueType) body.Description = strings.TrimSpace(body.Description) - if _, ok := allowedResourceTypes[body.ResourceType]; !ok { + if body.ResourceType != "mcp_server" { problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "resource_type must be 'mcp_server' or 'agent'", r.URL.Path) + "resource_type must be 'mcp_server'", r.URL.Path) return } if body.ResourceID == "" { diff --git a/server/internal/http/handlers/reports_test.go b/server/internal/http/handlers/reports_test.go index a6466f3a..2b1549c4 100644 --- a/server/internal/http/handlers/reports_test.go +++ b/server/internal/http/handlers/reports_test.go @@ -70,10 +70,10 @@ func TestReportHandler_Create_ValidationErrors(t *testing.T) { body map[string]any }{ {"bad resource_type", map[string]any{"resource_type": "widget", "resource_id": "1", "issue_type": "broken", "description": "bad thing happening"}}, - {"missing resource_id", map[string]any{"resource_type": "agent", "resource_id": "", "issue_type": "broken", "description": "bad thing happening"}}, - {"bad issue_type", map[string]any{"resource_type": "agent", "resource_id": "1", "issue_type": "flippity", "description": "bad thing happening"}}, - {"short description", map[string]any{"resource_type": "agent", "resource_id": "1", "issue_type": "broken", "description": "hi"}}, - {"long description", map[string]any{"resource_type": "agent", "resource_id": "1", "issue_type": "broken", "description": strings.Repeat("x", 4001)}}, + {"missing resource_id", map[string]any{"resource_type": "mcp_server", "resource_id": "", "issue_type": "broken", "description": "bad thing happening"}}, + {"bad issue_type", map[string]any{"resource_type": "mcp_server", "resource_id": "1", "issue_type": "flippity", "description": "bad thing happening"}}, + {"short description", map[string]any{"resource_type": "mcp_server", "resource_id": "1", "issue_type": "broken", "description": "hi"}}, + {"long description", map[string]any{"resource_type": "mcp_server", "resource_id": "1", "issue_type": "broken", "description": strings.Repeat("x", 4001)}}, } for _, c := range cases { @@ -197,8 +197,8 @@ func TestReportHandler_Create_XFFTrustedFromProxy(t *testing.T) { router := newReportsRouterWithProxy(proxyCIDR) buf, _ := json.Marshal(map[string]any{ - "resource_type": "agent", - "resource_id": "01HAG", + "resource_type": "mcp_server", + "resource_id": "01HMCP", "issue_type": "spam", "description": "report posted through the reverse proxy", }) @@ -245,8 +245,8 @@ func TestReportHandler_Patch_Valid(t *testing.T) { // Seed a pending report seed := postReport(t, map[string]any{ - "resource_type": "agent", - "resource_id": "01HAG", + "resource_type": "mcp_server", + "resource_id": "01HMCP", "issue_type": "misleading", "description": "the description says X but it does Y", }) diff --git a/server/internal/http/handlers/review.go b/server/internal/http/handlers/review.go index d358ccdb..e7025048 100644 --- a/server/internal/http/handlers/review.go +++ b/server/internal/http/handlers/review.go @@ -28,8 +28,7 @@ import ( ) // ReviewHandlers serves the change-approval workflow endpoints. The -// handlers depend on the same store + audit logger as the existing MCP -// and agent handlers. +// handlers depend on the same store + audit logger as the MCP handlers. type ReviewHandlers struct { db *store.DB audit store.AuditLogger @@ -516,282 +515,3 @@ func (h *ReviewHandlers) RejectMCPDeletion(w http.ResponseWriter, r *http.Reques }) w.WriteHeader(http.StatusNoContent) } - -// ── Agent version flow ────────────────────────────────────────────────── - -// SubmitAgentVersion: POST /api/v1/agents/{ns}/{slug}/versions/{ver}/submit -// Optional body: {"request_public": true} — ask for the entry to be made -// public when the submission is approved. -func (h *ReviewHandlers) SubmitAgentVersion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ver := chi.URLParam(r, "version") - body, ok := decodeOptionalSubmitBody(w, r) - if !ok { - return - } - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - if err := h.db.SubmitAgentVersion(r.Context(), ag.ID, ver, body.RequestPublic, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentVersionSubmitted, ResourceType: "agent_version", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"version": ver, "request_public": body.RequestPublic}, - }) - w.WriteHeader(http.StatusNoContent) -} - -// WithdrawAgentVersion: POST .../versions/{ver}/withdraw -func (h *ReviewHandlers) WithdrawAgentVersion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ver := chi.URLParam(r, "version") - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - if err := h.db.WithdrawAgentVersion(r.Context(), ag.ID, ver, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentVersionWithdrawn, ResourceType: "agent_version", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"version": ver}, - }) - w.WriteHeader(http.StatusNoContent) -} - -// ApproveAgentVersion: POST .../versions/{ver}/approve body: {"revision": N} -func (h *ReviewHandlers) ApproveAgentVersion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ver := chi.URLParam(r, "version") - - var body struct { - Revision int `json:"revision"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Revision <= 0 { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "revision is required and must be > 0", r.URL.Path) - return - } - - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - madePublic, err := h.db.ApproveAgentVersion(r.Context(), ag.ID, ver, body.Revision, reviewActor(r)) - if err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentVersionApproved, ResourceType: "agent_version", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"version": ver, "revision": body.Revision, "made_public": madePublic}, - }) - w.WriteHeader(http.StatusNoContent) -} - -// RejectAgentVersion: POST .../versions/{ver}/reject body: {"revision": N, "reason": "..."} -func (h *ReviewHandlers) RejectAgentVersion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ver := chi.URLParam(r, "version") - - var body struct { - Revision int `json:"revision"` - Reason string `json:"reason"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Revision <= 0 { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "revision is required and must be > 0", r.URL.Path) - return - } - if body.Reason == "" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "reason is required on reject", r.URL.Path) - return - } - - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - if err := h.db.RejectAgentVersion(r.Context(), ag.ID, ver, body.Revision, body.Reason, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentVersionRejected, ResourceType: "agent_version", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{ - "version": ver, - "revision": body.Revision, - "reason": body.Reason, - }, - }) - w.WriteHeader(http.StatusNoContent) -} - -// ── Agent deletion flow ───────────────────────────────────────────────── - -// RequestAgentDeletion: POST /api/v1/agents/{ns}/{slug}/deletion-request -func (h *ReviewHandlers) RequestAgentDeletion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - if err := h.db.RequestAgentDeletion(r.Context(), ag.ID, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentDeletionRequested, ResourceType: "agent", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - }) - w.WriteHeader(http.StatusAccepted) -} - -// ApproveAgentDeletion: POST .../deletion-request/approve -func (h *ReviewHandlers) ApproveAgentDeletion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - if err := h.db.ApproveAgentDeletion(r.Context(), ag.ID, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentDeletionApproved, ResourceType: "agent", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - }) - w.WriteHeader(http.StatusNoContent) -} - -// RejectAgentDeletion: POST .../deletion-request/reject body: {"reason": "..."} -func (h *ReviewHandlers) RejectAgentDeletion(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - var body struct { - Reason string `json:"reason"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Reason == "" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - "reason is required on reject", r.URL.Path) - return - } - - ag, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - if err := h.db.RejectAgentDeletion(r.Context(), ag.ID, reviewActor(r)); err != nil { - if writeReviewProblem(w, r, err) { - return - } - internalError(w, r, err) - return - } - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, ActorEmail: email, - Action: domain.ActionAgentDeletionRejected, ResourceType: "agent", - ResourceID: ag.ID, ResourceNS: ns, ResourceSlug: slug, - Metadata: map[string]any{"reason": body.Reason}, - }) - w.WriteHeader(http.StatusNoContent) -} diff --git a/server/internal/http/handlers/review_test.go b/server/internal/http/handlers/review_test.go index 32294780..6ebf377b 100644 --- a/server/internal/http/handlers/review_test.go +++ b/server/internal/http/handlers/review_test.go @@ -35,15 +35,6 @@ func newReviewRouter() *chi.Mux { r.Post("/deletion-request/approve", h.ApproveMCPDeletion) r.Post("/deletion-request/reject", h.RejectMCPDeletion) }) - r.Route("/api/v1/agents/{namespace}/{slug}", func(r chi.Router) { - r.Post("/versions/{version}/submit", h.SubmitAgentVersion) - r.Post("/versions/{version}/withdraw", h.WithdrawAgentVersion) - r.Post("/versions/{version}/approve", h.ApproveAgentVersion) - r.Post("/versions/{version}/reject", h.RejectAgentVersion) - r.Post("/deletion-request", h.RequestAgentDeletion) - r.Post("/deletion-request/approve", h.ApproveAgentDeletion) - r.Post("/deletion-request/reject", h.RejectAgentDeletion) - }) return r } @@ -87,28 +78,6 @@ func seedDraftMCPServerVersion(t *testing.T, ns, slug, ver string) { } } -func seedDraftAgentForHandler(t *testing.T, ns, slug, ver string) { - t.Helper() - pubID := seedPublisher(t, ns, ns) - ag, err := testDB.CreateAgent(context.Background(), store.CreateAgentParams{ - PublisherID: pubID, Slug: slug, Name: slug, - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if _, err := testDB.CreateAgentVersion(context.Background(), store.CreateAgentVersionParams{ - AgentID: ag.ID, - Version: ver, - EndpointURL: "https://agent.example/api", - Skills: json.RawMessage(`[{"id":"s1","name":"s","description":"d","tags":["x"]}]`), - DefaultInputModes: []string{"text/plain"}, - DefaultOutputModes: []string{"text/plain"}, - ProtocolVersion: "0.3.0", - }); err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } -} - // ── MCP handlers ──────────────────────────────────────────────────────── func TestReviewHandler_SubmitApproveMCP(t *testing.T) { @@ -325,126 +294,6 @@ func TestReviewHandler_MCPDeletion_RejectMissingReason(t *testing.T) { } } -// ── Agent handlers (smoke coverage; same shape as MCP) ────────────────── - -func TestReviewHandler_SubmitApproveAgent(t *testing.T) { - resetTables(t) - seedDraftAgentForHandler(t, "acme", "planner", "0.1.0") - r := newReviewRouter() - - rec := httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/versions/0.1.0/submit", nil)) - if rec.Code != http.StatusNoContent { - t.Fatalf("submit: %d, body: %s", rec.Code, rec.Body.String()) - } - - rec = httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/versions/0.1.0/approve", - []byte(`{"revision":1}`))) - if rec.Code != http.StatusNoContent { - t.Errorf("approve: %d, body: %s", rec.Code, rec.Body.String()) - } -} - -func TestReviewHandler_AgentVersionRejectAndWithdraw(t *testing.T) { - resetTables(t) - seedDraftAgentForHandler(t, "acme", "planner", "0.1.0") - r := newReviewRouter() - - r.ServeHTTP(httptest.NewRecorder(), authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/versions/0.1.0/submit", nil)) - - rec := httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/versions/0.1.0/reject", - []byte(`{"revision":1,"reason":"nope"}`))) - if rec.Code != http.StatusNoContent { - t.Fatalf("reject: %d", rec.Code) - } - - // Re-submit → withdraw. - r.ServeHTTP(httptest.NewRecorder(), authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/versions/0.1.0/submit", nil)) - rec = httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/versions/0.1.0/withdraw", nil)) - if rec.Code != http.StatusNoContent { - t.Errorf("withdraw: %d", rec.Code) - } -} - -func TestReviewHandler_AgentDeletionFlow(t *testing.T) { - resetTables(t) - seedDraftAgentForHandler(t, "acme", "planner", "0.1.0") - r := newReviewRouter() - - rec := httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, "/api/v1/agents/acme/planner/deletion-request", nil)) - if rec.Code != http.StatusAccepted { - t.Fatalf("request: %d", rec.Code) - } - rec = httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, "/api/v1/agents/acme/planner/deletion-request/approve", nil)) - if rec.Code != http.StatusNoContent { - t.Errorf("approve: %d, body: %s", rec.Code, rec.Body.String()) - } -} - -func TestReviewHandler_AgentDeletion_RejectFlow(t *testing.T) { - resetTables(t) - seedDraftAgentForHandler(t, "acme", "planner", "0.1.0") - r := newReviewRouter() - - // Request deletion, then reject with reason → 204. - r.ServeHTTP(httptest.NewRecorder(), authedRequest( - http.MethodPost, "/api/v1/agents/acme/planner/deletion-request", nil)) - - rec := httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/deletion-request/reject", - []byte(`{"reason":"not yet"}`))) - if rec.Code != http.StatusNoContent { - t.Fatalf("reject: %d, body: %s", rec.Code, rec.Body.String()) - } - - // Reject without reason → 422. - rec = httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, - "/api/v1/agents/acme/planner/deletion-request/reject", - []byte(`{}`))) - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("missing reason: %d, want 422", rec.Code) - } -} - -func TestReviewHandler_AgentDeletion_NotFound(t *testing.T) { - resetTables(t) - r := newReviewRouter() - - rec := httptest.NewRecorder() - r.ServeHTTP(rec, authedRequest( - http.MethodPost, - "/api/v1/agents/missing/missing/deletion-request", nil)) - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} - -// Exercise the writeReviewProblem branches that the happy-path tests -// don't reach: state-mismatch (approve a Draft) and already-pending -// (request deletion when one is already pending). func TestReviewHandler_DiscriminatedConflicts_StateAndConflict(t *testing.T) { resetTables(t) seedDraftMCPServerVersion(t, "acme", "weather", "1.0.0") @@ -526,7 +375,7 @@ func TestReviewHandler_ApproveMCP_AlreadyPublished(t *testing.T) { func TestReviewHandler_ListReviewQueue(t *testing.T) { resetTables(t) seedDraftMCPServerVersion(t, "acme", "weather", "1.0.0") - seedDraftAgentForHandler(t, "globex", "planner", "0.1.0") + seedDraftMCPServerVersion(t, "globex", "planner", "1.0.0") // Submit both so the queue has two items. r := newReviewRouter() @@ -535,7 +384,7 @@ func TestReviewHandler_ListReviewQueue(t *testing.T) { "/api/v1/mcp/servers/acme/weather/versions/1.0.0/submit", nil)) r.ServeHTTP(httptest.NewRecorder(), authedRequest( http.MethodPost, - "/api/v1/agents/globex/planner/versions/0.1.0/submit", nil)) + "/api/v1/mcp/servers/globex/planner/versions/1.0.0/submit", nil)) rec := httptest.NewRecorder() r.ServeHTTP(rec, authedRequest(http.MethodGet, "/api/v1/review-queue", nil)) @@ -557,9 +406,12 @@ func TestReviewHandler_ListReviewQueue(t *testing.T) { if len(body.Items) != 2 { t.Errorf("len = %d, want 2", len(body.Items)) } - kinds := map[string]bool{} + publishers := map[string]bool{} for _, it := range body.Items { - kinds[it.Kind] = true + publishers[it.PublisherSlug] = true + if it.Kind != "mcp_version" { + t.Errorf("queue item kind = %q, want mcp_version", it.Kind) + } if it.Version == "" { t.Errorf("queue item %s/%s missing version", it.PublisherSlug, it.EntrySlug) } @@ -567,8 +419,8 @@ func TestReviewHandler_ListReviewQueue(t *testing.T) { t.Errorf("queue item revision = %d, want 1", it.Revision) } } - if !kinds["mcp_version"] || !kinds["agent_version"] { - t.Errorf("expected both mcp_version and agent_version, got %+v", kinds) + if !publishers["acme"] || !publishers["globex"] { + t.Errorf("expected items from acme and globex, got %+v", publishers) } } @@ -618,14 +470,14 @@ func TestReviewHandler_ListReviewQueue_ScopedToReviewerPublishers(t *testing.T) resetTables(t) ctx := context.Background() seedDraftMCPServerVersion(t, "acme", "weather", "1.0.0") - seedDraftAgentForHandler(t, "globex", "planner", "0.1.0") + seedDraftMCPServerVersion(t, "globex", "planner", "1.0.0") r := newReviewRouter() // Submit both (as admin) so the queue has one item per publisher. r.ServeHTTP(httptest.NewRecorder(), authedRequest(http.MethodPost, "/api/v1/mcp/servers/acme/weather/versions/1.0.0/submit", nil)) r.ServeHTTP(httptest.NewRecorder(), authedRequest(http.MethodPost, - "/api/v1/agents/globex/planner/versions/0.1.0/submit", nil)) + "/api/v1/mcp/servers/globex/planner/versions/1.0.0/submit", nil)) // A Reviewer on acme only. acmeID, err := testDB.GetPublisherBySlug(ctx, "acme") @@ -673,13 +525,13 @@ func TestReviewHandler_ListReviewQueue_GlobalReviewerSeesAll(t *testing.T) { resetTables(t) ctx := context.Background() seedDraftMCPServerVersion(t, "acme", "weather", "1.0.0") - seedDraftAgentForHandler(t, "globex", "planner", "0.1.0") + seedDraftMCPServerVersion(t, "globex", "planner", "1.0.0") r := newReviewRouter() r.ServeHTTP(httptest.NewRecorder(), authedRequest(http.MethodPost, "/api/v1/mcp/servers/acme/weather/versions/1.0.0/submit", nil)) r.ServeHTTP(httptest.NewRecorder(), authedRequest(http.MethodPost, - "/api/v1/agents/globex/planner/versions/0.1.0/submit", nil)) + "/api/v1/mcp/servers/globex/planner/versions/1.0.0/submit", nil)) user, err := testDB.CreateUser(ctx, store.CreateUserParams{Email: "global-rev@x.test"}) if err != nil { @@ -839,25 +691,12 @@ func TestReviewHandler_SelfApprovalForbidden(t *testing.T) { approve: "/api/v1/mcp/servers/acme/weather/versions/1.0.0/approve", body: `{"revision":1}`, }, - { - name: "agent version", - seed: func(t *testing.T) { seedDraftAgentForHandler(t, "acme", "planner", "0.1.0") }, - submit: "/api/v1/agents/acme/planner/versions/0.1.0/submit", - approve: "/api/v1/agents/acme/planner/versions/0.1.0/approve", - body: `{"revision":1}`, - }, { name: "mcp deletion", seed: func(t *testing.T) { seedDraftMCPServerVersion(t, "acme", "weather", "1.0.0") }, submit: "/api/v1/mcp/servers/acme/weather/deletion-request", approve: "/api/v1/mcp/servers/acme/weather/deletion-request/approve", }, - { - name: "agent deletion", - seed: func(t *testing.T) { seedDraftAgentForHandler(t, "acme", "planner", "0.1.0") }, - submit: "/api/v1/agents/acme/planner/deletion-request", - approve: "/api/v1/agents/acme/planner/deletion-request/approve", - }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/server/internal/http/handlers/router_security_test.go b/server/internal/http/handlers/router_security_test.go index 31b2adca..cf67f2d2 100644 --- a/server/internal/http/handlers/router_security_test.go +++ b/server/internal/http/handlers/router_security_test.go @@ -70,8 +70,8 @@ func fireSecure(router http.Handler, method, path, token string) *httptest.Respo // no session → 401, a non-admin session → 403, a Server-Admin session → // neither. These routes resolve their publisher from the path (or are // Server-Admin-only), so the matrix is independent of the request body. The -// body-authorized create routes (POST /mcp/servers, /agents) have their own -// per-handler role tests. +// body-authorized create route (POST /mcp/servers) has its own per-handler +// role tests. func TestRouter_AdminRoutes_AuthEnforcement(t *testing.T) { resetTables(t) router, tokenFor := buildSecureRouter(t) @@ -82,10 +82,6 @@ func TestRouter_AdminRoutes_AuthEnforcement(t *testing.T) { {http.MethodPost, "/api/v1/mcp/servers/ns/slug/visibility"}, {http.MethodPost, "/api/v1/mcp/servers/ns/slug/versions"}, {http.MethodPost, "/api/v1/mcp/servers/ns/slug/versions/1.0.0/publish"}, - {http.MethodPost, "/api/v1/agents/ns/slug/deprecate"}, - {http.MethodPost, "/api/v1/agents/ns/slug/visibility"}, - {http.MethodPost, "/api/v1/agents/ns/slug/versions"}, - {http.MethodPost, "/api/v1/agents/ns/slug/versions/1.0.0/publish"}, {http.MethodGet, "/api/v1/stats"}, {http.MethodGet, "/api/v1/audit"}, {http.MethodGet, "/api/v1/users/some-id/grants"}, diff --git a/server/internal/http/handlers/stats_test.go b/server/internal/http/handlers/stats_test.go index c1a3c2b2..e7b0af02 100644 --- a/server/internal/http/handlers/stats_test.go +++ b/server/internal/http/handlers/stats_test.go @@ -34,12 +34,11 @@ func getStats(t *testing.T) map[string]int { if rec.Code != http.StatusOK { t.Fatalf("stats: status = %d, want 200; body: %s", rec.Code, rec.Body.String()) } - // The response has flat int totals (mcp_servers/agents/publishers) alongside + // The response has flat int totals (mcp_servers/publishers) alongside // nested *_status_breakdown objects. Decode the top-level fields we care // about explicitly so the nested objects don't break the int unmarshal. var shape struct { MCPServers int `json:"mcp_servers"` - Agents int `json:"agents"` Publishers int `json:"publishers"` } if err := json.NewDecoder(rec.Body).Decode(&shape); err != nil { @@ -47,7 +46,6 @@ func getStats(t *testing.T) map[string]int { } return map[string]int{ "mcp_servers": shape.MCPServers, - "agents": shape.Agents, "publishers": shape.Publishers, } } @@ -56,7 +54,7 @@ func TestStatsHandler_ZeroOnEmptyDB(t *testing.T) { resetTables(t) counts := getStats(t) - for _, key := range []string{"mcp_servers", "agents", "publishers"} { + for _, key := range []string{"mcp_servers", "publishers"} { if counts[key] != 0 { t.Errorf("%s = %d, want 0", key, counts[key]) } @@ -69,7 +67,7 @@ func TestStatsHandler_CountsMatchInserts(t *testing.T) { pubID := seedPublisher(t, "stats-pub", "Stats Pub") - // Insert 2 MCP servers and 1 agent. + // Insert 2 MCP servers. for _, slug := range []string{"srv-1", "srv-2"} { _, err := testDB.CreateMCPServer(ctx, store.CreateMCPServerParams{ PublisherID: pubID, Slug: slug, Name: slug, @@ -78,12 +76,6 @@ func TestStatsHandler_CountsMatchInserts(t *testing.T) { t.Fatalf("CreateMCPServer(%q): %v", slug, err) } } - _, err := testDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "ag-1", Name: "Ag 1", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } counts := getStats(t) @@ -93,9 +85,6 @@ func TestStatsHandler_CountsMatchInserts(t *testing.T) { if counts["mcp_servers"] != 2 { t.Errorf("mcp_servers = %d, want 2", counts["mcp_servers"]) } - if counts["agents"] != 1 { - t.Errorf("agents = %d, want 1", counts["agents"]) - } } func TestStatsHandler_IncludesPrivateAndDraftEntries(t *testing.T) { @@ -129,7 +118,7 @@ func TestStatsHandler_ResponseShape(t *testing.T) { if err := json.NewDecoder(rec.Body).Decode(&raw); err != nil { t.Fatalf("decode: %v", err) } - for _, key := range []string{"mcp_servers", "agents", "publishers"} { + for _, key := range []string{"mcp_servers", "publishers"} { if _, ok := raw[key]; !ok { t.Errorf("response missing key %q", key) } diff --git a/server/internal/http/handlers/testmain_test.go b/server/internal/http/handlers/testmain_test.go index 07aa3edb..ae6a1124 100644 --- a/server/internal/http/handlers/testmain_test.go +++ b/server/internal/http/handlers/testmain_test.go @@ -50,7 +50,7 @@ func TestMain(m *testing.M) { func resetTables(t *testing.T) { t.Helper() _, err := testDB.Pool.Exec(context.Background(), - `TRUNCATE agent_versions, agents, mcp_server_versions, mcp_servers, publishers, audit_log, reports, role_grants, group_members, groups, users, instance_tags RESTART IDENTITY CASCADE`) + `TRUNCATE mcp_server_versions, mcp_servers, publishers, audit_log, reports, role_grants, group_members, groups, users, instance_tags RESTART IDENTITY CASCADE`) if err != nil { t.Fatalf("truncating tables: %v", err) } diff --git a/server/internal/http/handlers/url_validation_test.go b/server/internal/http/handlers/url_validation_test.go index 4441f306..bc9dd365 100644 --- a/server/internal/http/handlers/url_validation_test.go +++ b/server/internal/http/handlers/url_validation_test.go @@ -56,26 +56,6 @@ func TestMCPHandler_CreateServer_RejectsNonHTTPURLs(t *testing.T) { } } -func TestAgentHandler_CreateVersion_RejectsNonHTTPURLs(t *testing.T) { - resetTables(t) - seedAgent(t, "ag-url", "ag-url") - r := newAgentRouter() - - tests := []struct { - name, payload, field string - }{ - {"javascript endpoint", `{"version":"1.0.0","endpoint_url":"javascript:alert(1)"}`, "endpoint_url"}, - {"data documentation", `{"version":"1.0.0","endpoint_url":"https://a.example","documentation_url":"data:text/html,x"}`, "documentation_url"}, - {"ftp icon", `{"version":"1.0.0","endpoint_url":"https://a.example","icon_url":"ftp://a.example/i.png"}`, "icon_url"}, - {"javascript provider url", `{"version":"1.0.0","endpoint_url":"https://a.example","provider":{"organization":"Acme","url":"javascript:alert(1)"}}`, "provider.url"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assertURLProblem(t, fire(r, adminAgentCtx(), http.MethodPost, "/api/v1/agents/ag-url/ag-url/versions", tt.payload), tt.field) - }) - } -} - func TestEntryChangeHandler_MetadataEditRejectsNonHTTPURLs(t *testing.T) { resetTables(t) srvID := seedPublishedMCPForHandler(t, "acme", "weather") diff --git a/server/internal/http/handlers/visibility.go b/server/internal/http/handlers/visibility.go index 3366ab5f..332cb582 100644 --- a/server/internal/http/handlers/visibility.go +++ b/server/internal/http/handlers/visibility.go @@ -78,66 +78,3 @@ func (h *MCPHandlers) SetVisibility(w http.ResponseWriter, r *http.Request) { writeJSON(w, r, http.StatusOK, map[string]string{"visibility": body.Visibility}) } - -// SetAgentVisibility handles POST /api/v1/agents/{namespace}/{slug}/visibility. -func (h *AgentHandlers) SetVisibility(w http.ResponseWriter, r *http.Request) { - ns := chi.URLParam(r, "namespace") - slug := chi.URLParam(r, "slug") - - var body struct { - Visibility string `json:"visibility"` - } - if !decodeJSON(w, r, &body) { - return - } - if body.Visibility != "public" && body.Visibility != "private" { - problem.Write(w, http.StatusUnprocessableEntity, "validation-error", - `visibility must be "public" or "private"`, r.URL.Path) - return - } - - agent, err := h.db.GetAgent(r.Context(), ns, slug, false) - if errors.Is(err, store.ErrNotFound) { - problem.Write(w, http.StatusNotFound, "not-found", - fmt.Sprintf("agent '%s/%s' does not exist", ns, slug), r.URL.Path) - return - } - if err != nil { - internalError(w, r, err) - return - } - - // Public exposure requires an approved (published) version (see the MCP - // handler note). Going back to private is always allowed. - if body.Visibility == "public" && agent.Status != domain.StatusPublished && agent.Status != domain.StatusDeprecated { - problem.Write(w, http.StatusConflict, "visibility-requires-approval", - "This entry has no approved version yet; submit it and have a Reviewer approve it before making it public.", r.URL.Path) - return - } - - if !auth.IsServerAdminFromContext(r.Context()) { - enqueueEntryChange(w, r, h.db, h.audit, domain.EntryResourceAgent, agent.ID, ns, slug, - domain.EntryChangeVisibility, map[string]string{"visibility": body.Visibility}, - domain.ActionAgentChangeRequested) - return - } - - if err := h.db.SetAgentVisibility(r.Context(), agent.ID, domain.Visibility(body.Visibility)); err != nil { - internalError(w, r, err) - return - } - - subject, email := auditActor(r.Context()) - h.audit.LogAuditEvent(r.Context(), domain.AuditEvent{ - ActorSubject: subject, - ActorEmail: email, - Action: domain.ActionAgentVisibility, - ResourceType: "agent", - ResourceID: agent.ID, - ResourceNS: ns, - ResourceSlug: slug, - Metadata: map[string]any{"visibility": body.Visibility}, - }) - - writeJSON(w, r, http.StatusOK, map[string]string{"visibility": body.Visibility}) -} diff --git a/server/internal/http/handlers/visibility_test.go b/server/internal/http/handlers/visibility_test.go index 4b977dca..dfe79c9a 100644 --- a/server/internal/http/handlers/visibility_test.go +++ b/server/internal/http/handlers/visibility_test.go @@ -136,111 +136,3 @@ func TestMCPHandler_SetVisibility_UnknownServer(t *testing.T) { t.Errorf("status = %d, want 404", rec.Code) } } - -// ─── Agent Visibility ──────────────────────────────────────────────────────── - -func TestAgentHandler_SetVisibility_Valid(t *testing.T) { - resetTables(t) - seedAgent(t, "agvis-ns", "agvis-ag") - // Promote to published (an approved version) so the public flip is allowed. - createAgentVersion(t, "agvis-ns", "agvis-ag", "1.0.0") - ag, err := testDB.GetAgent(context.Background(), "agvis-ns", "agvis-ag", false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if err := testDB.PublishAgentVersion(context.Background(), ag.ID, "1.0.0"); err != nil { - t.Fatalf("PublishAgentVersion: %v", err) - } - - r := newAgentRouter() - - tests := []struct { - visibility string - }{ - {"public"}, - {"private"}, - } - - for _, tt := range tests { - t.Run(tt.visibility, func(t *testing.T) { - payload := `{"visibility":"` + tt.visibility + `"}` - req := httptest.NewRequest(http.MethodPost, - "/api/v1/agents/agvis-ns/agvis-ag/visibility", - bytes.NewBufferString(payload)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - r.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String()) - } - var body map[string]string - json.NewDecoder(rec.Body).Decode(&body) //nolint:errcheck - if body["visibility"] != tt.visibility { - t.Errorf("visibility = %q, want %q", body["visibility"], tt.visibility) - } - }) - } -} - -// TestAgentHandler_SetVisibility_PublicRequiresApproval verifies an unapproved -// draft agent cannot be made public (409); private stays allowed. -func TestAgentHandler_SetVisibility_PublicRequiresApproval(t *testing.T) { - resetTables(t) - seedAgent(t, "agvis-draft-ns", "agvis-draft-ag") // draft, never published - - post := func(vis string) int { - req := httptest.NewRequest(http.MethodPost, - "/api/v1/agents/agvis-draft-ns/agvis-draft-ag/visibility", - bytes.NewBufferString(`{"visibility":"`+vis+`"}`)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - return rec.Code - } - - if code := post("public"); code != http.StatusConflict { - t.Errorf("public on an unapproved draft: status = %d, want 409", code) - } - if code := post("private"); code != http.StatusOK { - t.Errorf("private on a draft: status = %d, want 200", code) - } -} - -func TestAgentHandler_SetVisibility_InvalidValue(t *testing.T) { - resetTables(t) - seedAgent(t, "agvis-inv-ns", "agvis-inv-ag") - - payload := `{"visibility":"unknown"}` - req := httptest.NewRequest(http.MethodPost, - "/api/v1/agents/agvis-inv-ns/agvis-inv-ag/visibility", - bytes.NewBufferString(payload)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusUnprocessableEntity { - t.Errorf("status = %d, want 422", rec.Code) - } -} - -func TestAgentHandler_SetVisibility_UnknownAgent(t *testing.T) { - resetTables(t) - seedPublisher(t, "agvis-404-ns", "agvis-404-ns") - - payload := `{"visibility":"public"}` - req := httptest.NewRequest(http.MethodPost, - "/api/v1/agents/agvis-404-ns/nonexistent/visibility", - bytes.NewBufferString(payload)) - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(adminAgentCtx()) - rec := httptest.NewRecorder() - newAgentRouter().ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Errorf("status = %d, want 404", rec.Code) - } -} diff --git a/server/internal/http/router.go b/server/internal/http/router.go index b6c51258..6f1199bd 100644 --- a/server/internal/http/router.go +++ b/server/internal/http/router.go @@ -36,9 +36,8 @@ type RouterDeps struct { // reads on /api/v1, in requests per minute. Zero falls back to 1000. PublicRateLimitRPM int // PublicBaseURL is the externally reachable URL of this deployment. - // Threaded into the global agent card and the OIDC post-login/logout - // redirects. Empty makes the agent-card handler return HTTP 500 rather - // than silently advertise localhost. + // Threaded into the OIDC post-login/logout redirects; empty falls back to + // "/". PublicBaseURL string // Tokens mints / verifies registry access tokens (Ed25519 JWTs). Nil only in // route-walk tests, which makes Authenticate a pass-through. @@ -104,12 +103,10 @@ func buildMux(deps RouterDeps) *chi.Mux { // ── Handlers ────────────────────────────────────────────────────────────── mcpH := handlers.NewMCPHandlers(deps.DB, deps.DB, deps.Metrics) - agentH := handlers.NewAgentHandlers(deps.DB, deps.DB, deps.Metrics) pubH := handlers.NewPublisherHandlers(deps.DB, deps.DB) revH := handlers.NewReviewHandlers(deps.DB, deps.DB) auditH := handlers.NewAuditHandlers(deps.DB) statsH := handlers.NewStatsHandlers(deps.DB) - cardH := handlers.NewAgentCardHandlers(deps.DB, deps.Logger, deps.PublicBaseURL) reportH := handlers.NewReportHandlers(deps.DB, deps.TrustedProxy) changelogH := handlers.NewChangelogHandlers(deps.DB) authH := handlers.NewAuthHandlers(deps.Tokens, deps.Refresh, deps.DB, deps.LocalLoginEnabled) @@ -160,7 +157,6 @@ func buildMux(deps RouterDeps) *chi.Mux { return pub.ID, nil } requireMCPServerNS := auth.RequirePublisherRole(deps.DB, domain.RoleEditor, resolvePublisherByNamespace) - requireAgentNS := auth.RequirePublisherRole(deps.DB, domain.RoleEditor, resolvePublisherByNamespace) requireReviewerNS := auth.RequirePublisherRole(deps.DB, domain.RoleReviewer, resolvePublisherByNamespace) r := chi.NewRouter() @@ -204,11 +200,6 @@ func buildMux(deps RouterDeps) *chi.Mux { // ── Well-known endpoints ────────────────────────────────────────────────── // Registry JWKS: the Ed25519 public keys that verify registry access tokens. r.Get("/.well-known/jwks.json", handlers.JWKS(deps.Tokens)) - // Global registry agent card (makes the registry a first-class A2A citizen) - r.Get("/.well-known/agent-card.json", cardH.GlobalAgentCard) - - // ── Per-agent A2A card (public, outside /api/v1 per A2A spec path) ──────── - r.Get("/agents/{namespace}/{slug}/.well-known/agent-card.json", cardH.PerAgentCard) // ── API v1 ──────────────────────────────────────────────────────────────── publicRLMax := deps.PublicRateLimitRPM @@ -379,50 +370,6 @@ func buildMux(deps RouterDeps) *chi.Mux { discoveryRL := middleware.RateLimit(discoveryRLMax, time.Minute, deps.Metrics, deps.TrustedProxy) r.With(discoveryRL).Post("/mcp/tool-discoveries", discoveryH.Discover) - // Agents - r.Route("/agents", func(r chi.Router) { - r.With(publicRL).Get("/", agentH.ListAgents) - // Create is publisher-scoped; see the MCP create note. - r.Post("/", agentH.CreateAgent) - - r.Route("/{namespace}/{slug}", func(r chi.Router) { - r.With(publicRL).Get("/", agentH.GetAgent) - r.With(requireAgentNS).Patch("/", agentH.PatchAgent) - // Same reasoning as MCP servers: bypass-the-workflow path - // stays admin-only. - r.With(auth.RequireAdmin).Delete("/", agentH.DeleteAgent) - r.With(requireAgentNS).Post("/deprecate", agentH.DeprecateAgent) - r.With(requireAgentNS).Post("/undeprecate", agentH.UndeprecateAgent) - // Editor/Admin; public requires an approved version (see MCP note). - r.With(requireAgentNS).Post("/visibility", agentH.SetVisibility) - r.With(publicRL).Post("/view", agentH.RecordView) - r.With(publicRL).Post("/copy", agentH.RecordCopy) - r.With(publicRL).Get("/activity", agentH.ListAgentActivity) - - r.Route("/versions", func(r chi.Router) { - r.With(publicRL).Get("/", agentH.ListVersions) - r.With(requireAgentNS).Post("/", agentH.CreateVersion) - r.With(publicRL).Get("/{version}", agentH.GetVersion) - // Approver action (see the MCP publish note): Reviewer / Server Admin. - r.With(requireReviewerNS).Post("/{version}/publish", agentH.PublishVersion) - r.With(requireAgentNS).Patch("/{version}/status", agentH.PatchVersionStatus) - // Change-approval workflow. - r.With(requireAgentNS).Post("/{version}/submit", revH.SubmitAgentVersion) - r.With(requireAgentNS).Post("/{version}/withdraw", revH.WithdrawAgentVersion) - r.With(requireReviewerNS).Post("/{version}/approve", revH.ApproveAgentVersion) - r.With(requireReviewerNS).Post("/{version}/reject", revH.RejectAgentVersion) - }) - // Pending-deletion review flow. - r.With(requireAgentNS).Post("/deletion-request", revH.RequestAgentDeletion) - r.With(requireReviewerNS).Post("/deletion-request/approve", revH.ApproveAgentDeletion) - r.With(requireReviewerNS).Post("/deletion-request/reject", revH.RejectAgentDeletion) - // Entry-change review flow (visibility / deprecate / metadata edit). - r.With(requireAgentNS).Post("/change-request/withdraw", revH.WithdrawAgentChange) - r.With(requireReviewerNS).Post("/change-request/approve", revH.ApproveAgentChange) - r.With(requireReviewerNS).Post("/change-request/reject", revH.RejectAgentChange) - }) - }) - // Public stats (published + public only, no auth required) r.With(publicRL).Get("/public-stats", statsH.GetPublicStats) diff --git a/server/internal/http/router_admin_guard_test.go b/server/internal/http/router_admin_guard_test.go index d99a4b6f..cd3cbc85 100644 --- a/server/internal/http/router_admin_guard_test.go +++ b/server/internal/http/router_admin_guard_test.go @@ -68,8 +68,6 @@ func TestAllWriteRoutesRequireAdmin(t *testing.T) { // not require authentication. "POST /api/v1/mcp/servers/{namespace}/{slug}/view": "public view counter", "POST /api/v1/mcp/servers/{namespace}/{slug}/copy": "public copy counter", - "POST /api/v1/agents/{namespace}/{slug}/view": "public view counter", - "POST /api/v1/agents/{namespace}/{slug}/copy": "public copy counter", // Community-submitted issue reports — unauthenticated users can file // reports. List and Patch on /reports remain admin-only. @@ -190,8 +188,6 @@ func TestPublicWriteRoutesBypassAdmin(t *testing.T) { publicWriteKeys := []string{ "POST /api/v1/mcp/servers/{namespace}/{slug}/view", "POST /api/v1/mcp/servers/{namespace}/{slug}/copy", - "POST /api/v1/agents/{namespace}/{slug}/view", - "POST /api/v1/agents/{namespace}/{slug}/copy", "POST /api/v1/reports", "POST /api/v1/auth/login", "POST /api/v1/auth/refresh", diff --git a/server/internal/observability/metrics.go b/server/internal/observability/metrics.go index 199280f6..3a9ab3b2 100644 --- a/server/internal/observability/metrics.go +++ b/server/internal/observability/metrics.go @@ -17,7 +17,6 @@ type Metrics struct { // Registry counters MCPServersTotal metric.Int64UpDownCounter - AgentsTotal metric.Int64UpDownCounter // Auth AuthFailures metric.Int64Counter @@ -60,14 +59,6 @@ func InitMetrics() (*Metrics, error) { return nil, fmt.Errorf("creating registry.mcp.servers.total: %w", err) } - agentsTotal, err := m.Int64UpDownCounter( - "registry.agents.total", - metric.WithDescription("Live count of agent entries"), - ) - if err != nil { - return nil, fmt.Errorf("creating registry.agents.total: %w", err) - } - authFailures, err := m.Int64Counter( "registry.auth.failures", metric.WithDescription("Authentication and authorisation failures"), @@ -96,7 +87,6 @@ func InitMetrics() (*Metrics, error) { HTTPRequestsTotal: reqTotal, HTTPRequestDuration: reqDuration, MCPServersTotal: mcpServersTotal, - AgentsTotal: agentsTotal, AuthFailures: authFailures, RateLimitHits: rateLimitHits, ToolDiscoveries: toolDiscoveries, diff --git a/server/internal/observability/observability_test.go b/server/internal/observability/observability_test.go index bbca321f..35f22cee 100644 --- a/server/internal/observability/observability_test.go +++ b/server/internal/observability/observability_test.go @@ -211,9 +211,6 @@ func TestInitMetrics_ReturnsAllInstruments(t *testing.T) { if m.MCPServersTotal == nil { t.Error("MCPServersTotal is nil") } - if m.AgentsTotal == nil { - t.Error("AgentsTotal is nil") - } if m.AuthFailures == nil { t.Error("AuthFailures is nil") } diff --git a/server/internal/problem/problem_test.go b/server/internal/problem/problem_test.go index daa087e6..fe92019c 100644 --- a/server/internal/problem/problem_test.go +++ b/server/internal/problem/problem_test.go @@ -16,7 +16,7 @@ import ( func TestWrite_HappyPath(t *testing.T) { rec := httptest.NewRecorder() - problem.Write(rec, http.StatusNotFound, "not-found", "agent does not exist", "/api/v1/agents/x/y") + problem.Write(rec, http.StatusNotFound, "not-found", "MCP server does not exist", "/api/v1/mcp/servers/x/y") if rec.Code != http.StatusNotFound { t.Errorf("status = %d, want 404", rec.Code) @@ -38,10 +38,10 @@ func TestWrite_HappyPath(t *testing.T) { if got.Status != http.StatusNotFound { t.Errorf("Status = %d, want 404", got.Status) } - if got.Detail != "agent does not exist" { + if got.Detail != "MCP server does not exist" { t.Errorf("Detail = %q", got.Detail) } - if got.Instance != "/api/v1/agents/x/y" { + if got.Instance != "/api/v1/mcp/servers/x/y" { t.Errorf("Instance = %q", got.Instance) } if got.Errors != nil { diff --git a/server/internal/store/agent.go b/server/internal/store/agent.go deleted file mode 100644 index 1452e7d6..00000000 --- a/server/internal/store/agent.go +++ /dev/null @@ -1,1013 +0,0 @@ -package store - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" - - "github.com/haibread/ai-registry/internal/domain" -) - -// LatestAgentVersion is a summary of the most recently published agent version, -// embedded inline in list and detail responses. -type LatestAgentVersion struct { - Version string - EndpointURL string - Skills json.RawMessage - DefaultInputModes []string - DefaultOutputModes []string - Authentication json.RawMessage - ProtocolVersion string - Tags []string - PublishedAt *time.Time -} - -// AgentRow is a flat projection of an agent with its publisher namespace. -type AgentRow struct { - domain.Agent - LatestVersion *LatestAgentVersion -} - -// ListAgentsParams controls filtering and pagination for ListAgents. -type ListAgentsParams struct { - PublicOnly bool - Namespace string - PublisherIDs []string // when non-empty, restrict to these publisher ids (mine-scoped admin listing) - Status string // filter by status: "draft" | "published" | "deprecated" | "" (all non-deleted) - Visibility string // filter by visibility: "public" | "private" | "" (all); only meaningful when PublicOnly=false - Query string - Limit int32 - Cursor string - Sort string // sort order: "created_at_desc" (default), "updated_at_desc", "published_at_desc", "name_asc", "name_desc" - Featured *bool // when non-nil, filter by featured flag - Tag string // when non-empty, filter to agents whose latest published version carries this instance-tag slug - PublishedSince *time.Time // when non-nil, only entries whose latest version was published after this time - IncludeDeleted bool // when true, include agents with status='deleted' -} - -// ListAgents returns a paginated list of agents and the total count of rows -// that match the filters (before pagination). -func (db *DB) ListAgents(ctx context.Context, p ListAgentsParams) ([]AgentRow, int, error) { - ctx, span := startSpan(ctx, "ListAgents") - defer span.End() - - if p.Limit <= 0 || p.Limit > 100 { - p.Limit = 20 - } - - args := []any{} - argN := 1 - countArgN := 1 - filterWhere := "WHERE 1=1" - filterArgs := []any{} - - if p.PublicOnly { - filterWhere += fmt.Sprintf(" AND a.visibility = $%d", argN) - filterArgs = append(filterArgs, "public") - argN++ - countArgN++ - } else if p.Visibility != "" { - filterWhere += fmt.Sprintf(" AND a.visibility = $%d", argN) - filterArgs = append(filterArgs, p.Visibility) - argN++ - countArgN++ - } - if p.Status != "" { - filterWhere += fmt.Sprintf(" AND a.status = $%d", argN) - filterArgs = append(filterArgs, p.Status) - argN++ - countArgN++ - } else if !p.IncludeDeleted { - // By default, exclude deleted agents. - filterWhere += fmt.Sprintf(" AND a.status != $%d", argN) - filterArgs = append(filterArgs, "deleted") - argN++ - countArgN++ - } - if p.Namespace != "" { - filterWhere += fmt.Sprintf(" AND pub.slug = $%d", argN) - filterArgs = append(filterArgs, p.Namespace) - argN++ - countArgN++ - } - if len(p.PublisherIDs) > 0 { - // Mine-scoped admin listing: restrict to the publishers the caller holds - // a grant on. Combines with Namespace if both are set. - filterWhere += fmt.Sprintf(" AND a.publisher_id = ANY($%d)", argN) - filterArgs = append(filterArgs, p.PublisherIDs) - argN++ - countArgN++ - } - if p.Featured != nil { - filterWhere += fmt.Sprintf(" AND a.featured = $%d", argN) - filterArgs = append(filterArgs, *p.Featured) - argN++ - countArgN++ - } - // Post-join filters (reference lav.* columns only available after lateral join). - var postJoinFilter string - var postJoinFilterCount string - if p.Tag != "" { - // Tags live on version rows; the entry-level filter matches the - // latest published version's tags, mirroring what list responses show. - postJoinFilter += fmt.Sprintf(" AND $%d = ANY(lav.tags)", argN) - postJoinFilterCount += fmt.Sprintf(" AND $%d = ANY(lav.tags)", countArgN) - filterArgs = append(filterArgs, p.Tag) - argN++ - countArgN++ - } - if p.PublishedSince != nil { - postJoinFilter += fmt.Sprintf(" AND lav.published_at > $%d", argN) - postJoinFilterCount += fmt.Sprintf(" AND lav.published_at > $%d", countArgN) - filterArgs = append(filterArgs, *p.PublishedSince) - argN++ - countArgN++ - } - - tsQuery := prefixTSQuery(p.Query) - hasQuery := tsQuery != "" - if hasQuery { - filterWhere += fmt.Sprintf( - " AND a.search_vector @@ to_tsquery('english', $%d)", - argN, - ) - filterArgs = append(filterArgs, tsQuery) - argN++ - countArgN++ //nolint:ineffassign,staticcheck // kept in lockstep with argN so any arg appended below stays correctly numbered - } - - // Snapshot filterArgs before cursor / ORDER-BY args so the COUNT query - // can reuse just the filter portion. - countArgs := make([]any, len(filterArgs)) - copy(countArgs, filterArgs) - - args = append(args, filterArgs...) - - // Cursor (keyset pagination) — added to the main query only. - whereClause := filterWhere - if !hasQuery && p.Cursor != "" { - at, id, err := decodeCursor(p.Cursor) - if err != nil { - return nil, 0, ErrInvalidCursor - } - cursorCol := "a.created_at" - switch p.Sort { - case "updated_at_desc": - cursorCol = "a.updated_at" - case "published_at_desc": - cursorCol = "lav.published_at" - } - // For name-based sorts, cursor is not supported (cursor encodes a - // timestamp, not a name). Silently ignore the cursor. - if p.Sort != "name_asc" && p.Sort != "name_desc" { - whereClause += fmt.Sprintf(" AND (%s, a.id) < ($%d, $%d)", cursorCol, argN, argN+1) - args = append(args, at, id) - argN += 2 - } - } - - orderClause := "ORDER BY a.created_at DESC, a.id DESC" - if hasQuery { - orderClause = fmt.Sprintf( - "ORDER BY ts_rank(a.search_vector, to_tsquery('english', $%d)) DESC, a.created_at DESC", - argN, - ) - args = append(args, tsQuery) - argN++ - } else { - switch p.Sort { - case "updated_at_desc": - orderClause = "ORDER BY a.updated_at DESC, a.id DESC" - case "published_at_desc": - orderClause = "ORDER BY lav.published_at DESC NULLS LAST, a.id DESC" - case "name_asc": - orderClause = "ORDER BY a.name ASC, a.id ASC" - case "name_desc": - orderClause = "ORDER BY a.name DESC, a.id DESC" - } - } - - // Apply post-join filters to both main and count WHERE clauses. - if postJoinFilter != "" { - whereClause += postJoinFilter - filterWhere += postJoinFilterCount - } - - args = append(args, p.Limit) - q := fmt.Sprintf(` - SELECT a.id, pub.slug AS namespace, a.publisher_id, a.slug, a.name, - coalesce(a.description,''), a.visibility, a.status, a.featured, a.verified, - coalesce(lav.tags, '{}'), - coalesce(a.readme,''), a.view_count, a.copy_count, a.created_at, a.updated_at, - lav.version, lav.endpoint_url, lav.skills, lav.default_input_modes, - lav.default_output_modes, lav.authentication, lav.protocol_version, lav.published_at - FROM agents a - JOIN publishers pub ON pub.id = a.publisher_id - LEFT JOIN LATERAL ( - SELECT av.version, av.endpoint_url, av.skills, av.default_input_modes, - av.default_output_modes, av.authentication, av.protocol_version, av.tags, av.published_at - FROM agent_versions av - WHERE av.agent_id = a.id AND av.published_at IS NOT NULL - ORDER BY av.published_at DESC - LIMIT 1 - ) lav ON true - %s - %s - LIMIT $%d`, whereClause, orderClause, argN) - - rows, err := db.Pool.Query(ctx, q, args...) - if err != nil { - recordErr(span, err) - return nil, 0, fmt.Errorf("listing agents: %w", err) - } - defer rows.Close() - - var result []AgentRow - for rows.Next() { - var r AgentRow - var ( - lavVersion *string - lavEndpoint *string - lavSkills []byte - lavInputModes []string - lavOutputModes []string - lavAuth []byte - lavProto *string - lavPublishedAt *time.Time - ) - if err := rows.Scan( - &r.ID, &r.Namespace, &r.PublisherID, &r.Slug, &r.Name, - &r.Description, &r.Visibility, &r.Status, &r.Featured, &r.Verified, &r.Tags, - &r.Readme, &r.ViewCount, &r.CopyCount, &r.CreatedAt, &r.UpdatedAt, - &lavVersion, &lavEndpoint, &lavSkills, &lavInputModes, - &lavOutputModes, &lavAuth, &lavProto, &lavPublishedAt, - ); err != nil { - recordErr(span, err) - return nil, 0, fmt.Errorf("scanning agent row: %w", err) - } - if lavVersion != nil { - r.LatestVersion = &LatestAgentVersion{ - Version: *lavVersion, - EndpointURL: *lavEndpoint, - Skills: json.RawMessage(lavSkills), - DefaultInputModes: lavInputModes, - DefaultOutputModes: lavOutputModes, - Authentication: json.RawMessage(lavAuth), - ProtocolVersion: *lavProto, - PublishedAt: lavPublishedAt, - } - } - result = append(result, r) - } - if err := rows.Err(); err != nil { - recordErr(span, err) - return nil, 0, err - } - - // Separate COUNT query using the same filter conditions but without - // cursor / ORDER-BY so it reflects the full matching set. - // When post-join filters are present (e.g. published_since), the count - // query must include the lateral join so those conditions can reference lav.*. - var countQ string - if postJoinFilterCount != "" { - countQ = fmt.Sprintf(` - SELECT COUNT(*) - FROM agents a - JOIN publishers pub ON pub.id = a.publisher_id - LEFT JOIN LATERAL ( - SELECT av.published_at, av.tags - FROM agent_versions av - WHERE av.agent_id = a.id AND av.published_at IS NOT NULL - ORDER BY av.published_at DESC - LIMIT 1 - ) lav ON true - %s`, filterWhere) - } else { - countQ = fmt.Sprintf(` - SELECT COUNT(*) - FROM agents a - JOIN publishers pub ON pub.id = a.publisher_id - %s`, filterWhere) - } - - var total int - if err := db.Pool.QueryRow(ctx, countQ, countArgs...).Scan(&total); err != nil { - recordErr(span, err) - return nil, 0, fmt.Errorf("counting agents: %w", err) - } - - return result, total, nil -} - -// GetAgent retrieves a single agent by namespace and slug. -func (db *DB) GetAgent(ctx context.Context, namespace, slug string, publicOnly bool) (*AgentRow, error) { - ctx, span := startSpan(ctx, "GetAgent") - defer span.End() - - q := ` - SELECT a.id, pub.slug, a.publisher_id, a.slug, a.name, - coalesce(a.description,''), a.visibility, a.status, a.featured, a.verified, - coalesce(lav.tags, '{}'), - coalesce(a.readme,''), a.view_count, a.copy_count, a.created_at, a.updated_at, - lav.version, lav.endpoint_url, lav.skills, lav.default_input_modes, - lav.default_output_modes, lav.authentication, lav.protocol_version, lav.published_at - FROM agents a - JOIN publishers pub ON pub.id = a.publisher_id - LEFT JOIN LATERAL ( - SELECT av.version, av.endpoint_url, av.skills, av.default_input_modes, - av.default_output_modes, av.authentication, av.protocol_version, av.tags, av.published_at - FROM agent_versions av - WHERE av.agent_id = a.id AND av.published_at IS NOT NULL - ORDER BY av.published_at DESC - LIMIT 1 - ) lav ON true - WHERE pub.slug = $1 AND a.slug = $2 AND a.status != 'deleted'` - args := []any{namespace, slug} - if publicOnly { - q += " AND a.visibility = 'public'" - } - - var r AgentRow - var ( - lavVersion *string - lavEndpoint *string - lavSkills []byte - lavInputModes []string - lavOutputModes []string - lavAuth []byte - lavProto *string - lavPublishedAt *time.Time - ) - err := db.Pool.QueryRow(ctx, q, args...).Scan( - &r.ID, &r.Namespace, &r.PublisherID, &r.Slug, &r.Name, - &r.Description, &r.Visibility, &r.Status, &r.Featured, &r.Verified, &r.Tags, - &r.Readme, &r.ViewCount, &r.CopyCount, &r.CreatedAt, &r.UpdatedAt, - &lavVersion, &lavEndpoint, &lavSkills, &lavInputModes, - &lavOutputModes, &lavAuth, &lavProto, &lavPublishedAt, - ) - if errors.Is(err, pgx.ErrNoRows) { - recordErr(span, ErrNotFound) - return nil, ErrNotFound - } - if err != nil { - recordErr(span, err) - return nil, fmt.Errorf("getting agent: %w", err) - } - if lavVersion != nil { - r.LatestVersion = &LatestAgentVersion{ - Version: *lavVersion, - EndpointURL: *lavEndpoint, - Skills: json.RawMessage(lavSkills), - DefaultInputModes: lavInputModes, - DefaultOutputModes: lavOutputModes, - Authentication: json.RawMessage(lavAuth), - ProtocolVersion: *lavProto, - Tags: r.Tags, // entry tags ARE the latest version's tags - PublishedAt: lavPublishedAt, - } - } - return &r, nil -} - -// CreateAgentParams holds the fields needed to insert a new agent. -// PublisherID is required — resources are publisher-scoped. -type CreateAgentParams struct { - PublisherID string - Slug string - Name string - Description string -} - -// CreateAgent inserts a new agent (draft, private by default). Returns -// ErrConflict on a duplicate (publisher_id, slug) and ErrNotFound when the -// publisher_id FK does not resolve. -func (db *DB) CreateAgent(ctx context.Context, p CreateAgentParams) (*domain.Agent, error) { - ctx, span := startSpan(ctx, "CreateAgent") - defer span.End() - - if p.PublisherID == "" { - return nil, fmt.Errorf("CreateAgent: PublisherID is required") - } - - id := NewULID() - now := time.Now().UTC() - - _, err := db.Pool.Exec(ctx, ` - INSERT INTO agents (id, publisher_id, slug, name, description, visibility, status, created_at, updated_at) - VALUES ($1,$2,$3,$4,$5,'private','draft',$6,$6)`, - id, p.PublisherID, p.Slug, p.Name, p.Description, now, - ) - if err != nil { - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) { - switch pgErr.Code { - case "23505": - recordErr(span, ErrConflict) - return nil, ErrConflict - case "23503": - recordErr(span, ErrNotFound) - return nil, ErrNotFound - } - } - recordErr(span, err) - return nil, fmt.Errorf("creating agent: %w", err) - } - - return &domain.Agent{ - ID: id, - PublisherID: p.PublisherID, - Slug: p.Slug, - Name: p.Name, - Description: p.Description, - Visibility: domain.VisibilityPrivate, - Status: domain.StatusDraft, - CreatedAt: now, - UpdatedAt: now, - }, nil -} - -// ListAgentVersions returns versions for a given agent ID. When -// publicOnly is true the result excludes content that has not reached -// `published` (drafts, pending_review, rejected) so the workflow does -// not leak to anonymous callers. -func (db *DB) ListAgentVersions(ctx context.Context, agentID string, publicOnly bool) ([]domain.AgentVersion, error) { - ctx, span := startSpan(ctx, "ListAgentVersions") - defer span.End() - - where := "WHERE agent_id = $1" - if publicOnly { - where += " AND published_at IS NOT NULL" - } - rows, err := db.Pool.Query(ctx, ` - SELECT id, agent_id, version, endpoint_url, skills, capabilities, authentication, - default_input_modes, default_output_modes, provider, - coalesce(documentation_url,''), coalesce(icon_url,''), tags, - protocol_version, status, coalesce(status_message,''), status_changed_at, published_at, created_at, updated_at, - review_state, revision, submitted_at, coalesce(submitted_by,''), coalesce(submitted_by_email,''), - reviewed_at, coalesce(reviewed_by,''), coalesce(reviewed_by_email,''), - coalesce(review_decision,''), coalesce(rejection_reason,''), request_public - FROM agent_versions - `+where+` - ORDER BY created_at DESC`, agentID) - if err != nil { - recordErr(span, err) - return nil, fmt.Errorf("listing agent versions: %w", err) - } - defer rows.Close() - - var result []domain.AgentVersion - for rows.Next() { - v, err := scanAgentVersion(rows) - if err != nil { - recordErr(span, err) - return nil, err - } - result = append(result, v) - } - if err := rows.Err(); err != nil { - recordErr(span, err) - return nil, err - } - return result, nil -} - -// GetAgentVersion retrieves a specific version by agent ID and semver -// string. When publicOnly is true a non-published row appears as -// ErrNotFound to the caller. -func (db *DB) GetAgentVersion(ctx context.Context, agentID, version string, publicOnly bool) (*domain.AgentVersion, error) { - ctx, span := startSpan(ctx, "GetAgentVersion") - defer span.End() - - where := "WHERE agent_id = $1 AND version = $2" - if publicOnly { - where += " AND published_at IS NOT NULL" - } - row := db.Pool.QueryRow(ctx, ` - SELECT id, agent_id, version, endpoint_url, skills, capabilities, authentication, - default_input_modes, default_output_modes, provider, - coalesce(documentation_url,''), coalesce(icon_url,''), tags, - protocol_version, status, coalesce(status_message,''), status_changed_at, published_at, created_at, updated_at, - review_state, revision, submitted_at, coalesce(submitted_by,''), coalesce(submitted_by_email,''), - reviewed_at, coalesce(reviewed_by,''), coalesce(reviewed_by_email,''), - coalesce(review_decision,''), coalesce(rejection_reason,''), request_public - FROM agent_versions - `+where, agentID, version) - - v, err := scanAgentVersion(row) - if errors.Is(err, pgx.ErrNoRows) { - recordErr(span, ErrNotFound) - return nil, ErrNotFound - } - if err != nil { - recordErr(span, err) - return nil, fmt.Errorf("getting agent version: %w", err) - } - return &v, nil -} - -// GetLatestPublishedAgentVersion returns the most recently published version for an agent. -func (db *DB) GetLatestPublishedAgentVersion(ctx context.Context, agentID string) (*domain.AgentVersion, error) { - ctx, span := startSpan(ctx, "GetLatestPublishedAgentVersion") - defer span.End() - - row := db.Pool.QueryRow(ctx, ` - SELECT id, agent_id, version, endpoint_url, skills, capabilities, authentication, - default_input_modes, default_output_modes, provider, - coalesce(documentation_url,''), coalesce(icon_url,''), tags, - protocol_version, status, coalesce(status_message,''), status_changed_at, published_at, created_at, updated_at, - review_state, revision, submitted_at, coalesce(submitted_by,''), coalesce(submitted_by_email,''), - reviewed_at, coalesce(reviewed_by,''), coalesce(reviewed_by_email,''), - coalesce(review_decision,''), coalesce(rejection_reason,''), request_public - FROM agent_versions - WHERE agent_id = $1 AND published_at IS NOT NULL - ORDER BY published_at DESC - LIMIT 1`, agentID) - - v, err := scanAgentVersion(row) - if errors.Is(err, pgx.ErrNoRows) { - recordErr(span, ErrNotFound) - return nil, ErrNotFound - } - if err != nil { - recordErr(span, err) - return nil, fmt.Errorf("getting latest published agent version: %w", err) - } - return &v, nil -} - -// CreateAgentVersionParams holds the fields needed to insert a new agent version. -type CreateAgentVersionParams struct { - AgentID string - Version string - EndpointURL string - Skills json.RawMessage - Capabilities json.RawMessage - Authentication json.RawMessage - DefaultInputModes []string - DefaultOutputModes []string - Provider json.RawMessage - DocumentationURL string - IconURL string - Tags []string // instance-tag slugs, validated by the handler against the active vocabulary - ProtocolVersion string -} - -// CreateAgentVersion inserts a new draft agent version. -func (db *DB) CreateAgentVersion(ctx context.Context, p CreateAgentVersionParams) (*domain.AgentVersion, error) { - ctx, span := startSpan(ctx, "CreateAgentVersion") - defer span.End() - - if len(p.Skills) == 0 { - p.Skills = json.RawMessage("[]") - } - if len(p.Capabilities) == 0 { - p.Capabilities = json.RawMessage("{}") - } - if len(p.Authentication) == 0 { - p.Authentication = json.RawMessage("[]") - } - if len(p.DefaultInputModes) == 0 { - p.DefaultInputModes = []string{"text/plain"} - } - if len(p.DefaultOutputModes) == 0 { - p.DefaultOutputModes = []string{"text/plain"} - } - if p.Tags == nil { - p.Tags = []string{} - } - - id := NewULID() - now := time.Now().UTC() - - _, err := db.Pool.Exec(ctx, ` - INSERT INTO agent_versions - (id, agent_id, version, endpoint_url, skills, capabilities, authentication, - default_input_modes, default_output_modes, provider, - documentation_url, icon_url, tags, protocol_version) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)`, - id, p.AgentID, p.Version, p.EndpointURL, - p.Skills, p.Capabilities, p.Authentication, - p.DefaultInputModes, p.DefaultOutputModes, p.Provider, - p.DocumentationURL, p.IconURL, p.Tags, p.ProtocolVersion, - ) - if err != nil { - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) && pgErr.Code == "23505" { - recordErr(span, ErrConflict) - return nil, ErrConflict - } - recordErr(span, err) - return nil, fmt.Errorf("creating agent version: %w", err) - } - - return &domain.AgentVersion{ - ID: id, - AgentID: p.AgentID, - Version: p.Version, - EndpointURL: p.EndpointURL, - Skills: p.Skills, - Capabilities: p.Capabilities, - Authentication: p.Authentication, - DefaultInputModes: p.DefaultInputModes, - DefaultOutputModes: p.DefaultOutputModes, - Provider: p.Provider, - DocumentationURL: p.DocumentationURL, - IconURL: p.IconURL, - Tags: p.Tags, - ProtocolVersion: p.ProtocolVersion, - Status: domain.VersionStatusActive, - StatusChangedAt: now, - CreatedAt: now, - UpdatedAt: now, - }, nil -} - -// PublishAgentVersion sets published_at on a draft version. -func (db *DB) PublishAgentVersion(ctx context.Context, agentID, version string) error { - ctx, span := startSpan(ctx, "PublishAgentVersion") - defer span.End() - - // Publishing the version and promoting the parent must be atomic: if the - // promotion is lost, the version is live but the agent stays 'draft' and - // never appears in default (status='published') listings. - tx, err := db.Pool.Begin(ctx) - if err != nil { - recordErr(span, err) - return fmt.Errorf("begin tx: %w", err) - } - defer tx.Rollback(ctx) //nolint:errcheck // rollback is a no-op after commit - - now := time.Now().UTC() - tag, err := tx.Exec(ctx, ` - UPDATE agent_versions - SET published_at = $1 - WHERE agent_id = $2 AND version = $3 AND published_at IS NULL`, - now, agentID, version) - if err != nil { - recordErr(span, err) - return fmt.Errorf("publishing agent version: %w", err) - } - if tag.RowsAffected() == 0 { - var publishedAt *time.Time - err := tx.QueryRow(ctx, - `SELECT published_at FROM agent_versions WHERE agent_id=$1 AND version=$2`, - agentID, version, - ).Scan(&publishedAt) - if errors.Is(err, pgx.ErrNoRows) { - recordErr(span, ErrNotFound) - return ErrNotFound - } - recordErr(span, ErrImmutable) - return ErrImmutable - } - if _, err := tx.Exec(ctx, - `UPDATE agents SET status='published', updated_at=now() WHERE id=$1 AND status='draft'`, - agentID); err != nil { - recordErr(span, err) - return fmt.Errorf("promoting agent status: %w", err) - } - - if err := tx.Commit(ctx); err != nil { - recordErr(span, err) - return fmt.Errorf("commit tx: %w", err) - } - return nil -} - -// DeprecateAgent marks an agent as deprecated. -func (db *DB) DeprecateAgent(ctx context.Context, agentID string) error { - ctx, span := startSpan(ctx, "DeprecateAgent") - defer span.End() - - rows, err := applyAgentDeprecation(ctx, db.Pool, agentID) - if err != nil { - recordErr(span, err) - return fmt.Errorf("deprecating agent: %w", err) - } - if rows == 0 { - recordErr(span, ErrNotFound) - return ErrNotFound - } - return nil -} - -// UndeprecateAgent returns a deprecated agent to published. -func (db *DB) UndeprecateAgent(ctx context.Context, agentID string) error { - ctx, span := startSpan(ctx, "UndeprecateAgent") - defer span.End() - - rows, err := applyAgentUndeprecation(ctx, db.Pool, agentID) - if err != nil { - recordErr(span, err) - return fmt.Errorf("undeprecating agent: %w", err) - } - if rows == 0 { - recordErr(span, ErrNotFound) - return ErrNotFound - } - return nil -} - -// SetAgentVisibility sets the visibility of an agent. -func (db *DB) SetAgentVisibility(ctx context.Context, agentID string, vis domain.Visibility) error { - ctx, span := startSpan(ctx, "SetAgentVisibility") - defer span.End() - - rows, err := applyAgentVisibility(ctx, db.Pool, agentID, vis) - if err != nil { - recordErr(span, err) - return fmt.Errorf("setting agent visibility: %w", err) - } - if rows == 0 { - recordErr(span, ErrNotFound) - return ErrNotFound - } - return nil -} - -// SetAgentVersionStatus updates the lifecycle status of a specific agent version. -// statusMessage is optional and should be empty when status is "active". -func (db *DB) SetAgentVersionStatus(ctx context.Context, agentID, version string, status domain.VersionStatus, statusMessage string) error { - ctx, span := startSpan(ctx, "SetAgentVersionStatus") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agent_versions - SET status=$1, status_message=$2, status_changed_at=now() - WHERE agent_id=$3 AND version=$4`, - status, statusMessage, agentID, version) - if err != nil { - recordErr(span, err) - return fmt.Errorf("setting agent version status: %w", err) - } - if tag.RowsAffected() == 0 { - recordErr(span, ErrNotFound) - return ErrNotFound - } - return nil -} - -// SetAllAgentVersionsStatus updates the lifecycle status on all published versions of -// an agent atomically. Returns the updated versions. -func (db *DB) SetAllAgentVersionsStatus(ctx context.Context, agentID string, status domain.VersionStatus, statusMessage string) ([]domain.AgentVersion, error) { - ctx, span := startSpan(ctx, "SetAllAgentVersionsStatus") - defer span.End() - - rows, err := db.Pool.Query(ctx, ` - UPDATE agent_versions - SET status=$1, status_message=$2, status_changed_at=now() - WHERE agent_id=$3 AND published_at IS NOT NULL - RETURNING id, agent_id, version, endpoint_url, skills, capabilities, authentication, - default_input_modes, default_output_modes, provider, - coalesce(documentation_url,''), coalesce(icon_url,''), - protocol_version, status, coalesce(status_message,''), status_changed_at, - published_at, created_at, updated_at, - review_state, revision, submitted_at, coalesce(submitted_by,''), coalesce(submitted_by_email,''), - reviewed_at, coalesce(reviewed_by,''), coalesce(reviewed_by_email,''), - coalesce(review_decision,''), coalesce(rejection_reason,''), request_public`, - status, statusMessage, agentID) - if err != nil { - recordErr(span, err) - return nil, fmt.Errorf("setting all agent versions status: %w", err) - } - defer rows.Close() - - var result []domain.AgentVersion - for rows.Next() { - v, err := scanAgentVersion(rows) - if err != nil { - recordErr(span, err) - return nil, err - } - result = append(result, v) - } - if err := rows.Err(); err != nil { - recordErr(span, err) - return nil, err - } - return result, nil -} - -// UpdateAgentParams holds the mutable fields for a PATCH operation on an agent. -type UpdateAgentParams struct { - Name string `json:"name"` - Description string `json:"description"` -} - -// UpdateAgent updates the mutable metadata fields of an agent. -// Returns ErrNotFound if the agent does not exist. -func (db *DB) UpdateAgent(ctx context.Context, agentID string, p UpdateAgentParams) (*AgentRow, error) { - ctx, span := startSpan(ctx, "UpdateAgent") - defer span.End() - - rows, err := applyAgentMetadata(ctx, db.Pool, agentID, p) - if err != nil { - recordErr(span, err) - return nil, fmt.Errorf("updating agent: %w", err) - } - if rows == 0 { - recordErr(span, ErrNotFound) - return nil, ErrNotFound - } - return db.getAgentByID(ctx, agentID) -} - -// DeleteAgent soft-deletes an agent by setting status='deleted' (and -// deleted_at) on the agent and all its versions. Any review-queue residue — -// a pending deletion request, pending version submissions, a pending entry -// change — is resolved in the same transaction so the queue can never hold an -// item whose target no longer exists. Returns ErrNotFound if not found. -func (db *DB) DeleteAgent(ctx context.Context, agentID string) error { - ctx, span := startSpan(ctx, "DeleteAgent") - defer span.End() - - // Parent and child rows must flip together: a partial soft-delete leaves the - // agent in an inconsistent state, so wrap both UPDATEs in one transaction. - tx, err := db.Pool.Begin(ctx) - if err != nil { - recordErr(span, err) - return fmt.Errorf("begin tx: %w", err) - } - defer tx.Rollback(ctx) //nolint:errcheck // rollback is a no-op after commit - - // deleted_at drives the review-queue exclusion (the deletion-request branch - // keys off deletion_requested_at; the deletion_requested_* audit columns are - // retained, mirroring ApproveAgentDeletion). - tag, err := tx.Exec(ctx, - `UPDATE agents - SET status='deleted', deleted_at=COALESCE(deleted_at, now()), updated_at=now() - WHERE id=$1 AND status != 'deleted'`, - agentID) - if err != nil { - recordErr(span, err) - return fmt.Errorf("deleting agent: %w", err) - } - if tag.RowsAffected() == 0 { - recordErr(span, ErrNotFound) - return ErrNotFound - } - if _, err = tx.Exec(ctx, - `UPDATE agent_versions SET status='deleted', status_changed_at=now() WHERE agent_id=$1`, - agentID); err != nil { - recordErr(span, err) - return fmt.Errorf("deleting agent versions: %w", err) - } - // Cancel in-flight version submissions so the queue's version branch drops them. - if _, err = tx.Exec(ctx, - `UPDATE agent_versions - SET review_state='none', submitted_at=NULL, submitted_by=NULL, submitted_by_email=NULL - WHERE agent_id=$1 AND review_state='pending_review'`, - agentID); err != nil { - recordErr(span, err) - return fmt.Errorf("cancelling pending agent version reviews: %w", err) - } - // Drop a pending entry-change request, mirroring the editor's withdraw path. - if _, err = tx.Exec(ctx, - `DELETE FROM entry_change_requests - WHERE resource_type='agent' AND entry_id=$1 AND state='pending_review'`, - agentID); err != nil { - recordErr(span, err) - return fmt.Errorf("cancelling pending agent entry change: %w", err) - } - - if err := tx.Commit(ctx); err != nil { - recordErr(span, err) - return fmt.Errorf("commit tx: %w", err) - } - return nil -} - -// getAgentByID retrieves an agent by its ULID (internal helper for update returns). -func (db *DB) getAgentByID(ctx context.Context, id string) (*AgentRow, error) { - ctx, span := startSpan(ctx, "getAgentByID") - defer span.End() - - q := ` - SELECT a.id, pub.slug, a.publisher_id, a.slug, a.name, - coalesce(a.description,''), a.visibility, a.status, a.featured, a.verified, - coalesce(lav.tags, '{}'), - coalesce(a.readme,''), a.view_count, a.copy_count, a.created_at, a.updated_at, - lav.version, lav.endpoint_url, lav.skills, lav.default_input_modes, - lav.default_output_modes, lav.authentication, lav.protocol_version, lav.published_at - FROM agents a - JOIN publishers pub ON pub.id = a.publisher_id - LEFT JOIN LATERAL ( - SELECT av.version, av.endpoint_url, av.skills, av.default_input_modes, - av.default_output_modes, av.authentication, av.protocol_version, av.tags, av.published_at - FROM agent_versions av - WHERE av.agent_id = a.id AND av.published_at IS NOT NULL - ORDER BY av.published_at DESC - LIMIT 1 - ) lav ON true - WHERE a.id = $1` - - var r AgentRow - var ( - lavVersion *string - lavEndpoint *string - lavSkills []byte - lavInputModes []string - lavOutputModes []string - lavAuth []byte - lavProto *string - lavPublishedAt *time.Time - ) - err := db.Pool.QueryRow(ctx, q, id).Scan( - &r.ID, &r.Namespace, &r.PublisherID, &r.Slug, &r.Name, - &r.Description, &r.Visibility, &r.Status, &r.Featured, &r.Verified, &r.Tags, - &r.Readme, &r.ViewCount, &r.CopyCount, &r.CreatedAt, &r.UpdatedAt, - &lavVersion, &lavEndpoint, &lavSkills, &lavInputModes, - &lavOutputModes, &lavAuth, &lavProto, &lavPublishedAt, - ) - if errors.Is(err, pgx.ErrNoRows) { - recordErr(span, ErrNotFound) - return nil, ErrNotFound - } - if err != nil { - recordErr(span, err) - return nil, fmt.Errorf("getting agent by id: %w", err) - } - if lavVersion != nil { - r.LatestVersion = &LatestAgentVersion{ - Version: *lavVersion, - EndpointURL: *lavEndpoint, - Skills: json.RawMessage(lavSkills), - DefaultInputModes: lavInputModes, - DefaultOutputModes: lavOutputModes, - Authentication: json.RawMessage(lavAuth), - ProtocolVersion: *lavProto, - Tags: r.Tags, // entry tags ARE the latest version's tags - PublishedAt: lavPublishedAt, - } - } - return &r, nil -} - -func scanAgentVersion(s interface{ Scan(...any) error }) (domain.AgentVersion, error) { - var v domain.AgentVersion - err := s.Scan( - &v.ID, &v.AgentID, &v.Version, &v.EndpointURL, - &v.Skills, &v.Capabilities, &v.Authentication, - &v.DefaultInputModes, &v.DefaultOutputModes, &v.Provider, - &v.DocumentationURL, &v.IconURL, &v.Tags, - &v.ProtocolVersion, &v.Status, &v.StatusMessage, &v.StatusChangedAt, - &v.PublishedAt, &v.CreatedAt, &v.UpdatedAt, - &v.ReviewState, &v.Revision, &v.SubmittedAt, &v.SubmittedBy, &v.SubmittedByEmail, - &v.ReviewedAt, &v.ReviewedBy, &v.ReviewedByEmail, - &v.ReviewDecision, &v.RejectionReason, &v.RequestPublic, - ) - return v, err -} - -// IncrementAgentViewCount atomically increments the view_count for the -// given agent identified by namespace and slug. -func (db *DB) IncrementAgentViewCount(ctx context.Context, namespace, slug string) error { - ctx, span := startSpan(ctx, "IncrementAgentViewCount") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agents a - SET view_count = view_count + 1 - FROM publishers pub - WHERE pub.id = a.publisher_id - AND pub.slug = $1 AND a.slug = $2 AND a.status != 'deleted'`, - namespace, slug, - ) - if err != nil { - recordErr(span, err) - return fmt.Errorf("incrementing agent view count: %w", err) - } - if tag.RowsAffected() == 0 { - return ErrNotFound - } - return nil -} - -// IncrementAgentCopyCount atomically increments the copy_count for the -// given agent identified by namespace and slug. -func (db *DB) IncrementAgentCopyCount(ctx context.Context, namespace, slug string) error { - ctx, span := startSpan(ctx, "IncrementAgentCopyCount") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agents a - SET copy_count = copy_count + 1 - FROM publishers pub - WHERE pub.id = a.publisher_id - AND pub.slug = $1 AND a.slug = $2 AND a.status != 'deleted'`, - namespace, slug, - ) - if err != nil { - recordErr(span, err) - return fmt.Errorf("incrementing agent copy count: %w", err) - } - if tag.RowsAffected() == 0 { - return ErrNotFound - } - return nil -} diff --git a/server/internal/store/agent_test.go b/server/internal/store/agent_test.go deleted file mode 100644 index b7dff085..00000000 --- a/server/internal/store/agent_test.go +++ /dev/null @@ -1,841 +0,0 @@ -package store_test - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "testing" - - "github.com/haibread/ai-registry/internal/domain" - "github.com/haibread/ai-registry/internal/store" -) - -var validSkills = json.RawMessage( - `[{"id":"search","name":"Search","description":"Searches the web","tags":["search"]}]`) - -var validAuthentication = json.RawMessage(`[{"scheme":"Bearer"}]`) - -func TestCreateAndGetAgent(t *testing.T) { - resetDB(t) - ctx := context.Background() - - pubID := insertPublisher(t, "agent-ns", "Agent Corp") - - agent, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, - Slug: "my-agent", - Name: "My Agent", - Description: "A test agent", - }) - if err != nil { - t.Fatalf("CreateAgent() error = %v", err) - } - if agent.ID == "" { - t.Error("expected non-empty ID") - } - if agent.Status != domain.StatusDraft { - t.Errorf("status = %v, want draft", agent.Status) - } - if agent.Visibility != domain.VisibilityPrivate { - t.Errorf("visibility = %v, want private", agent.Visibility) - } - - got, err := sharedDB.GetAgent(ctx, "agent-ns", "my-agent", false) - if err != nil { - t.Fatalf("GetAgent() error = %v", err) - } - if got.ID != agent.ID { - t.Errorf("id = %v, want %v", got.ID, agent.ID) - } - if got.Namespace != "agent-ns" { - t.Errorf("namespace = %v, want agent-ns", got.Namespace) - } - if got.Description != "A test agent" { - t.Errorf("description = %q, want %q", got.Description, "A test agent") - } -} - -func TestCreateAgent_ConflictOnDuplicateSlug(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "agent-ns2", "Agent Corp 2") - - params := store.CreateAgentParams{PublisherID: pubID, Slug: "dup-agent", Name: "Dup"} - if _, err := sharedDB.CreateAgent(ctx, params); err != nil { - t.Fatalf("first create: %v", err) - } - _, err := sharedDB.CreateAgent(ctx, params) - if err != store.ErrConflict { - t.Errorf("expected ErrConflict, got %v", err) - } -} - -// TestCreateAgent_SlugUniquenessIsPerPublisher verifies that the unique key -// is (publisher_id, slug): two -// different publishers may each expose an agent with the same slug, but a -// duplicate within one publisher conflicts. -func TestCreateAgent_SlugUniquenessIsPerPublisher(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubA := insertPublisher(t, "agent-pub-a", "Agent Pub A") - pubB := insertPublisher(t, "agent-pub-b", "Agent Pub B") - - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubA, Slug: "planner", Name: "Planner A", - }); err != nil { - t.Fatalf("create planner in pub-a: %v", err) - } - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubB, Slug: "planner", Name: "Planner B", - }); err != nil { - t.Errorf("create planner in pub-b should succeed (per-publisher slug), got %v", err) - } - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubA, Slug: "planner", Name: "Planner A dup", - }); err != store.ErrConflict { - t.Errorf("duplicate planner in pub-a: expected ErrConflict, got %v", err) - } -} - -func TestGetAgent_NotFoundWhenPrivateAndPublicOnly(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "agent-ns3", "Agent Corp 3") - - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "priv-agent", Name: "Private", - }); err != nil { - t.Fatalf("create: %v", err) - } - - _, err := sharedDB.GetAgent(ctx, "agent-ns3", "priv-agent", true) - if err != store.ErrNotFound { - t.Errorf("expected ErrNotFound for private agent with publicOnly=true, got %v", err) - } -} - -func TestAgentVersionLifecycle(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "lifecycle-agent-ns", "Lifecycle Agent Corp") - - agent, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "lifecycle-agent", Name: "Lifecycle Agent", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - - // Create a draft version. - ver, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, - Version: "1.0.0", - EndpointURL: "https://agent.example.com/api", - Skills: validSkills, - Authentication: validAuthentication, - ProtocolVersion: domain.A2AProtocolVersion, - }) - if err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } - if ver.IsPublished() { - t.Error("newly created version should not be published") - } - if ver.Version != "1.0.0" { - t.Errorf("version = %q, want %q", ver.Version, "1.0.0") - } - - // Publish it. - if err := sharedDB.PublishAgentVersion(ctx, agent.ID, "1.0.0"); err != nil { - t.Fatalf("PublishAgentVersion: %v", err) - } - - // Fetch and verify published. - got, err := sharedDB.GetAgentVersion(ctx, agent.ID, "1.0.0", false) - if err != nil { - t.Fatalf("GetAgentVersion: %v", err) - } - if !got.IsPublished() { - t.Error("version should be published after publish call") - } - - // Publishing again should return ErrImmutable. - if err := sharedDB.PublishAgentVersion(ctx, agent.ID, "1.0.0"); err != store.ErrImmutable { - t.Errorf("expected ErrImmutable on re-publish, got %v", err) - } - - // Duplicate version should return ErrConflict. - _, err = sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, - Version: "1.0.0", - EndpointURL: "https://agent.example.com/api", - Skills: validSkills, - ProtocolVersion: domain.A2AProtocolVersion, - }) - if err != store.ErrConflict { - t.Errorf("expected ErrConflict on duplicate version, got %v", err) - } -} - -func TestGetLatestPublishedAgentVersion(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "latest-agent-ns", "Latest Agent Corp") - - agent, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "latest-agent", Name: "Latest Agent", - }) - - // No published version yet. - _, err := sharedDB.GetLatestPublishedAgentVersion(ctx, agent.ID) - if err != store.ErrNotFound { - t.Errorf("expected ErrNotFound with no published versions, got %v", err) - } - - // Create and publish 1.0.0. - sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, Version: "1.0.0", EndpointURL: "https://agent.example.com/api", - Skills: validSkills, ProtocolVersion: domain.A2AProtocolVersion, - }) - sharedDB.PublishAgentVersion(ctx, agent.ID, "1.0.0") - - // Create and publish 2.0.0. - sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, Version: "2.0.0", EndpointURL: "https://agent.example.com/api", - Skills: validSkills, ProtocolVersion: domain.A2AProtocolVersion, - }) - sharedDB.PublishAgentVersion(ctx, agent.ID, "2.0.0") - - latest, err := sharedDB.GetLatestPublishedAgentVersion(ctx, agent.ID) - if err != nil { - t.Fatalf("GetLatestPublishedAgentVersion: %v", err) - } - if latest.Version != "2.0.0" { - t.Errorf("latest version = %q, want %q", latest.Version, "2.0.0") - } -} - -func TestListAgents_Filtering(t *testing.T) { - resetDB(t) - ctx := context.Background() - - pub1 := insertPublisher(t, "agent-filter-ns1", "Filter NS 1") - pub2 := insertPublisher(t, "agent-filter-ns2", "Filter NS 2") - - // Create a public agent under pub1. - ag1, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub1, Slug: "public-agent", Name: "Public Agent", - }) - sharedDB.SetAgentVisibility(ctx, ag1.ID, domain.VisibilityPublic) - - // Create a private agent under pub2. - sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub2, Slug: "private-agent", Name: "Private Agent", - }) - - // PublicOnly=true should return only public entries. - rows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{PublicOnly: true, Limit: 20}) - if err != nil { - t.Fatalf("ListAgents: %v", err) - } - for _, r := range rows { - if r.Visibility != domain.VisibilityPublic { - t.Errorf("expected public visibility, got %v for agent %v", r.Visibility, r.Slug) - } - } - - // Namespace filter. - rows2, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Namespace: "agent-filter-ns1", Limit: 20}) - if err != nil { - t.Fatalf("ListAgents with namespace: %v", err) - } - for _, r := range rows2 { - if r.Namespace != "agent-filter-ns1" { - t.Errorf("expected namespace agent-filter-ns1, got %v", r.Namespace) - } - } -} - -func TestDeprecateAgent(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "dep-agent-ns", "Deprecate Agent NS") - - agent, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "dep-agent", Name: "Dep Agent", - }) - - // Can't deprecate a draft agent. - if err := sharedDB.DeprecateAgent(ctx, agent.ID); err != store.ErrNotFound { - t.Errorf("expected ErrNotFound when deprecating draft, got %v", err) - } - - // Publish a version first, which promotes agent to published. - sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, Version: "1.0.0", EndpointURL: "https://agent.example.com/api", - Skills: validSkills, ProtocolVersion: domain.A2AProtocolVersion, - }) - sharedDB.PublishAgentVersion(ctx, agent.ID, "1.0.0") - - if err := sharedDB.DeprecateAgent(ctx, agent.ID); err != nil { - t.Fatalf("DeprecateAgent: %v", err) - } - - // Check status is deprecated. - got, _ := sharedDB.GetAgent(ctx, "dep-agent-ns", "dep-agent", false) - if got.Status != domain.StatusDeprecated { - t.Errorf("status = %v, want deprecated", got.Status) - } -} - -func TestListAgentVersions(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "listver-agent-ns", "ListVer Agent NS") - - agent, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "listver-agent", Name: "ListVer Agent", - }) - - for _, v := range []string{"1.0.0", "1.1.0", "2.0.0"} { - sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, Version: v, EndpointURL: "https://agent.example.com/api", - Skills: validSkills, ProtocolVersion: domain.A2AProtocolVersion, - }) - } - - versions, err := sharedDB.ListAgentVersions(ctx, agent.ID, false) - if err != nil { - t.Fatalf("ListAgentVersions: %v", err) - } - if len(versions) != 3 { - t.Errorf("versions count = %d, want 3", len(versions)) - } -} - -func TestGetAgentVersion_NotFound(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "getaver-ns", "GetAgentVer NS") - - agent, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "getaver-agent", Name: "GetAgentVer Agent", - }) - - _, err := sharedDB.GetAgentVersion(ctx, agent.ID, "9.9.9", false) - if err != store.ErrNotFound { - t.Errorf("expected ErrNotFound for missing version, got %v", err) - } -} - -func TestSetAgentVisibility(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "avis-ns", "AgentVis NS") - - agent, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "avis-agent", Name: "AgentVis Agent", - }) - - // Set to public. - if err := sharedDB.SetAgentVisibility(ctx, agent.ID, domain.VisibilityPublic); err != nil { - t.Fatalf("SetAgentVisibility(public): %v", err) - } - got, err := sharedDB.GetAgent(ctx, "avis-ns", "avis-agent", false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if got.Visibility != domain.VisibilityPublic { - t.Errorf("visibility = %v, want public", got.Visibility) - } - - // Set back to private. - if err := sharedDB.SetAgentVisibility(ctx, agent.ID, domain.VisibilityPrivate); err != nil { - t.Fatalf("SetAgentVisibility(private): %v", err) - } - got2, _ := sharedDB.GetAgent(ctx, "avis-ns", "avis-agent", false) - if got2.Visibility != domain.VisibilityPrivate { - t.Errorf("visibility = %v, want private", got2.Visibility) - } - - // Non-existent ID must return ErrNotFound. - if err := sharedDB.SetAgentVisibility(ctx, "nonexistent-id", domain.VisibilityPublic); err != store.ErrNotFound { - t.Errorf("expected ErrNotFound for bad ID, got %v", err) - } -} - -func TestListAgents_SearchQuery(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "asearch-ns", "AgentSearch NS") - - sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "alpha-agent", Name: "AlphaSearch Agent", - Description: "Unique alpha description for agent search test", - }) - sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "beta-agent", Name: "BetaOther Agent", - Description: "Completely different beta description", - }) - - rows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{ - Query: "alpha", Limit: 20, - }) - if err != nil { - t.Fatalf("ListAgents(query=alpha): %v", err) - } - if len(rows) != 1 { - t.Errorf("expected 1 result for query 'alpha', got %d", len(rows)) - } - if len(rows) > 0 && rows[0].Slug != "alpha-agent" { - t.Errorf("expected slug alpha-agent, got %s", rows[0].Slug) - } -} - -func TestListAgents_NamespaceFilter(t *testing.T) { - resetDB(t) - ctx := context.Background() - pub1 := insertPublisher(t, "ansfilt-ns1", "AgentNS Filter 1") - pub2 := insertPublisher(t, "ansfilt-ns2", "AgentNS Filter 2") - - sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub1, Slug: "agent-in-ns1", Name: "Agent In NS1", - }) - sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub2, Slug: "agent-in-ns2", Name: "Agent In NS2", - }) - - rows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{ - Namespace: "ansfilt-ns1", Limit: 20, - }) - if err != nil { - t.Fatalf("ListAgents(namespace=ansfilt-ns1): %v", err) - } - if len(rows) != 1 { - t.Errorf("expected 1 result for namespace ansfilt-ns1, got %d", len(rows)) - } - for _, r := range rows { - if r.Namespace != "ansfilt-ns1" { - t.Errorf("expected namespace ansfilt-ns1, got %s", r.Namespace) - } - } -} - -func TestDeprecateAgent_BadID(t *testing.T) { - resetDB(t) - ctx := context.Background() - - // A completely non-existent ID must also return ErrNotFound. - if err := sharedDB.DeprecateAgent(ctx, "nonexistent-id"); err != store.ErrNotFound { - t.Errorf("expected ErrNotFound for bad ID, got %v", err) - } -} - -func TestListAgents_FilterByStatus(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "ag-status-ns", "Agent Status NS") - - ag1, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pubID, Slug: "ag-status-draft", Name: "Draft Agent"}) - ag2, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pubID, Slug: "ag-status-published", Name: "Published Agent"}) - ag3, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pubID, Slug: "ag-status-deprecated", Name: "Deprecated Agent"}) - - if _, err := sharedDB.Pool.Exec(ctx, "UPDATE agents SET status=$1 WHERE id=$2", "published", ag2.ID); err != nil { - t.Fatalf("setting published status: %v", err) - } - if _, err := sharedDB.Pool.Exec(ctx, "UPDATE agents SET status=$1 WHERE id=$2", "deprecated", ag3.ID); err != nil { - t.Fatalf("setting deprecated status: %v", err) - } - _ = ag1 // stays draft - - for _, tc := range []struct { - status string - want int - slug string - }{ - {"draft", 1, "ag-status-draft"}, - {"published", 1, "ag-status-published"}, - {"deprecated", 1, "ag-status-deprecated"}, - } { - t.Run(tc.status, func(t *testing.T) { - rows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Status: tc.status, Limit: 20}) - if err != nil { - t.Fatalf("ListAgents(status=%s): %v", tc.status, err) - } - if len(rows) != tc.want { - t.Errorf("status=%s: got %d rows, want %d", tc.status, len(rows), tc.want) - } - if len(rows) > 0 && rows[0].Slug != tc.slug { - t.Errorf("status=%s: slug=%q, want %q", tc.status, rows[0].Slug, tc.slug) - } - }) - } -} - -func TestListAgents_FilterByVisibility(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "ag-vis-filter-ns", "Agent Vis Filter NS") - - ag1, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pubID, Slug: "ag-vf-public-1", Name: "Public Agent 1"}) - ag2, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pubID, Slug: "ag-vf-public-2", Name: "Public Agent 2"}) - _, _ = sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pubID, Slug: "ag-vf-private", Name: "Private Agent"}) - - for _, id := range []string{ag1.ID, ag2.ID} { - if _, err := sharedDB.Pool.Exec(ctx, "UPDATE agents SET visibility=$1 WHERE id=$2", "public", id); err != nil { - t.Fatalf("setting visibility: %v", err) - } - } - - pubRows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Visibility: "public", Limit: 20}) - if err != nil { - t.Fatalf("ListAgents(visibility=public): %v", err) - } - if len(pubRows) != 2 { - t.Errorf("visibility=public: got %d rows, want 2", len(pubRows)) - } - for _, r := range pubRows { - if r.Visibility != "public" { - t.Errorf("expected public visibility, got %q for slug %q", r.Visibility, r.Slug) - } - } - - privRows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Visibility: "private", Limit: 20}) - if err != nil { - t.Fatalf("ListAgents(visibility=private): %v", err) - } - if len(privRows) != 1 { - t.Errorf("visibility=private: got %d rows, want 1", len(privRows)) - } - if len(privRows) > 0 && privRows[0].Slug != "ag-vf-private" { - t.Errorf("visibility=private: slug=%q, want ag-vf-private", privRows[0].Slug) - } -} - -func TestListAgents_FilterCombined(t *testing.T) { - resetDB(t) - ctx := context.Background() - pub1 := insertPublisher(t, "ag-comb-ns1", "Agent Combined NS1") - pub2 := insertPublisher(t, "ag-comb-ns2", "Agent Combined NS2") - - // ns1: one public+published, one public+draft, one private+published - agA, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pub1, Slug: "ag-comb-a", Name: "Comb A"}) - agB, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pub1, Slug: "ag-comb-b", Name: "Comb B"}) - agC, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pub1, Slug: "ag-comb-c", Name: "Comb C"}) - // ns2: one public+published - agD, _ := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pub2, Slug: "ag-comb-d", Name: "Comb D"}) - - type update struct{ id, col, val string } - for _, u := range []update{ - {agA.ID, "visibility", "public"}, - {agA.ID, "status", "published"}, - {agB.ID, "visibility", "public"}, - // agB stays draft - {agC.ID, "status", "published"}, - // agC stays private - {agD.ID, "visibility", "public"}, - {agD.ID, "status", "published"}, - } { - if _, err := sharedDB.Pool.Exec(ctx, "UPDATE agents SET "+u.col+"=$1 WHERE id=$2", u.val, u.id); err != nil { - t.Fatalf("update %s=%s on %s: %v", u.col, u.val, u.id, err) - } - } - - // namespace=ag-comb-ns1 + status=published + visibility=public => only agA - rows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{ - Namespace: "ag-comb-ns1", - Status: "published", - Visibility: "public", - Limit: 20, - }) - if err != nil { - t.Fatalf("ListAgents(combined): %v", err) - } - if len(rows) != 1 { - t.Errorf("combined filter: got %d rows, want 1", len(rows)) - } - if len(rows) > 0 && rows[0].Slug != "ag-comb-a" { - t.Errorf("combined filter: slug=%q, want ag-comb-a", rows[0].Slug) - } -} - -func TestListAgents_TotalCount(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "atc-ns", "AgentTotalCount NS") - - // Create 3 agents. - for i := range 3 { - sharedDB.CreateAgent(ctx, store.CreateAgentParams{ //nolint:errcheck - PublisherID: pubID, - Slug: fmt.Sprintf("atc-ag-%d", i), - Name: fmt.Sprintf("AgentTotalCount %d", i), - }) - } - - // Request page of 2 — should return 2 rows but total_count = 3. - rows, total, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Limit: 2}) - if err != nil { - t.Fatalf("ListAgents: %v", err) - } - if len(rows) != 2 { - t.Errorf("page size: got %d rows, want 2", len(rows)) - } - if total != 3 { - t.Errorf("total_count: got %d, want 3", total) - } - - // Second page — total_count must still reflect the full set. - cursor := store.EncodeCursor(rows[len(rows)-1].CreatedAt, rows[len(rows)-1].ID) - _, total2, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Limit: 2, Cursor: cursor}) - if err != nil { - t.Fatalf("ListAgents page 2: %v", err) - } - if total2 != 3 { - t.Errorf("total_count page 2: got %d, want 3", total2) - } -} - -func TestUpdateAgent(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "ag-update-pub", "Update Pub") - - ag, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, - Slug: "update-agent", - Name: "Original Agent", - Description: "Original description", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - - updated, err := sharedDB.UpdateAgent(ctx, ag.ID, store.UpdateAgentParams{ - Name: "Updated Agent", - Description: "Updated description", - }) - if err != nil { - t.Fatalf("UpdateAgent: %v", err) - } - if updated.Name != "Updated Agent" { - t.Errorf("name = %q, want %q", updated.Name, "Updated Agent") - } - if updated.Description != "Updated description" { - t.Errorf("description = %q, want %q", updated.Description, "Updated description") - } -} - -func TestUpdateAgent_NotFound(t *testing.T) { - resetDB(t) - ctx := context.Background() - _, err := sharedDB.UpdateAgent(ctx, store.NewULID(), store.UpdateAgentParams{Name: "X"}) - if !errors.Is(err, store.ErrNotFound) { - t.Errorf("expected ErrNotFound, got %v", err) - } -} - -func TestDeleteAgent(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "ag-del-pub", "Delete Pub") - - ag, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, - Slug: "del-agent", - Name: "Delete Me", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - - if err := sharedDB.DeleteAgent(ctx, ag.ID); err != nil { - t.Fatalf("DeleteAgent: %v", err) - } - - // Should not appear in public listing. - rows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{PublicOnly: true}) - if err != nil { - t.Fatalf("ListAgents: %v", err) - } - for _, r := range rows { - if r.ID == ag.ID { - t.Error("deleted agent still appears in public listing") - } - } - - // Should not appear in admin listing either (default excludes deleted). - adminRows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{}) - if err != nil { - t.Fatalf("ListAgents admin: %v", err) - } - for _, r := range adminRows { - if r.ID == ag.ID { - t.Error("deleted agent still appears in admin listing") - } - } - - // Opting in with IncludeDeleted should surface the row. - includedRows, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{IncludeDeleted: true}) - if err != nil { - t.Fatalf("ListAgents IncludeDeleted: %v", err) - } - found := false - for _, r := range includedRows { - if r.ID == ag.ID { - found = true - break - } - } - if !found { - t.Error("deleted agent missing from listing even with IncludeDeleted=true") - } - - // Double-delete should return ErrNotFound. - if err := sharedDB.DeleteAgent(ctx, ag.ID); !errors.Is(err, store.ErrNotFound) { - t.Errorf("second delete: expected ErrNotFound, got %v", err) - } -} - -// TestCreateAgent_SlugReuseAfterDelete verifies that once an agent is -// soft-deleted its slug is freed: re-creating the same (publisher, slug) -// succeeds with a fresh row, and the getter resolves to the live row. -func TestCreateAgent_SlugReuseAfterDelete(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "ag-reuse-pub", "Reuse Pub") - - first, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "reuse-agent", Name: "First", - }) - if err != nil { - t.Fatalf("first CreateAgent: %v", err) - } - if err := sharedDB.DeleteAgent(ctx, first.ID); err != nil { - t.Fatalf("DeleteAgent: %v", err) - } - - if _, err := sharedDB.GetAgent(ctx, "ag-reuse-pub", "reuse-agent", false); !errors.Is(err, store.ErrNotFound) { - t.Errorf("GetAgent after delete: expected ErrNotFound, got %v", err) - } - - second, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "reuse-agent", Name: "Second", - }) - if err != nil { - t.Fatalf("re-create after delete: %v", err) - } - if second.ID == first.ID { - t.Error("re-created agent reused the deleted row's ID") - } - - got, err := sharedDB.GetAgent(ctx, "ag-reuse-pub", "reuse-agent", false) - if err != nil { - t.Fatalf("GetAgent after re-create: %v", err) - } - if got.ID != second.ID { - t.Errorf("getter resolved to %q, want live row %q", got.ID, second.ID) - } -} - -func TestDeleteAgent_NotFound(t *testing.T) { - resetDB(t) - ctx := context.Background() - if err := sharedDB.DeleteAgent(ctx, store.NewULID()); !errors.Is(err, store.ErrNotFound) { - t.Errorf("expected ErrNotFound, got %v", err) - } -} - -func TestIncrementAgentViewCount(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "view-ns", "View Corp") - - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "view-agent", Name: "View Agent", - }); err != nil { - t.Fatalf("CreateAgent: %v", err) - } - - // Baseline. - got, err := sharedDB.GetAgent(ctx, "view-ns", "view-agent", false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if got.ViewCount != 0 { - t.Errorf("initial view_count = %d, want 0", got.ViewCount) - } - - // Three successive increments should be monotonic. - for i := 1; i <= 3; i++ { - if err := sharedDB.IncrementAgentViewCount(ctx, "view-ns", "view-agent"); err != nil { - t.Fatalf("IncrementAgentViewCount #%d: %v", i, err) - } - got, err = sharedDB.GetAgent(ctx, "view-ns", "view-agent", false) - if err != nil { - t.Fatalf("GetAgent after increment #%d: %v", i, err) - } - if got.ViewCount != i { - t.Errorf("after increment #%d view_count = %d, want %d", i, got.ViewCount, i) - } - } - - // Copy count should not be affected. - if got.CopyCount != 0 { - t.Errorf("copy_count = %d, want 0 (view increments must not touch copy)", got.CopyCount) - } -} - -func TestIncrementAgentViewCount_NotFound(t *testing.T) { - resetDB(t) - ctx := context.Background() - - // No publisher, no agent. - if err := sharedDB.IncrementAgentViewCount(ctx, "missing-ns", "missing-slug"); !errors.Is(err, store.ErrNotFound) { - t.Errorf("expected ErrNotFound for unknown agent, got %v", err) - } - - // Publisher exists but agent does not. - insertPublisher(t, "exists-ns", "Exists") - if err := sharedDB.IncrementAgentViewCount(ctx, "exists-ns", "missing-slug"); !errors.Is(err, store.ErrNotFound) { - t.Errorf("expected ErrNotFound for unknown slug under known namespace, got %v", err) - } -} - -func TestIncrementAgentCopyCount(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "copy-ns", "Copy Corp") - - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "copy-agent", Name: "Copy Agent", - }); err != nil { - t.Fatalf("CreateAgent: %v", err) - } - - for i := 1; i <= 2; i++ { - if err := sharedDB.IncrementAgentCopyCount(ctx, "copy-ns", "copy-agent"); err != nil { - t.Fatalf("IncrementAgentCopyCount #%d: %v", i, err) - } - } - - got, err := sharedDB.GetAgent(ctx, "copy-ns", "copy-agent", false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if got.CopyCount != 2 { - t.Errorf("copy_count = %d, want 2", got.CopyCount) - } - if got.ViewCount != 0 { - t.Errorf("view_count = %d, want 0 (copy increments must not touch view)", got.ViewCount) - } -} - -func TestIncrementAgentCopyCount_NotFound(t *testing.T) { - resetDB(t) - ctx := context.Background() - if err := sharedDB.IncrementAgentCopyCount(ctx, "nope", "nope"); !errors.Is(err, store.ErrNotFound) { - t.Errorf("expected ErrNotFound, got %v", err) - } -} diff --git a/server/internal/store/changelog.go b/server/internal/store/changelog.go index cf8d1736..3e91e510 100644 --- a/server/internal/store/changelog.go +++ b/server/internal/store/changelog.go @@ -6,10 +6,10 @@ import ( "time" ) -// ChangelogEntry represents one recently-published version (from either the -// MCP or agent registry) in the aggregated public changelog feed. +// ChangelogEntry represents one recently-published MCP server version in the +// public changelog feed. type ChangelogEntry struct { - ResourceType string // "mcp_server" | "agent" + ResourceType string // "mcp_server" Namespace string // publisher slug Slug string // resource slug Name string // human-readable resource name @@ -17,9 +17,8 @@ type ChangelogEntry struct { PublishedAt time.Time // when the version transitioned to published } -// ListChangelog returns the most recently published versions across both -// registries, merged and sorted by published_at descending. Only public, -// non-deprecated resources are included. +// ListChangelog returns the most recently published versions, sorted by +// published_at descending. Only public, non-deleted resources are included. // // limit is clamped to [1, 200]; 50 is the default when limit <= 0. func (db *DB) ListChangelog(ctx context.Context, limit int) ([]ChangelogEntry, error) { @@ -33,36 +32,19 @@ func (db *DB) ListChangelog(ctx context.Context, limit int) ([]ChangelogEntry, e } rows, err := db.Pool.Query(ctx, ` - ( - SELECT 'mcp_server' AS resource_type, - pub.slug AS namespace, - s.slug AS slug, - s.name AS name, - v.version AS version, - v.published_at - FROM mcp_server_versions v - JOIN mcp_servers s ON s.id = v.server_id - JOIN publishers pub ON pub.id = s.publisher_id - WHERE v.published_at IS NOT NULL - AND s.visibility = 'public' - AND s.status <> 'deleted' - ) - UNION ALL - ( - SELECT 'agent' AS resource_type, - pub.slug AS namespace, - a.slug AS slug, - a.name AS name, - v.version AS version, - v.published_at - FROM agent_versions v - JOIN agents a ON a.id = v.agent_id - JOIN publishers pub ON pub.id = a.publisher_id - WHERE v.published_at IS NOT NULL - AND a.visibility = 'public' - AND a.status <> 'deleted' - ) - ORDER BY published_at DESC + SELECT 'mcp_server' AS resource_type, + pub.slug AS namespace, + s.slug AS slug, + s.name AS name, + v.version AS version, + v.published_at + FROM mcp_server_versions v + JOIN mcp_servers s ON s.id = v.server_id + JOIN publishers pub ON pub.id = s.publisher_id + WHERE v.published_at IS NOT NULL + AND s.visibility = 'public' + AND s.status <> 'deleted' + ORDER BY v.published_at DESC LIMIT $1 `, limit) if err != nil { diff --git a/server/internal/store/entrychange.go b/server/internal/store/entrychange.go index bf5d2520..61d85314 100644 --- a/server/internal/store/entrychange.go +++ b/server/internal/store/entrychange.go @@ -64,36 +64,6 @@ func applyMCPMetadata(ctx context.Context, q querier, serverID string, p UpdateM return tag.RowsAffected(), err } -func applyAgentVisibility(ctx context.Context, q querier, agentID string, vis domain.Visibility) (int64, error) { - tag, err := q.Exec(ctx, - `UPDATE agents SET visibility=$1, updated_at=now() WHERE id=$2`, - vis, agentID) - return tag.RowsAffected(), err -} - -func applyAgentDeprecation(ctx context.Context, q querier, agentID string) (int64, error) { - tag, err := q.Exec(ctx, - `UPDATE agents SET status='deprecated', updated_at=now() WHERE id=$1 AND status='published'`, - agentID) - return tag.RowsAffected(), err -} - -func applyAgentUndeprecation(ctx context.Context, q querier, agentID string) (int64, error) { - tag, err := q.Exec(ctx, - `UPDATE agents SET status='published', updated_at=now() WHERE id=$1 AND status='deprecated'`, - agentID) - return tag.RowsAffected(), err -} - -func applyAgentMetadata(ctx context.Context, q querier, agentID string, p UpdateAgentParams) (int64, error) { - tag, err := q.Exec(ctx, ` - UPDATE agents - SET name=$1, description=$2, updated_at=now() - WHERE id=$3 AND status != 'deleted'`, - p.Name, p.Description, agentID) - return tag.RowsAffected(), err -} - // ── Change-request CRUD ────────────────────────────────────────────────────── // entryChangeSelectCols is the column list shared by the single-row reads. @@ -302,31 +272,6 @@ func applyEntryChange(ctx context.Context, tx querier, cr domain.EntryChangeRequ rows, err := applyMCPMetadata(ctx, tx, cr.EntryID, p) return applyResult(rows, err) } - case domain.EntryResourceAgent: - switch cr.Action { - case domain.EntryChangeVisibility: - var p struct { - Visibility string `json:"visibility"` - } - if err := json.Unmarshal(cr.Payload, &p); err != nil { - return fmt.Errorf("decoding visibility payload: %w", err) - } - rows, err := applyAgentVisibility(ctx, tx, cr.EntryID, domain.Visibility(p.Visibility)) - return applyResult(rows, err) - case domain.EntryChangeDeprecation: - rows, err := applyAgentDeprecation(ctx, tx, cr.EntryID) - return applyResult(rows, err) - case domain.EntryChangeUndeprecation: - rows, err := applyAgentUndeprecation(ctx, tx, cr.EntryID) - return applyResult(rows, err) - case domain.EntryChangeMetadataEdit: - var p UpdateAgentParams - if err := json.Unmarshal(cr.Payload, &p); err != nil { - return fmt.Errorf("decoding metadata payload: %w", err) - } - rows, err := applyAgentMetadata(ctx, tx, cr.EntryID, p) - return applyResult(rows, err) - } } return fmt.Errorf("unknown change (%s, %s)", cr.ResourceType, cr.Action) } diff --git a/server/internal/store/entrychange_test.go b/server/internal/store/entrychange_test.go index 8b659ea1..b00af394 100644 --- a/server/internal/store/entrychange_test.go +++ b/server/internal/store/entrychange_test.go @@ -247,35 +247,3 @@ func TestEntryChange_QueueListsPendingChange(t *testing.T) { t.Error("payload is empty") } } - -func TestEntryChange_AgentVisibilityApplies(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "acme", "acme") - ag, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "router", Name: "router", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if _, err := sharedDB.Pool.Exec(ctx, - `UPDATE agents SET status='published' WHERE id=$1`, ag.ID); err != nil { - t.Fatalf("publish agent: %v", err) - } - - id, err := sharedDB.CreateEntryChangeRequest(ctx, domain.EntryResourceAgent, ag.ID, - domain.EntryChangeVisibility, json.RawMessage(`{"visibility":"public"}`), actor()) - if err != nil { - t.Fatalf("create: %v", err) - } - if _, err := sharedDB.ApproveEntryChangeRequest(ctx, id, 1, reviewer()); err != nil { - t.Fatalf("approve: %v", err) - } - var vis string - if err := sharedDB.Pool.QueryRow(ctx, `SELECT visibility FROM agents WHERE id=$1`, ag.ID).Scan(&vis); err != nil { - t.Fatalf("read agent: %v", err) - } - if vis != "public" { - t.Errorf("agent visibility = %q, want public", vis) - } -} diff --git a/server/internal/store/migrate_test.go b/server/internal/store/migrate_test.go index dadaa072..5827a35f 100644 --- a/server/internal/store/migrate_test.go +++ b/server/internal/store/migrate_test.go @@ -61,8 +61,6 @@ func TestMigrate_AppliesAllMigrationsToFreshDatabase(t *testing.T) { "publishers", "mcp_servers", "mcp_server_versions", - "agents", - "agent_versions", "audit_log", "reports", "instance_tags", @@ -83,6 +81,18 @@ func TestMigrate_AppliesAllMigrationsToFreshDatabase(t *testing.T) { } } + // 000026 dropped the agent tables. + for _, table := range []string{"agents", "agent_versions"} { + var exists bool + if err := db.Pool.QueryRow(ctx, + `SELECT to_regclass('public.' || $1) IS NOT NULL`, table).Scan(&exists); err != nil { + t.Fatalf("checking table %q: %v", table, err) + } + if exists { + t.Errorf("table %q should have been dropped by 000026", table) + } + } + // A sample of columns added by later migrations on mcp_servers. They // were added incrementally and prove the later migrations ran in order. // - 000002: featured (its `tags` twin was dropped by 000022) @@ -135,15 +145,9 @@ func TestMigrate_AppliesAllMigrationsToFreshDatabase(t *testing.T) { if columnExists("mcp_servers", "tags") { t.Error("column mcp_servers.tags should have been dropped by 000022") } - if columnExists("agents", "tags") { - t.Error("column agents.tags should have been dropped by 000022") - } if !columnExists("mcp_server_versions", "tags") { t.Error("column mcp_server_versions.tags not created by 000022") } - if !columnExists("agent_versions", "tags") { - t.Error("column agent_versions.tags not created by 000022") - } if !columnExists("instance_tags", "managed") { t.Error("column instance_tags.managed not created by 000023") } diff --git a/server/internal/store/publisher.go b/server/internal/store/publisher.go index dace804a..471cabd0 100644 --- a/server/internal/store/publisher.go +++ b/server/internal/store/publisher.go @@ -196,7 +196,7 @@ func (db *DB) UpdatePublisher(ctx context.Context, publisherID string, p UpdateP } // DeletePublisher hard-deletes a publisher and cascades the deletion to every -// resource it owns: all MCP servers and agents (whatever their status), their +// resource it owns: all MCP servers (whatever their status), their // version rows, and any community reports filed against them. Role grants // scoped to the publisher are removed automatically by their ON DELETE CASCADE // foreign key. @@ -204,7 +204,7 @@ func (db *DB) UpdatePublisher(ctx context.Context, publisherID string, p UpdateP // The whole cascade runs in one transaction, so the publisher and all of its // dependents disappear together or not at all. The entry and version tables use // ON DELETE RESTRICT, so children are deleted bottom-up — versions before their -// parent mcp_server/agent rows, and those before the publisher itself — rather +// parent mcp_server rows, and those before the publisher itself — rather // than relying on the database to cascade. A delete on a publisher with no // resources is just the final DELETE with nothing to sweep. func (db *DB) DeletePublisher(ctx context.Context, publisherID string) error { @@ -224,17 +224,15 @@ func (db *DB) DeletePublisher(ctx context.Context, publisherID string) error { // no dangling reports behind. if _, err := tx.Exec(ctx, `DELETE FROM reports - WHERE (resource_type='mcp_server' - AND resource_id IN (SELECT id FROM mcp_servers WHERE publisher_id=$1)) - OR (resource_type='agent' - AND resource_id IN (SELECT id FROM agents WHERE publisher_id=$1))`, + WHERE resource_type='mcp_server' + AND resource_id IN (SELECT id FROM mcp_servers WHERE publisher_id=$1)`, publisherID); err != nil { recordErr(span, err) return fmt.Errorf("deleting resource reports: %w", err) } // Version tables use ON DELETE RESTRICT, so delete version rows before the - // parent mcp_server/agent rows. + // parent mcp_server rows. if _, err := tx.Exec(ctx, `DELETE FROM mcp_server_versions WHERE server_id IN (SELECT id FROM mcp_servers WHERE publisher_id=$1)`, @@ -248,20 +246,6 @@ func (db *DB) DeletePublisher(ctx context.Context, publisherID string) error { recordErr(span, err) return fmt.Errorf("deleting mcp servers: %w", err) } - if _, err := tx.Exec(ctx, - `DELETE FROM agent_versions - WHERE agent_id IN (SELECT id FROM agents WHERE publisher_id=$1)`, - publisherID); err != nil { - recordErr(span, err) - return fmt.Errorf("deleting agent versions: %w", err) - } - agentTag, err := tx.Exec(ctx, - `DELETE FROM agents WHERE publisher_id=$1`, publisherID) - if err != nil { - recordErr(span, err) - return fmt.Errorf("deleting agents: %w", err) - } - tag, err := tx.Exec(ctx, `DELETE FROM publishers WHERE id=$1`, publisherID) if err != nil { recordErr(span, err) @@ -272,10 +256,7 @@ func (db *DB) DeletePublisher(ctx context.Context, publisherID string) error { return ErrNotFound } - span.SetAttributes( - attribute.Int64("registry.cascade.mcp_servers_deleted", mcpTag.RowsAffected()), - attribute.Int64("registry.cascade.agents_deleted", agentTag.RowsAffected()), - ) + span.SetAttributes(attribute.Int64("registry.cascade.mcp_servers_deleted", mcpTag.RowsAffected())) if err := tx.Commit(ctx); err != nil { recordErr(span, err) diff --git a/server/internal/store/publisher_stats_test.go b/server/internal/store/publisher_stats_test.go index 9cd4fa73..f25860bf 100644 --- a/server/internal/store/publisher_stats_test.go +++ b/server/internal/store/publisher_stats_test.go @@ -37,11 +37,6 @@ func TestGetPublisherStats(t *testing.T) { t.Fatalf("CreateMCPServer other: %v", err) } - // One draft agent under stats-pub. - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{PublisherID: pubID, Slug: "ag", Name: "Ag"}); err != nil { - t.Fatalf("CreateAgent: %v", err) - } - // u1 dual-hats Editor + Reviewer; u2 is a Viewer. Distinct members = 2. u1, err := sharedDB.CreateUser(ctx, store.CreateUserParams{Email: "u1@stats.test"}) if err != nil { @@ -86,9 +81,6 @@ func TestGetPublisherStats(t *testing.T) { if s.MCPStatusBreakdown.Draft != 1 || s.MCPStatusBreakdown.Published != 1 { t.Errorf("mcp breakdown = %+v, want draft 1 / published 1", *s.MCPStatusBreakdown) } - if s.Agents != 1 || s.AgentStatusBreakdown.Draft != 1 { - t.Errorf("agents = %d breakdown = %+v, want 1 draft", s.Agents, *s.AgentStatusBreakdown) - } if s.Members != 2 { t.Errorf("Members = %d, want 2 distinct principals", s.Members) } diff --git a/server/internal/store/publisher_test.go b/server/internal/store/publisher_test.go index 05bcf640..26fea042 100644 --- a/server/internal/store/publisher_test.go +++ b/server/internal/store/publisher_test.go @@ -187,7 +187,7 @@ func TestSetPublisherVerified_NotFound(t *testing.T) { } } -// TestGetPublisherBySlug exercises the existing helper used by server/agent creation. +// TestGetPublisherBySlug exercises the existing helper used by server creation. func TestGetPublisherBySlug(t *testing.T) { resetDB(t) ctx := context.Background() @@ -281,7 +281,7 @@ func TestDeletePublisher_NotFound(t *testing.T) { func TestDeletePublisher_PurgesTombstonedChildren(t *testing.T) { // Regression: earlier DeletePublisher only COUNT-checked non-deleted // children. The ON DELETE RESTRICT FK then blocked the hard delete - // whenever soft-deleted (status='deleted') mcp_servers or agents still + // whenever soft-deleted (status='deleted') mcp_servers still // referenced the publisher — and version rows under them blocked the // child delete in turn. The fixed version purges tombstoned descendants // (version rows first, then parent rows) in the same transaction. @@ -317,28 +317,6 @@ func TestDeletePublisher_PurgesTombstonedChildren(t *testing.T) { t.Fatalf("DeleteMCPServer: %v", err) } - // Create an agent + version, then soft-delete the agent. - ag, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub.ID, - Slug: "tombstone-agent", - Name: "Tombstone Agent", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if _, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: ag.ID, - Version: "1.0.0", - EndpointURL: "https://agents.example/tombstone", - Skills: []byte(`[]`), - ProtocolVersion: "0.3.0", - }); err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } - if err := sharedDB.DeleteAgent(ctx, ag.ID); err != nil { - t.Fatalf("DeleteAgent: %v", err) - } - // All active entries are gone; only tombstones remain. DeletePublisher // must succeed and purge those tombstones transactionally. if err := sharedDB.DeletePublisher(ctx, pub.ID); err != nil { @@ -363,27 +341,18 @@ func TestDeletePublisher_SweepsTombstonedChildren(t *testing.T) { t.Fatalf("CreatePublisher: %v", err) } - // A tombstoned MCP server and a tombstoned agent under the publisher. + // A tombstoned MCP server under the publisher. srv, err := sharedDB.CreateMCPServer(ctx, store.CreateMCPServerParams{ PublisherID: pub.ID, Slug: "weather", Name: "Weather", }) if err != nil { t.Fatalf("create server: %v", err) } - ag, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub.ID, Slug: "planner", Name: "Planner", - }) - if err != nil { - t.Fatalf("create agent: %v", err) - } if err := sharedDB.DeleteMCPServer(ctx, srv.ID); err != nil { t.Fatalf("soft-delete server: %v", err) } - if err := sharedDB.DeleteAgent(ctx, ag.ID); err != nil { - t.Fatalf("soft-delete agent: %v", err) - } - // DeletePublisher must sweep tombstoned children of both kinds. + // DeletePublisher must sweep tombstoned children. if err := sharedDB.DeletePublisher(ctx, pub.ID); err != nil { t.Fatalf("DeletePublisher: %v", err) } @@ -393,7 +362,7 @@ func TestDeletePublisher_SweepsTombstonedChildren(t *testing.T) { } // TestDeletePublisher_CascadesActiveResources verifies that deleting a -// publisher cascades to its active MCP servers and agents (and their versions), +// publisher cascades to its active MCP servers (and their versions), // plus any reports filed against them — rather than failing with ErrConflict. func TestDeletePublisher_CascadesActiveResources(t *testing.T) { resetDB(t) @@ -426,21 +395,6 @@ func TestDeletePublisher_CascadesActiveResources(t *testing.T) { t.Fatalf("CreateReport: %v", err) } - // An active agent with a version. - ag, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub.ID, Slug: "active-agent", Name: "Active Agent", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if _, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: ag.ID, Version: "1.0.0", - EndpointURL: "https://agents.example/active", Skills: []byte(`[]`), - ProtocolVersion: "0.3.0", - }); err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } - // The delete must succeed (no ErrConflict) and cascade everything away. if err := sharedDB.DeletePublisher(ctx, pub.ID); err != nil { t.Fatalf("DeletePublisher: %v", err) @@ -455,9 +409,7 @@ func TestDeletePublisher_CascadesActiveResources(t *testing.T) { arg string }{ {"mcp_servers", `SELECT COUNT(*) FROM mcp_servers WHERE publisher_id=$1`, pub.ID}, - {"agents", `SELECT COUNT(*) FROM agents WHERE publisher_id=$1`, pub.ID}, {"mcp_server_versions", `SELECT COUNT(*) FROM mcp_server_versions WHERE server_id=$1`, srv.ID}, - {"agent_versions", `SELECT COUNT(*) FROM agent_versions WHERE agent_id=$1`, ag.ID}, {"reports", `SELECT COUNT(*) FROM reports WHERE resource_id=$1`, srv.ID}, } { var n int diff --git a/server/internal/store/reports.go b/server/internal/store/reports.go index fc833fe6..3b8d088e 100644 --- a/server/internal/store/reports.go +++ b/server/internal/store/reports.go @@ -70,14 +70,12 @@ func (db *DB) ListReports(ctx context.Context, p ListReportsParams) ([]domain.Re // bare ULID. LEFT JOINs: a report must survive its target's deletion. q := `SELECT r.id, r.resource_type, r.resource_id, r.issue_type, r.description, coalesce(r.reporter_ip, ''), r.status, r.created_at, r.reviewed_at, coalesce(r.reviewed_by, ''), - coalesce(pm.slug, pa.slug, '') AS resource_ns, - coalesce(m.slug, a.slug, '') AS resource_slug, - coalesce(m.name, a.name, '') AS resource_name + coalesce(pm.slug, '') AS resource_ns, + coalesce(m.slug, '') AS resource_slug, + coalesce(m.name, '') AS resource_name FROM reports r LEFT JOIN mcp_servers m ON r.resource_type = 'mcp_server' AND m.id = r.resource_id - LEFT JOIN publishers pm ON pm.id = m.publisher_id - LEFT JOIN agents a ON r.resource_type = 'agent' AND a.id = r.resource_id - LEFT JOIN publishers pa ON pa.id = a.publisher_id` + LEFT JOIN publishers pm ON pm.id = m.publisher_id` args := []any{} if p.Status != "" { q += " WHERE r.status = $1" diff --git a/server/internal/store/reports_test.go b/server/internal/store/reports_test.go index 31a94b1f..595dd8f1 100644 --- a/server/internal/store/reports_test.go +++ b/server/internal/store/reports_test.go @@ -30,8 +30,8 @@ func TestReports_CreateAndList(t *testing.T) { } if _, err := sharedDB.CreateReport(ctx, store.CreateReportParams{ - ResourceType: "agent", - ResourceID: "01HAGENT", + ResourceType: "mcp_server", + ResourceID: "01HMCP2", IssueType: "spam", Description: "this is advertising", ReporterIP: "2.2.2.2", @@ -47,9 +47,9 @@ func TestReports_CreateAndList(t *testing.T) { if len(all) != 2 { t.Fatalf("expected 2 reports, got %d", len(all)) } - // Newest first — the agent one was inserted second. - if all[0].ResourceType != "agent" { - t.Errorf("newest first: [0].resource_type = %q, want agent", all[0].ResourceType) + // Newest first — the spam one was inserted second. + if all[0].ResourceID != "01HMCP2" { + t.Errorf("newest first: [0].resource_id = %q, want 01HMCP2", all[0].ResourceID) } // ListReports — status filter @@ -95,7 +95,7 @@ func TestReports_ListJoinsReportedResourceHandle(t *testing.T) { // A report whose target never existed — the join must degrade to empty // strings, not drop the row. if _, err := sharedDB.CreateReport(ctx, store.CreateReportParams{ - ResourceType: "agent", + ResourceType: "mcp_server", ResourceID: "01HNOSUCH", IssueType: "spam", Description: "this is advertising", @@ -110,7 +110,7 @@ func TestReports_ListJoinsReportedResourceHandle(t *testing.T) { if len(all) != 2 { t.Fatalf("expected 2 reports, got %d", len(all)) } - // Newest first: [0] is the orphan agent report, [1] the MCP one. + // Newest first: [0] is the orphan report, [1] the joined one. if all[0].ResourceNS != "" || all[0].ResourceSlug != "" || all[0].ResourceName != "" { t.Errorf("orphan report should have empty handle, got %q/%q (%q)", all[0].ResourceNS, all[0].ResourceSlug, all[0].ResourceName) @@ -182,7 +182,7 @@ func TestReports_UpdateStatus_Invalid(t *testing.T) { ctx := context.Background() r, _ := sharedDB.CreateReport(ctx, store.CreateReportParams{ - ResourceType: "agent", ResourceID: "01H", IssueType: "other", Description: "x", + ResourceType: "mcp_server", ResourceID: "01H", IssueType: "other", Description: "x", }) if err := sharedDB.UpdateReportStatus(ctx, r.ID, "bogus", "admin"); err == nil { t.Error("expected error for invalid status") diff --git a/server/internal/store/review.go b/server/internal/store/review.go index 03469370..0c702c07 100644 --- a/server/internal/store/review.go +++ b/server/internal/store/review.go @@ -372,118 +372,6 @@ func diagnoseMCPDeletionMiss(ctx context.Context, db *DB, serverID string) error return ErrConflict } -// RequestAgentDeletion is the agent equivalent of RequestMCPDeletion. -func (db *DB) RequestAgentDeletion(ctx context.Context, agentID string, a Actor) error { - ctx, span := startSpan(ctx, "RequestAgentDeletion") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agents - SET deletion_requested_at = NOW(), - deletion_requested_by = $2, - deletion_requested_by_email = $3, - updated_at = NOW() - WHERE id = $1 - AND deletion_requested_at IS NULL - AND deleted_at IS NULL`, - agentID, a.Subject, a.Email) - if err != nil { - recordErr(span, err) - return fmt.Errorf("requesting agent deletion: %w", err) - } - if tag.RowsAffected() == 0 { - return diagnoseAgentDeletionMiss(ctx, db, agentID) - } - return nil -} - -// ApproveAgentDeletion is the agent equivalent of ApproveMCPDeletion. -// Sets both deleted_at and status='deleted' so existing read filters -// keep working without any change. -func (db *DB) ApproveAgentDeletion(ctx context.Context, agentID string, a Actor) error { - ctx, span := startSpan(ctx, "ApproveAgentDeletion") - defer span.End() - - tx, err := db.Pool.Begin(ctx) - if err != nil { - recordErr(span, err) - return fmt.Errorf("begin tx: %w", err) - } - defer tx.Rollback(ctx) //nolint:errcheck - - var requestedBy string - err = tx.QueryRow(ctx, ` - UPDATE agents - SET deleted_at = NOW(), - status = 'deleted', - updated_at = NOW() - WHERE id = $1 - AND deletion_requested_at IS NOT NULL - AND deleted_at IS NULL - RETURNING coalesce(deletion_requested_by, '')`, agentID).Scan(&requestedBy) - if errors.Is(err, pgx.ErrNoRows) { - return diagnoseAgentDeletionMiss(ctx, db, agentID) - } - if err != nil { - recordErr(span, err) - return fmt.Errorf("approving agent deletion: %w", err) - } - if err := refuseSelfApproval(requestedBy, a); err != nil { - recordErr(span, err) - return err - } - if err := tx.Commit(ctx); err != nil { - recordErr(span, err) - return fmt.Errorf("commit tx: %w", err) - } - return nil -} - -// RejectAgentDeletion is the agent equivalent of RejectMCPDeletion. -func (db *DB) RejectAgentDeletion(ctx context.Context, agentID string, _ Actor) error { - ctx, span := startSpan(ctx, "RejectAgentDeletion") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agents - SET deletion_requested_at = NULL, - deletion_requested_by = NULL, - deletion_requested_by_email = NULL, - updated_at = NOW() - WHERE id = $1 - AND deletion_requested_at IS NOT NULL - AND deleted_at IS NULL`, agentID) - if err != nil { - recordErr(span, err) - return fmt.Errorf("rejecting agent deletion: %w", err) - } - if tag.RowsAffected() == 0 { - return diagnoseAgentDeletionMiss(ctx, db, agentID) - } - return nil -} - -func diagnoseAgentDeletionMiss(ctx context.Context, db *DB, agentID string) error { - var ( - requestedAt *time.Time //nolint:wastedassign // scanned for symmetry; not consulted - deletedAt *time.Time - ) - _ = requestedAt - err := db.Pool.QueryRow(ctx, - `SELECT deletion_requested_at, deleted_at FROM agents WHERE id=$1`, - agentID).Scan(&requestedAt, &deletedAt) - if errors.Is(err, pgx.ErrNoRows) { - return ErrNotFound - } - if err != nil { - return fmt.Errorf("diagnosing deletion miss: %w", err) - } - if deletedAt != nil { - return ErrNotFound - } - return ErrConflict -} - // ── Review queue ───────────────────────────────────────────────────────── // ReviewQueueItemKind discriminates the kinds of items that show up in @@ -491,12 +379,9 @@ func diagnoseAgentDeletionMiss(ctx context.Context, db *DB, agentID string) erro type ReviewQueueItemKind string const ( - ReviewQueueItemMCPVersion ReviewQueueItemKind = "mcp_version" - ReviewQueueItemAgentVersion ReviewQueueItemKind = "agent_version" - ReviewQueueItemMCPDeletion ReviewQueueItemKind = "mcp_deletion" - ReviewQueueItemAgentDeletion ReviewQueueItemKind = "agent_deletion" - ReviewQueueItemMCPChange ReviewQueueItemKind = "mcp_change" - ReviewQueueItemAgentChange ReviewQueueItemKind = "agent_change" + ReviewQueueItemMCPVersion ReviewQueueItemKind = "mcp_version" + ReviewQueueItemMCPDeletion ReviewQueueItemKind = "mcp_deletion" + ReviewQueueItemMCPChange ReviewQueueItemKind = "mcp_change" ) // ReviewQueueItem is a flattened entry in the reviewer's queue. Version @@ -538,11 +423,11 @@ type ListReviewQueueParams struct { PublisherIDs []string } -// ListReviewQueue returns pending_review versions and pending deletions, -// newest first. The query unions the four sources (MCP version, agent version, -// MCP deletion, agent deletion) and sorts by the submission / request -// timestamp. When p.PublisherIDs is non-empty the result is restricted to those -// owning publishers (reviewer scoping); empty means no filter. +// ListReviewQueue returns pending_review versions, pending deletions and +// pending entry changes, newest first. The query unions the three sources and +// sorts by the submission / request timestamp. When p.PublisherIDs is +// non-empty the result is restricted to those owning publishers (reviewer +// scoping); empty means no filter. // // Reviewers and admins are the only legitimate callers; the handler resolves // the caller's reviewer scope (Server Admin / global Reviewer → all publishers; @@ -599,17 +484,6 @@ func (db *DB) ListReviewQueue(ctx context.Context, p ListReviewQueueParams) ([]R WHERE v.review_state = 'pending_review' AND v.submitted_at IS NOT NULL AND s.status != 'deleted' - UNION ALL - SELECT 'agent_version'::text, p.id, p.slug, a.slug, a.id, - av.version, av.revision, av.submitted_at, - coalesce(av.submitted_by, ''), coalesce(av.submitted_by_email, ''), - av.request_public, '', '', NULL::jsonb - FROM agent_versions av - JOIN agents a ON a.id = av.agent_id - JOIN publishers p ON p.id = a.publisher_id - WHERE av.review_state = 'pending_review' AND av.submitted_at IS NOT NULL - AND a.status != 'deleted' - UNION ALL SELECT 'mcp_deletion'::text, p.id, p.slug, s.slug, s.id, '', 0, s.deletion_requested_at, @@ -620,16 +494,6 @@ func (db *DB) ListReviewQueue(ctx context.Context, p ListReviewQueueParams) ([]R WHERE s.deletion_requested_at IS NOT NULL AND s.deleted_at IS NULL AND s.status != 'deleted' - UNION ALL - SELECT 'agent_deletion'::text, p.id, p.slug, a.slug, a.id, - '', 0, a.deletion_requested_at, - coalesce(a.deletion_requested_by, ''), coalesce(a.deletion_requested_by_email, ''), - false, '', '', NULL::jsonb - FROM agents a - JOIN publishers p ON p.id = a.publisher_id - WHERE a.deletion_requested_at IS NOT NULL AND a.deleted_at IS NULL - AND a.status != 'deleted' - UNION ALL SELECT 'mcp_change'::text, p.id, p.slug, s.slug, s.id, '', ecr.revision, ecr.submitted_at, @@ -640,17 +504,6 @@ func (db *DB) ListReviewQueue(ctx context.Context, p ListReviewQueueParams) ([]R JOIN publishers p ON p.id = s.publisher_id WHERE ecr.resource_type = 'mcp_server' AND ecr.state = 'pending_review' AND s.status != 'deleted' - - UNION ALL - SELECT 'agent_change'::text, p.id, p.slug, a.slug, a.id, - '', ecr.revision, ecr.submitted_at, - coalesce(ecr.submitted_by, ''), coalesce(ecr.submitted_by_email, ''), - false, ecr.id, ecr.action, ecr.payload - FROM entry_change_requests ecr - JOIN agents a ON a.id = ecr.entry_id - JOIN publishers p ON p.id = a.publisher_id - WHERE ecr.resource_type = 'agent' AND ecr.state = 'pending_review' - AND a.status != 'deleted' ) SELECT kind, publisher_slug, entry_slug, entry_id, version, revision, submitted_at, submitted_by, submitted_by_email, request_public, @@ -749,245 +602,6 @@ func diagnoseMCPApproveMiss(ctx context.Context, db *DB, serverID, version strin return ErrReviewStateMismatch } -// ── Agent versions: workflow ───────────────────────────────────────────── - -// SubmitAgentVersion is the agent equivalent of SubmitMCPVersion. -func (db *DB) SubmitAgentVersion(ctx context.Context, agentID, version string, requestPublic bool, a Actor) error { - ctx, span := startSpan(ctx, "SubmitAgentVersion") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agent_versions - SET review_state = 'pending_review', - submitted_at = NOW(), - submitted_by = $3, - submitted_by_email = $4, - rejection_reason = NULL, - request_public = $5, - updated_at = NOW() - WHERE agent_id = $1 - AND version = $2 - AND review_state IN ('none', 'rejected') - AND published_at IS NULL`, - agentID, version, a.Subject, a.Email, requestPublic) - if err != nil { - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) && pgErr.Code == "23505" { - recordErr(span, ErrConflict) - return ErrConflict - } - recordErr(span, err) - return fmt.Errorf("submitting agent version: %w", err) - } - if tag.RowsAffected() == 0 { - return diagnoseAgentReviewMiss(ctx, db, agentID, version) - } - return nil -} - -// WithdrawAgentVersion is the agent equivalent of WithdrawMCPVersion. -func (db *DB) WithdrawAgentVersion(ctx context.Context, agentID, version string, _ Actor) error { - ctx, span := startSpan(ctx, "WithdrawAgentVersion") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agent_versions - SET review_state = 'none', - submitted_at = NULL, - submitted_by = NULL, - submitted_by_email = NULL, - request_public = false, - updated_at = NOW() - WHERE agent_id = $1 - AND version = $2 - AND review_state = 'pending_review'`, - agentID, version) - if err != nil { - recordErr(span, err) - return fmt.Errorf("withdrawing agent version: %w", err) - } - if tag.RowsAffected() == 0 { - return diagnoseAgentReviewMiss(ctx, db, agentID, version) - } - return nil -} - -// ApproveAgentVersion is the agent equivalent of ApproveMCPVersion, -// including the request_public handling — see that function's commentary. -func (db *DB) ApproveAgentVersion(ctx context.Context, agentID, version string, expectedRevision int, a Actor) (madePublic bool, err error) { - ctx, span := startSpan(ctx, "ApproveAgentVersion") - defer span.End() - - tx, err := db.Pool.Begin(ctx) - if err != nil { - recordErr(span, err) - return false, fmt.Errorf("begin tx: %w", err) - } - defer tx.Rollback(ctx) //nolint:errcheck - - var ( - requestPublic bool - submittedBy string - ) - err = tx.QueryRow(ctx, ` - UPDATE agent_versions - SET review_state = 'none', - reviewed_at = NOW(), - reviewed_by = $3, - reviewed_by_email = $4, - review_decision = 'approved', - published_at = COALESCE(published_at, NOW()), - updated_at = NOW() - WHERE agent_id = $1 - AND version = $2 - AND review_state = 'pending_review' - AND revision = $5 - RETURNING request_public, coalesce(submitted_by, '')`, - agentID, version, a.Subject, a.Email, expectedRevision).Scan(&requestPublic, &submittedBy) - if errors.Is(err, pgx.ErrNoRows) { - if err := diagnoseAgentApproveMissTx(ctx, tx, agentID, version, expectedRevision); err != nil { - recordErr(span, err) - return false, err - } - return false, ErrReviewStateMismatch - } - if err != nil { - recordErr(span, err) - return false, fmt.Errorf("approving agent version: %w", err) - } - if err := refuseSelfApproval(submittedBy, a); err != nil { - recordErr(span, err) - return false, err - } - if _, err := tx.Exec(ctx, - `UPDATE agents SET status='published', updated_at=NOW() WHERE id=$1 AND status='draft'`, - agentID); err != nil { - recordErr(span, err) - return false, fmt.Errorf("promoting agent status: %w", err) - } - if requestPublic { - tag, err := tx.Exec(ctx, - `UPDATE agents SET visibility='public', updated_at=NOW() WHERE id=$1 AND visibility='private'`, - agentID) - if err != nil { - recordErr(span, err) - return false, fmt.Errorf("applying requested public visibility: %w", err) - } - madePublic = tag.RowsAffected() > 0 - } - if err := tx.Commit(ctx); err != nil { - recordErr(span, err) - return false, fmt.Errorf("commit tx: %w", err) - } - return madePublic, nil -} - -// RejectAgentVersion is the agent equivalent of RejectMCPVersion. -func (db *DB) RejectAgentVersion(ctx context.Context, agentID, version string, expectedRevision int, reason string, a Actor) error { - ctx, span := startSpan(ctx, "RejectAgentVersion") - defer span.End() - - tag, err := db.Pool.Exec(ctx, ` - UPDATE agent_versions - SET review_state = 'rejected', - reviewed_at = NOW(), - reviewed_by = $3, - reviewed_by_email = $4, - review_decision = 'rejected', - rejection_reason = $5, - updated_at = NOW() - WHERE agent_id = $1 - AND version = $2 - AND review_state = 'pending_review' - AND revision = $6`, - agentID, version, a.Subject, a.Email, reason, expectedRevision) - if err != nil { - recordErr(span, err) - return fmt.Errorf("rejecting agent version: %w", err) - } - if tag.RowsAffected() == 0 { - return diagnoseAgentApproveMiss(ctx, db, agentID, version, expectedRevision) - } - return nil -} - -func diagnoseAgentReviewMiss(ctx context.Context, db *DB, agentID, version string) error { - var ( - state string - publishedAt *time.Time - ) - err := db.Pool.QueryRow(ctx, - `SELECT review_state, published_at FROM agent_versions - WHERE agent_id = $1 AND version = $2`, - agentID, version).Scan(&state, &publishedAt) - if errors.Is(err, pgx.ErrNoRows) { - return ErrNotFound - } - if err != nil { - return fmt.Errorf("diagnosing agent review miss: %w", err) - } - if publishedAt != nil { - return ErrAlreadyPublished - } - return ErrReviewStateMismatch -} - -func diagnoseAgentApproveMiss(ctx context.Context, db *DB, agentID, version string, expectedRevision int) error { - var ( - state string - revision int - publishedAt *time.Time - ) - err := db.Pool.QueryRow(ctx, - `SELECT review_state, revision, published_at FROM agent_versions - WHERE agent_id = $1 AND version = $2`, - agentID, version).Scan(&state, &revision, &publishedAt) - if errors.Is(err, pgx.ErrNoRows) { - return ErrNotFound - } - if err != nil { - return fmt.Errorf("diagnosing agent approve miss: %w", err) - } - if publishedAt != nil { - return ErrAlreadyPublished - } - if state != string(domain.ReviewStatePendingReview) { - return ErrReviewStateMismatch - } - if revision != expectedRevision { - return ErrReviewRevisionMismatch - } - return ErrReviewStateMismatch -} - -func diagnoseAgentApproveMissTx(ctx context.Context, tx pgx.Tx, agentID, version string, expectedRevision int) error { - var ( - state string - revision int - publishedAt *time.Time - ) - err := tx.QueryRow(ctx, - `SELECT review_state, revision, published_at FROM agent_versions - WHERE agent_id = $1 AND version = $2`, - agentID, version).Scan(&state, &revision, &publishedAt) - if errors.Is(err, pgx.ErrNoRows) { - return ErrNotFound - } - if err != nil { - return fmt.Errorf("diagnosing agent approve miss: %w", err) - } - if publishedAt != nil { - return ErrAlreadyPublished - } - if state != string(domain.ReviewStatePendingReview) { - return ErrReviewStateMismatch - } - if revision != expectedRevision { - return ErrReviewRevisionMismatch - } - return ErrReviewStateMismatch -} - // diagnoseMCPApproveMissTx is the in-transaction variant used by // ApproveMCPVersion (the read must see the same snapshot as the failed // UPDATE). diff --git a/server/internal/store/review_test.go b/server/internal/store/review_test.go index 93ec35a0..e516234a 100644 --- a/server/internal/store/review_test.go +++ b/server/internal/store/review_test.go @@ -306,136 +306,6 @@ func TestRejectMCPVersion_StateMismatchOnDraft(t *testing.T) { } } -// ── Agent version workflow ────────────────────────────────────────────── - -func seedDraftAgentVersion(t *testing.T, ctx context.Context, ns, slug, ver string) string { - t.Helper() - pubID := insertPublisher(t, ns, ns) - ag, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: slug, Name: slug, - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if _, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: ag.ID, - Version: ver, - EndpointURL: "https://agent.example/api", - Skills: json.RawMessage(`[{"id":"s1","name":"s","description":"d","tags":["x"]}]`), - DefaultInputModes: []string{"text/plain"}, - DefaultOutputModes: []string{"text/plain"}, - ProtocolVersion: "0.3.0", - }); err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } - return ag.ID -} - -func readAgentReviewState(t *testing.T, ctx context.Context, agentID, version string) (state string, revision int, reason string, publishedAt *string) { - t.Helper() - var pa *string - err := sharedDB.Pool.QueryRow(ctx, ` - SELECT review_state, revision, coalesce(rejection_reason,''), - to_char(published_at, 'YYYY-MM-DD"T"HH24:MI:SS') - FROM agent_versions WHERE agent_id=$1 AND version=$2`, - agentID, version, - ).Scan(&state, &revision, &reason, &pa) - if err != nil { - t.Fatalf("read agent review state: %v", err) - } - return state, revision, reason, pa -} - -func TestSubmitAgentVersion_DraftToPending(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit: %v", err) - } - state, _, _, _ := readAgentReviewState(t, ctx, agID, "0.1.0") - if state != "pending_review" { - t.Errorf("state = %q, want pending_review", state) - } -} - -func TestApproveAgentVersion_HappyPath(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit: %v", err) - } - if _, err := sharedDB.ApproveAgentVersion(ctx, agID, "0.1.0", 1, reviewer()); err != nil { - t.Fatalf("approve: %v", err) - } - state, _, _, pa := readAgentReviewState(t, ctx, agID, "0.1.0") - if state != "none" { - t.Errorf("state = %q, want none", state) - } - if pa == nil { - t.Errorf("published_at should be set") - } - - // Parent agent status should have flipped to 'published'. - var st string - if err := sharedDB.Pool.QueryRow(ctx, - `SELECT status FROM agents WHERE id=$1`, agID).Scan(&st); err != nil { - t.Fatalf("read agent status: %v", err) - } - if st != "published" { - t.Errorf("agent.status = %q, want published", st) - } -} - -func TestApproveAgentVersion_RevisionMismatch(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit: %v", err) - } - _, err := sharedDB.ApproveAgentVersion(ctx, agID, "0.1.0", 99, reviewer()) - if !errors.Is(err, store.ErrReviewRevisionMismatch) { - t.Errorf("err = %v, want ErrReviewRevisionMismatch", err) - } -} - -func TestRejectAgentVersion_HappyPath(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit: %v", err) - } - if err := sharedDB.RejectAgentVersion(ctx, agID, "0.1.0", 1, "needs polish", reviewer()); err != nil { - t.Fatalf("reject: %v", err) - } - state, _, reason, _ := readAgentReviewState(t, ctx, agID, "0.1.0") - if state != "rejected" { - t.Errorf("state = %q, want rejected", state) - } - if reason != "needs polish" { - t.Errorf("reason = %q", reason) - } -} - -func TestWithdrawAgentVersion_PendingToDraft(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit: %v", err) - } - if err := sharedDB.WithdrawAgentVersion(ctx, agID, "0.1.0", actor()); err != nil { - t.Fatalf("withdraw: %v", err) - } - state, _, _, _ := readAgentReviewState(t, ctx, agID, "0.1.0") - if state != "none" { - t.Errorf("state = %q, want none", state) - } -} - // ── Deletion flow ─────────────────────────────────────────────────────── func TestRequestMCPDeletion_HappyPath(t *testing.T) { @@ -526,7 +396,7 @@ func TestRejectMCPDeletion_ClearsRequest(t *testing.T) { } } -func TestListReviewQueue_UnionsAllFourSources(t *testing.T) { +func TestListReviewQueue_UnionsAllSources(t *testing.T) { resetDB(t) ctx := context.Background() @@ -540,15 +410,11 @@ func TestListReviewQueue_UnionsAllFourSources(t *testing.T) { if err := sharedDB.RequestMCPDeletion(ctx, srvB, actor()); err != nil { t.Fatalf("request mcp deletion: %v", err) } - // Agent version: pending_review. - agA := seedDraftAgentVersion(t, ctx, "initech", "planner", "0.1.0") - if err := sharedDB.SubmitAgentVersion(ctx, agA, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit agent version: %v", err) - } - // Agent deletion: pending request. - agB := seedDraftAgentVersion(t, ctx, "umbrella", "sweeper", "0.1.0") - if err := sharedDB.RequestAgentDeletion(ctx, agB, actor()); err != nil { - t.Fatalf("request agent deletion: %v", err) + // MCP entry change: pending request. + srvD := seedDraftMCPVersion(t, ctx, "initech", "planner", "1.0.0") + if _, err := sharedDB.CreateEntryChangeRequest(ctx, domain.EntryResourceMCPServer, srvD, + domain.EntryChangeMetadataEdit, json.RawMessage(`{"name":"x"}`), actor()); err != nil { + t.Fatalf("create entry change: %v", err) } // Approved versions and rejected ones must not appear in the queue. @@ -564,17 +430,16 @@ func TestListReviewQueue_UnionsAllFourSources(t *testing.T) { if err != nil { t.Fatalf("ListReviewQueue: %v", err) } - if len(items) != 4 { - t.Errorf("expected 4 items (1 mcp ver + 1 mcp del + 1 ag ver + 1 ag del), got %d", len(items)) + if len(items) != 3 { + t.Errorf("expected 3 items (1 version + 1 deletion + 1 change), got %d", len(items)) } kinds := map[store.ReviewQueueItemKind]int{} for _, it := range items { kinds[it.Kind]++ } if kinds[store.ReviewQueueItemMCPVersion] != 1 || - kinds[store.ReviewQueueItemAgentVersion] != 1 || kinds[store.ReviewQueueItemMCPDeletion] != 1 || - kinds[store.ReviewQueueItemAgentDeletion] != 1 { + kinds[store.ReviewQueueItemMCPChange] != 1 { t.Errorf("unexpected kind distribution: %+v", kinds) } } @@ -672,8 +537,8 @@ func TestApproveMCPDeletion_HidesFromPublicReads(t *testing.T) { // TestVersionPublicReadFilter_HidesPendingAndRejected is the version- // level counterpart to TestApproveMCPDeletion_HidesFromPublicReads. -// Confirms that ListMCPServerVersions / GetMCPServerVersion (and the -// agent equivalents) hide unpublished content from anonymous callers +// Confirms that ListMCPServerVersions / GetMCPServerVersion hide +// unpublished content from anonymous callers // when publicOnly=true is passed — closing the workflow leak that // would otherwise expose pending and rejected drafts. func TestVersionPublicReadFilter_HidesPendingAndRejected(t *testing.T) { @@ -767,131 +632,6 @@ func TestVersionPublicReadFilter_HidesPendingAndRejected(t *testing.T) { } } -func TestApproveAgentDeletion_SoftDeletes(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - if err := sharedDB.RequestAgentDeletion(ctx, agID, actor()); err != nil { - t.Fatalf("request: %v", err) - } - if err := sharedDB.ApproveAgentDeletion(ctx, agID, reviewer()); err != nil { - t.Fatalf("approve: %v", err) - } - var deletedAt *string - if err := sharedDB.Pool.QueryRow(ctx, - `SELECT to_char(deleted_at,'YYYY-MM-DD"T"HH24:MI:SS') FROM agents WHERE id=$1`, - agID, - ).Scan(&deletedAt); err != nil { - t.Fatalf("read: %v", err) - } - if deletedAt == nil { - t.Errorf("deleted_at not set") - } -} - -// Exercise the agent-side diagnostic functions (non-Tx variants) that -// the happy paths don't touch. Each test forces a 0-row UPDATE so the -// store falls through to the diagnose* helper. -func TestSubmitAgentVersion_DiagnoseHelpers(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - - // Submit twice → second hits diagnoseAgentReviewMiss because the - // row is no longer in 'none'/'rejected'. - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("first submit: %v", err) - } - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); !errors.Is(err, store.ErrReviewStateMismatch) { - t.Errorf("err = %v, want ErrReviewStateMismatch via diagnoseAgentReviewMiss", err) - } - - // SubmitAgentVersion with unknown id → diagnoseAgentReviewMiss returns NotFound. - if err := sharedDB.SubmitAgentVersion(ctx, "01J0NOPE0000000000000NOPE0", "0.1.0", false, actor()); !errors.Is(err, store.ErrNotFound) { - t.Errorf("err = %v, want ErrNotFound", err) - } -} - -func TestRejectAgentVersion_DiagnoseHelpersNonTx(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - - // RejectAgentVersion runs without a transaction wrapper, so its - // 0-row path goes through diagnoseAgentApproveMiss (the non-Tx - // variant). Reject a Draft → state-mismatch. - if err := sharedDB.RejectAgentVersion(ctx, agID, "0.1.0", 1, "no", reviewer()); !errors.Is(err, store.ErrReviewStateMismatch) { - t.Errorf("err = %v, want ErrReviewStateMismatch via diagnoseAgentApproveMiss", err) - } - - // Submit then reject with stale revision → revision-mismatch via - // the same path. - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit: %v", err) - } - if err := sharedDB.RejectAgentVersion(ctx, agID, "0.1.0", 99, "stale", reviewer()); !errors.Is(err, store.ErrReviewRevisionMismatch) { - t.Errorf("err = %v, want ErrReviewRevisionMismatch", err) - } - - // Reject a not-found row → not-found. - if err := sharedDB.RejectAgentVersion(ctx, "01J0NOPE0000000000000NOPE0", "0.1.0", 1, "x", reviewer()); !errors.Is(err, store.ErrNotFound) { - t.Errorf("err = %v, want ErrNotFound", err) - } -} - -func TestAgentDeletion_DiagnoseHelpers(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - - // Approve when no request is pending → ErrConflict via - // diagnoseAgentDeletionMiss. - if err := sharedDB.ApproveAgentDeletion(ctx, agID, reviewer()); !errors.Is(err, store.ErrConflict) { - t.Errorf("err = %v, want ErrConflict (no pending)", err) - } - - // Reject when no request is pending → same diagnostic. - if err := sharedDB.RejectAgentDeletion(ctx, agID, reviewer()); !errors.Is(err, store.ErrConflict) { - t.Errorf("err = %v, want ErrConflict (reject with no pending)", err) - } - - // Request twice → second hits diagnoseAgentDeletionMiss. - if err := sharedDB.RequestAgentDeletion(ctx, agID, actor()); err != nil { - t.Fatalf("first request: %v", err) - } - if err := sharedDB.RequestAgentDeletion(ctx, agID, actor()); !errors.Is(err, store.ErrConflict) { - t.Errorf("err = %v, want ErrConflict (already pending)", err) - } - - // Operate on a non-existent agent → not-found. - if err := sharedDB.RequestAgentDeletion(ctx, "01J0NOPE0000000000000NOPE0", actor()); !errors.Is(err, store.ErrNotFound) { - t.Errorf("err = %v, want ErrNotFound", err) - } -} - -func TestSubmitAgentVersion_StackingRejectedByPartialUniqueIndex(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "planner", "0.1.0") - if _, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agID, - Version: "0.2.0", - EndpointURL: "https://agent.example/api", - Skills: json.RawMessage(`[{"id":"s1","name":"s","description":"d","tags":["x"]}]`), - DefaultInputModes: []string{"text/plain"}, - DefaultOutputModes: []string{"text/plain"}, - ProtocolVersion: "0.3.0", - }); err != nil { - t.Fatalf("create v0.2.0: %v", err) - } - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit v0.1.0: %v", err) - } - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.2.0", false, actor()); !errors.Is(err, store.ErrConflict) { - t.Errorf("expected ErrConflict, got %v", err) - } -} - // ── Force-delete must not strand review-queue items ───────────────────── // TestForceDeleteMCP_ClearsReviewQueueResidue covers the zombie-review-item @@ -961,35 +701,6 @@ func TestForceDeleteMCP_DropsPendingEntryChange(t *testing.T) { } } -func TestForceDeleteAgent_ClearsReviewQueueResidue(t *testing.T) { - resetDB(t) - ctx := context.Background() - - agID := seedDraftAgentVersion(t, ctx, "umbrella", "sweeper", "0.1.0") - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", false, actor()); err != nil { - t.Fatalf("submit version: %v", err) - } - if err := sharedDB.RequestAgentDeletion(ctx, agID, actor()); err != nil { - t.Fatalf("request deletion: %v", err) - } - if _, err := sharedDB.CreateEntryChangeRequest(ctx, domain.EntryResourceAgent, agID, - domain.EntryChangeMetadataEdit, json.RawMessage(`{"name":"x"}`), actor()); err != nil { - t.Fatalf("create entry change: %v", err) - } - - if err := sharedDB.DeleteAgent(ctx, agID); err != nil { - t.Fatalf("DeleteAgent: %v", err) - } - - items, err := sharedDB.ListReviewQueue(ctx, store.ListReviewQueueParams{Limit: 50}) - if err != nil { - t.Fatalf("ListReviewQueue: %v", err) - } - if len(items) != 0 { - t.Errorf("queue not empty after force-delete: %+v", items) - } -} - // TestListReviewQueue_ExcludesLegacyZombies asserts the queue's defensive // status filter also hides pre-fix residue: a row force-deleted by the OLD // code path (status='deleted' but deleted_at NULL, deletion_requested_at @@ -998,13 +709,13 @@ func TestListReviewQueue_ExcludesLegacyZombies(t *testing.T) { resetDB(t) ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "umbrella", "sweeper", "0.1.0") - if err := sharedDB.RequestAgentDeletion(ctx, agID, actor()); err != nil { + srvID := seedDraftMCPVersion(t, ctx, "umbrella", "sweeper", "1.0.0") + if err := sharedDB.RequestMCPDeletion(ctx, srvID, actor()); err != nil { t.Fatalf("request deletion: %v", err) } // Reproduce the legacy tombstone shape directly. if _, err := sharedDB.Pool.Exec(ctx, - `UPDATE agents SET status='deleted' WHERE id=$1`, agID); err != nil { + `UPDATE mcp_servers SET status='deleted' WHERE id=$1`, srvID); err != nil { t.Fatalf("simulate legacy force-delete: %v", err) } @@ -1031,7 +742,8 @@ func readVisibility(t *testing.T, ctx context.Context, table, id string) string } // TestApproveMCPVersion_RequestPublicFlipsVisibility: a submission with -// request_public makes the (private) entry public atomically on approval. +// request_public makes the (private) entry public atomically on approval, and +// is a no-op (madePublic=false, not an error) on an already-public entry. func TestApproveMCPVersion_RequestPublicFlipsVisibility(t *testing.T) { resetDB(t) ctx := context.Background() @@ -1054,6 +766,28 @@ func TestApproveMCPVersion_RequestPublicFlipsVisibility(t *testing.T) { if v := readVisibility(t, ctx, "mcp_servers", srvID); v != "public" { t.Errorf("visibility after approve = %q, want public", v) } + + // Second version with the request on a now-public entry: no-op. + if _, err := sharedDB.CreateMCPServerVersion(ctx, store.CreateMCPServerVersionParams{ + ServerID: srvID, + Version: "1.1.0", + Runtime: domain.RuntimeStdio, + Packages: validPackages, + Capabilities: json.RawMessage(`{}`), + ProtocolVersions: []string{"2024-11-05"}, + }); err != nil { + t.Fatalf("create second version: %v", err) + } + if err := sharedDB.SubmitMCPVersion(ctx, srvID, "1.1.0", true, actor()); err != nil { + t.Fatalf("submit second: %v", err) + } + madePublic, err = sharedDB.ApproveMCPVersion(ctx, srvID, "1.1.0", 1, reviewer()) + if err != nil { + t.Fatalf("approve second: %v", err) + } + if madePublic { + t.Error("madePublic = true on an already-public entry, want false") + } } // TestApproveMCPVersion_NoRequestKeepsPrivate: without the request, approval @@ -1106,51 +840,6 @@ func TestWithdrawMCPVersion_DropsRequestPublic(t *testing.T) { } } -// TestApproveAgentVersion_RequestPublicFlipsVisibility is the agent twin of -// the MCP test, and also asserts an already-public entry reports -// madePublic=false (no-op, not an error). -func TestApproveAgentVersion_RequestPublicFlipsVisibility(t *testing.T) { - resetDB(t) - ctx := context.Background() - agID := seedDraftAgentVersion(t, ctx, "acme", "helper", "0.1.0") - - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.1.0", true, actor()); err != nil { - t.Fatalf("submit: %v", err) - } - madePublic, err := sharedDB.ApproveAgentVersion(ctx, agID, "0.1.0", 1, reviewer()) - if err != nil { - t.Fatalf("approve: %v", err) - } - if !madePublic { - t.Error("madePublic = false, want true") - } - if v := readVisibility(t, ctx, "agents", agID); v != "public" { - t.Errorf("visibility = %q, want public", v) - } - - // Second version with the request on a now-public entry: no-op. - if _, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agID, - Version: "0.2.0", - EndpointURL: "https://agents.example.com/helper", - Skills: json.RawMessage(`[]`), - Authentication: json.RawMessage(`[]`), - ProtocolVersion: "0.3.0", - }); err != nil { - t.Fatalf("create second version: %v", err) - } - if err := sharedDB.SubmitAgentVersion(ctx, agID, "0.2.0", true, actor()); err != nil { - t.Fatalf("submit second: %v", err) - } - madePublic, err = sharedDB.ApproveAgentVersion(ctx, agID, "0.2.0", 1, reviewer()) - if err != nil { - t.Fatalf("approve second: %v", err) - } - if madePublic { - t.Error("madePublic = true on an already-public entry, want false") - } -} - // TestListReviewQueue_CarriesRequestPublic: the queue surfaces the author's // intent so the reviewer sees the blast radius before approving. func TestListReviewQueue_CarriesRequestPublic(t *testing.T) { diff --git a/server/internal/store/stats.go b/server/internal/store/stats.go index 579a0834..ae86e164 100644 --- a/server/internal/store/stats.go +++ b/server/internal/store/stats.go @@ -14,11 +14,9 @@ type StatusBreakdown struct { // RegistryCounts holds the total number of entries for each resource type. type RegistryCounts struct { - MCPServers int `json:"mcp_servers"` - Agents int `json:"agents"` - Publishers int `json:"publishers"` - MCPStatusBreakdown *StatusBreakdown `json:"mcp_status_breakdown,omitempty"` - AgentStatusBreakdown *StatusBreakdown `json:"agent_status_breakdown,omitempty"` + MCPServers int `json:"mcp_servers"` + Publishers int `json:"publishers"` + MCPStatusBreakdown *StatusBreakdown `json:"mcp_status_breakdown,omitempty"` } // GetRegistryCounts returns the total row count for each resource table. @@ -30,27 +28,21 @@ func (db *DB) GetRegistryCounts(ctx context.Context) (*RegistryCounts, error) { row := db.Pool.QueryRow(ctx, ` SELECT (SELECT COUNT(*) FROM mcp_servers)::int, - (SELECT COUNT(*) FROM agents)::int, (SELECT COUNT(*) FROM publishers)::int, (SELECT COUNT(*) FROM mcp_servers WHERE status='draft')::int, (SELECT COUNT(*) FROM mcp_servers WHERE status='published')::int, - (SELECT COUNT(*) FROM mcp_servers WHERE status='deprecated')::int, - (SELECT COUNT(*) FROM agents WHERE status='draft')::int, - (SELECT COUNT(*) FROM agents WHERE status='published')::int, - (SELECT COUNT(*) FROM agents WHERE status='deprecated')::int + (SELECT COUNT(*) FROM mcp_servers WHERE status='deprecated')::int `) var c RegistryCounts - var mcpBd, agentBd StatusBreakdown - if err := row.Scan(&c.MCPServers, &c.Agents, &c.Publishers, + var mcpBd StatusBreakdown + if err := row.Scan(&c.MCPServers, &c.Publishers, &mcpBd.Draft, &mcpBd.Published, &mcpBd.Deprecated, - &agentBd.Draft, &agentBd.Published, &agentBd.Deprecated, ); err != nil { recordErr(span, err) return nil, fmt.Errorf("getting registry counts: %w", err) } c.MCPStatusBreakdown = &mcpBd - c.AgentStatusBreakdown = &agentBd return &c, nil } @@ -72,13 +64,11 @@ type MemberRoles struct { // signal. Members counts distinct principals holding a grant scoped to this // publisher (global-grant holders are not counted as members of one publisher). type PublisherStats struct { - MCPServers int `json:"mcp_servers"` - Agents int `json:"agents"` - Members int `json:"members"` - PendingReview int `json:"pending_review"` - MCPStatusBreakdown *StatusBreakdown `json:"mcp_status_breakdown"` - AgentStatusBreakdown *StatusBreakdown `json:"agent_status_breakdown"` - MemberRoles *MemberRoles `json:"member_roles"` + MCPServers int `json:"mcp_servers"` + Members int `json:"members"` + PendingReview int `json:"pending_review"` + MCPStatusBreakdown *StatusBreakdown `json:"mcp_status_breakdown"` + MemberRoles *MemberRoles `json:"member_roles"` } // GetPublisherStats returns the per-publisher rollup for the given publisher id. @@ -93,10 +83,6 @@ func (db *DB) GetPublisherStats(ctx context.Context, publisherID string) (*Publi (SELECT COUNT(*) FROM mcp_servers WHERE publisher_id=$1 AND status='draft')::int, (SELECT COUNT(*) FROM mcp_servers WHERE publisher_id=$1 AND status='published')::int, (SELECT COUNT(*) FROM mcp_servers WHERE publisher_id=$1 AND status='deprecated')::int, - (SELECT COUNT(*) FROM agents WHERE publisher_id=$1 AND status!='deleted')::int, - (SELECT COUNT(*) FROM agents WHERE publisher_id=$1 AND status='draft')::int, - (SELECT COUNT(*) FROM agents WHERE publisher_id=$1 AND status='published')::int, - (SELECT COUNT(*) FROM agents WHERE publisher_id=$1 AND status='deprecated')::int, (SELECT COUNT(DISTINCT principal_id) FROM role_grants WHERE publisher_id=$1)::int, (SELECT COUNT(*) FROM role_grants WHERE publisher_id=$1 AND role='viewer')::int, (SELECT COUNT(*) FROM role_grants WHERE publisher_id=$1 AND role='editor')::int, @@ -105,19 +91,15 @@ func (db *DB) GetPublisherStats(ctx context.Context, publisherID string) (*Publi ( (SELECT COUNT(*) FROM mcp_server_versions v JOIN mcp_servers s ON s.id=v.server_id WHERE s.publisher_id=$1 AND v.review_state='pending_review' AND v.submitted_at IS NOT NULL) - + (SELECT COUNT(*) FROM agent_versions av JOIN agents a ON a.id=av.agent_id - WHERE a.publisher_id=$1 AND av.review_state='pending_review' AND av.submitted_at IS NOT NULL) + (SELECT COUNT(*) FROM mcp_servers WHERE publisher_id=$1 AND deletion_requested_at IS NOT NULL AND deleted_at IS NULL) - + (SELECT COUNT(*) FROM agents WHERE publisher_id=$1 AND deletion_requested_at IS NOT NULL AND deleted_at IS NULL) )::int `, publisherID) var s PublisherStats - var mcpBd, agentBd StatusBreakdown + var mcpBd StatusBreakdown var roles MemberRoles if err := row.Scan( &s.MCPServers, &mcpBd.Draft, &mcpBd.Published, &mcpBd.Deprecated, - &s.Agents, &agentBd.Draft, &agentBd.Published, &agentBd.Deprecated, &s.Members, &roles.Viewers, &roles.Editors, &roles.Reviewers, &roles.Admins, &s.PendingReview, ); err != nil { @@ -125,7 +107,6 @@ func (db *DB) GetPublisherStats(ctx context.Context, publisherID string) (*Publi return nil, fmt.Errorf("getting publisher stats: %w", err) } s.MCPStatusBreakdown = &mcpBd - s.AgentStatusBreakdown = &agentBd s.MemberRoles = &roles return &s, nil } @@ -133,10 +114,8 @@ func (db *DB) GetPublisherStats(ctx context.Context, publisherID string) (*Publi // PublicStats holds counts visible to unauthenticated users (published + public only). type PublicStats struct { MCPServers int `json:"mcp_servers"` - Agents int `json:"agents"` Publishers int `json:"publishers"` NewMCPServersWeek int `json:"new_mcp_servers_this_week"` - NewAgentsWeek int `json:"new_agents_this_week"` NewPublishersWeek int `json:"new_publishers_this_week"` } @@ -150,17 +129,11 @@ func (db *DB) GetPublicStats(ctx context.Context) (*PublicStats, error) { SELECT s.publisher_id FROM mcp_servers s WHERE s.status='published' AND s.visibility='public' - UNION - SELECT a.publisher_id - FROM agents a - WHERE a.status='published' AND a.visibility='public' ) SELECT (SELECT COUNT(*) FROM mcp_servers WHERE status='published' AND visibility='public')::int, - (SELECT COUNT(*) FROM agents WHERE status='published' AND visibility='public')::int, (SELECT COUNT(*) FROM active_publishers)::int, (SELECT COUNT(*) FROM mcp_servers WHERE status='published' AND visibility='public' AND created_at > now() - interval '7 days')::int, - (SELECT COUNT(*) FROM agents WHERE status='published' AND visibility='public' AND created_at > now() - interval '7 days')::int, (SELECT COUNT(*) FROM publishers p WHERE p.id IN (SELECT publisher_id FROM active_publishers) AND p.created_at > now() - interval '7 days')::int @@ -168,8 +141,8 @@ func (db *DB) GetPublicStats(ctx context.Context) (*PublicStats, error) { var s PublicStats if err := row.Scan( - &s.MCPServers, &s.Agents, &s.Publishers, - &s.NewMCPServersWeek, &s.NewAgentsWeek, &s.NewPublishersWeek, + &s.MCPServers, &s.Publishers, + &s.NewMCPServersWeek, &s.NewPublishersWeek, ); err != nil { recordErr(span, err) return nil, fmt.Errorf("getting public stats: %w", err) diff --git a/server/internal/store/stats_test.go b/server/internal/store/stats_test.go index 54496fa6..189d1c15 100644 --- a/server/internal/store/stats_test.go +++ b/server/internal/store/stats_test.go @@ -19,7 +19,7 @@ func TestGetRegistryCounts_Empty(t *testing.T) { if err != nil { t.Fatalf("GetRegistryCounts() error = %v", err) } - if counts.MCPServers != 0 || counts.Agents != 0 || counts.Publishers != 0 { + if counts.MCPServers != 0 || counts.Publishers != 0 { t.Errorf("expected all zeros on empty DB, got %+v", counts) } } @@ -41,15 +41,6 @@ func TestGetRegistryCounts_ReflectsInserts(t *testing.T) { } } - // Create 2 agents under pub1. - for _, slug := range []string{"agent-a", "agent-b"} { - if _, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pub1ID, Slug: slug, Name: slug, - }); err != nil { - t.Fatalf("CreateAgent(%q): %v", slug, err) - } - } - counts, err := sharedDB.GetRegistryCounts(ctx) if err != nil { t.Fatalf("GetRegistryCounts() error = %v", err) @@ -60,9 +51,6 @@ func TestGetRegistryCounts_ReflectsInserts(t *testing.T) { if counts.MCPServers != 3 { t.Errorf("MCPServers = %d, want 3", counts.MCPServers) } - if counts.Agents != 2 { - t.Errorf("Agents = %d, want 2", counts.Agents) - } } func TestGetRegistryCounts_IncludesPrivateEntries(t *testing.T) { diff --git a/server/internal/store/tags.go b/server/internal/store/tags.go index 777a7dde..92cde2ea 100644 --- a/server/internal/store/tags.go +++ b/server/internal/store/tags.go @@ -172,8 +172,8 @@ func (db *DB) tagMissingOrManaged(ctx context.Context, slug string) error { // DeleteInstanceTag hard-deletes a tag that no version references. Returns // ErrNotFound if the tag does not exist, ErrManagedTag when it is reconciled -// from server configuration, and ErrConflict if any MCP server or agent -// version carries it (published versions are immutable, so an in-use tag can +// from server configuration, and ErrConflict if any MCP server version +// carries it (published versions are immutable, so an in-use tag can // only be deactivated). func (db *DB) DeleteInstanceTag(ctx context.Context, slug string) error { ctx, span := startSpan(ctx, "DeleteInstanceTag") @@ -186,8 +186,7 @@ func (db *DB) DeleteInstanceTag(ctx context.Context, slug string) error { DELETE FROM instance_tags WHERE slug = $1 AND NOT managed - AND NOT EXISTS (SELECT 1 FROM mcp_server_versions v WHERE v.tags @> $2) - AND NOT EXISTS (SELECT 1 FROM agent_versions av WHERE av.tags @> $2)`, + AND NOT EXISTS (SELECT 1 FROM mcp_server_versions v WHERE v.tags @> $2)`, slug, asArray) if err != nil { recordErr(span, err) diff --git a/server/internal/store/tags_test.go b/server/internal/store/tags_test.go index 239632ad..fad52709 100644 --- a/server/internal/store/tags_test.go +++ b/server/internal/store/tags_test.go @@ -2,7 +2,6 @@ package store_test import ( "context" - "encoding/json" "reflect" "testing" @@ -89,7 +88,6 @@ func TestDeleteInstanceTag_InUseConflicts(t *testing.T) { ctx := context.Background() pubID := insertPublisher(t, "tagged", "Tagged Corp") insertTag(t, "free", "Free", "green") - insertTag(t, "beta", "Beta", "orange") srv, err := sharedDB.CreateMCPServer(ctx, store.CreateMCPServerParams{ PublisherID: pubID, Slug: "srv", Name: "Server", @@ -109,22 +107,6 @@ func TestDeleteInstanceTag_InUseConflicts(t *testing.T) { t.Errorf("expected ErrConflict for in-use tag, got %v", err) } - // Carried by an agent version → conflict too. - agent, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "bot", Name: "Bot", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - if _, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, Version: "1.0.0", EndpointURL: "https://bot.example.com", - ProtocolVersion: "0.2.1", Tags: []string{"beta"}, - }); err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } - if err := sharedDB.DeleteInstanceTag(ctx, "beta"); err != store.ErrConflict { - t.Errorf("expected ErrConflict for agent-carried tag, got %v", err) - } } func TestMissingActiveTagSlugs(t *testing.T) { @@ -259,60 +241,6 @@ func TestVersionTags_FlowThroughReads(t *testing.T) { } } -func TestAgentVersionTags_FlowThroughReads(t *testing.T) { - resetDB(t) - ctx := context.Background() - pubID := insertPublisher(t, "acme", "Acme") - insertTag(t, "free", "Free", "green") - - agent, err := sharedDB.CreateAgent(ctx, store.CreateAgentParams{ - PublisherID: pubID, Slug: "bot", Name: "Bot", - }) - if err != nil { - t.Fatalf("CreateAgent: %v", err) - } - v, err := sharedDB.CreateAgentVersion(ctx, store.CreateAgentVersionParams{ - AgentID: agent.ID, Version: "1.0.0", EndpointURL: "https://bot.example.com", - Skills: json.RawMessage(`[]`), ProtocolVersion: "0.2.1", - Tags: []string{"free"}, - }) - if err != nil { - t.Fatalf("CreateAgentVersion: %v", err) - } - if !reflect.DeepEqual(v.Tags, []string{"free"}) { - t.Errorf("created agent version tags = %v", v.Tags) - } - if err := sharedDB.PublishAgentVersion(ctx, agent.ID, "1.0.0"); err != nil { - t.Fatalf("PublishAgentVersion: %v", err) - } - - row, err := sharedDB.GetAgent(ctx, "acme", "bot", false) - if err != nil { - t.Fatalf("GetAgent: %v", err) - } - if !reflect.DeepEqual(row.Tags, []string{"free"}) { - t.Errorf("agent entry tags = %v", row.Tags) - } - if row.LatestVersion == nil || !reflect.DeepEqual(row.LatestVersion.Tags, []string{"free"}) { - t.Errorf("agent latest_version tags = %+v", row.LatestVersion) - } - - matched, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Tag: "free"}) - if err != nil { - t.Fatalf("ListAgents(tag=free): %v", err) - } - if len(matched) != 1 { - t.Errorf("tag=free matched %d agents, want 1", len(matched)) - } - none, _, err := sharedDB.ListAgents(ctx, store.ListAgentsParams{Tag: "nope"}) - if err != nil { - t.Fatalf("ListAgents(tag=nope): %v", err) - } - if len(none) != 0 { - t.Errorf("tag=nope matched %d agents, want 0", len(none)) - } -} - func TestReconcileManagedInstanceTags(t *testing.T) { resetDB(t) ctx := context.Background() diff --git a/server/internal/store/testhelper_test.go b/server/internal/store/testhelper_test.go index 8a731488..646a5ab0 100644 --- a/server/internal/store/testhelper_test.go +++ b/server/internal/store/testhelper_test.go @@ -54,7 +54,7 @@ func TestMain(m *testing.M) { func resetDB(t *testing.T) { t.Helper() _, err := sharedDB.Pool.Exec(context.Background(), - `TRUNCATE agent_versions, agents, mcp_server_versions, mcp_servers, publishers, audit_log, reports, refresh_tokens, oidc_auth_requests, auth_handoff_codes, role_grants, group_members, groups, users, instance_tags RESTART IDENTITY CASCADE`) + `TRUNCATE mcp_server_versions, mcp_servers, publishers, audit_log, reports, refresh_tokens, oidc_auth_requests, auth_handoff_codes, role_grants, group_members, groups, users, instance_tags RESTART IDENTITY CASCADE`) if err != nil { t.Fatalf("truncating tables: %v", err) } diff --git a/server/migrations/000026_remove_agents.down.sql b/server/migrations/000026_remove_agents.down.sql new file mode 100644 index 00000000..0578a3c5 --- /dev/null +++ b/server/migrations/000026_remove_agents.down.sql @@ -0,0 +1,108 @@ +-- Restores the empty agent tables in their 000025 shape so earlier down +-- migrations still apply; the deleted agent rows are not recoverable. +CREATE TABLE agents ( + id TEXT PRIMARY KEY, + publisher_id TEXT NOT NULL REFERENCES publishers (id) ON DELETE RESTRICT, + slug TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT, + readme TEXT, + visibility TEXT NOT NULL DEFAULT 'private' + CHECK (visibility IN ('private', 'public')), + status TEXT NOT NULL DEFAULT 'draft' + CHECK (status IN ('draft', 'published', 'deprecated', 'deleted')), + featured BOOLEAN NOT NULL DEFAULT FALSE, + verified BOOLEAN NOT NULL DEFAULT FALSE, + view_count INTEGER NOT NULL DEFAULT 0, + copy_count INTEGER NOT NULL DEFAULT 0, + search_vector TSVECTOR GENERATED ALWAYS AS ( + to_tsvector( + 'english', + coalesce(name, '') || ' ' || coalesce(description, '') || ' ' + || coalesce(slug, '') + ) + ) STORED, + deleted_at TIMESTAMPTZ, + deletion_requested_at TIMESTAMPTZ, + deletion_requested_by TEXT, + deletion_requested_by_email TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX idx_agents_publisher ON agents (publisher_id); +CREATE INDEX idx_agents_visibility ON agents (visibility); +CREATE INDEX idx_agents_status ON agents (status); +CREATE INDEX idx_agents_search ON agents USING gin (search_vector); +CREATE INDEX idx_agents_featured ON agents (featured) WHERE featured = TRUE; +CREATE INDEX agents_active_idx ON agents (id) WHERE deleted_at IS NULL; +CREATE UNIQUE INDEX agents_publisher_slug_live +ON agents (publisher_id, slug) WHERE status != 'deleted'; + +CREATE TRIGGER trg_agents_updated_at +BEFORE UPDATE ON agents +FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + +CREATE TABLE agent_versions ( + id TEXT PRIMARY KEY, + agent_id TEXT NOT NULL REFERENCES agents (id) ON DELETE RESTRICT, + version TEXT NOT NULL, + endpoint_url TEXT NOT NULL, + skills JSONB NOT NULL DEFAULT '[]', + capabilities JSONB NOT NULL DEFAULT '{}', + authentication JSONB NOT NULL DEFAULT '[]', + default_input_modes TEXT[] NOT NULL DEFAULT '{text/plain}', + default_output_modes TEXT[] NOT NULL DEFAULT '{text/plain}', + provider JSONB, + documentation_url TEXT, + icon_url TEXT, + protocol_version TEXT NOT NULL, + tags TEXT[] NOT NULL DEFAULT '{}', + status TEXT NOT NULL DEFAULT 'active' + CHECK (status IN ('active', 'deprecated', 'deleted')), + status_message TEXT, + status_changed_at TIMESTAMPTZ NOT NULL DEFAULT now(), + published_at TIMESTAMPTZ, + review_state TEXT NOT NULL DEFAULT 'none', + revision INTEGER NOT NULL DEFAULT 1, + submitted_at TIMESTAMPTZ, + submitted_by TEXT, + submitted_by_email TEXT, + reviewed_at TIMESTAMPTZ, + reviewed_by TEXT, + reviewed_by_email TEXT, + review_decision TEXT, + rejection_reason TEXT, + request_public BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (agent_id, version), + CONSTRAINT agent_versions_review_state_chk + CHECK (review_state IN ('none', 'pending_review', 'rejected')), + CONSTRAINT agent_versions_review_unpublished_chk + CHECK (review_state = 'none' OR published_at IS NULL) +); + +CREATE INDEX idx_agent_versions_agent ON agent_versions (agent_id); +CREATE INDEX idx_agent_versions_published ON agent_versions (published_at) +WHERE published_at IS NOT NULL; +CREATE INDEX idx_agent_versions_status ON agent_versions (status); +CREATE INDEX idx_agent_versions_tags ON agent_versions USING gin (tags); +CREATE INDEX agent_versions_review_state_idx ON agent_versions (review_state) +WHERE review_state != 'none'; +CREATE UNIQUE INDEX agent_versions_one_pending_idx ON agent_versions (agent_id) +WHERE review_state = 'pending_review'; + +CREATE TRIGGER trg_agent_versions_updated_at +BEFORE UPDATE ON agent_versions +FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + +ALTER TABLE reports +DROP CONSTRAINT reports_resource_type_check, +ADD CONSTRAINT reports_resource_type_check +CHECK (resource_type IN ('mcp_server', 'agent')); + +ALTER TABLE entry_change_requests +DROP CONSTRAINT ecr_resource_type_chk, +ADD CONSTRAINT ecr_resource_type_chk +CHECK (resource_type IN ('mcp_server', 'agent')); diff --git a/server/migrations/000026_remove_agents.up.sql b/server/migrations/000026_remove_agents.up.sql new file mode 100644 index 00000000..f5493282 --- /dev/null +++ b/server/migrations/000026_remove_agents.up.sql @@ -0,0 +1,22 @@ +-- The registry catalogs MCP servers only. Rows in the shared tables that +-- point at an agent have no target left once the agent tables go, and would +-- carry a resource type the API no longer defines. +DELETE FROM entry_change_requests +WHERE resource_type = 'agent'; + +DELETE FROM reports +WHERE resource_type = 'agent'; + +DELETE FROM audit_log +WHERE resource_type = 'agent' OR action LIKE 'agent%'; + +ALTER TABLE entry_change_requests +DROP CONSTRAINT ecr_resource_type_chk, +ADD CONSTRAINT ecr_resource_type_chk CHECK (resource_type = 'mcp_server'); + +ALTER TABLE reports +DROP CONSTRAINT reports_resource_type_check, +ADD CONSTRAINT reports_resource_type_check CHECK (resource_type = 'mcp_server'); + +DROP TABLE agent_versions; +DROP TABLE agents; diff --git a/test/load/smoke.js b/test/load/smoke.js index ee337b5f..8d9c3674 100644 --- a/test/load/smoke.js +++ b/test/load/smoke.js @@ -71,12 +71,5 @@ export default function () { })); }); - group('global agent card', () => { - const res = http.get(`${BASE_URL}/.well-known/agent-card.json`); - failures.add(!check(res, { - 'agent card 200': (r) => r.status === 200, - })); - }); - sleep(1); } diff --git a/test/nginx/routing.sh b/test/nginx/routing.sh index 3f214371..ed10cfdd 100755 --- a/test/nginx/routing.sh +++ b/test/nginx/routing.sh @@ -83,7 +83,7 @@ expect_header / X-Frame-Options SAMEORIGIN expect_header /metrics X-Content-Type-Options nosniff # Proxied responses keep the backend's own headers, without the SPA's stacked on. -for path in /docs /api/v1/mcp/servers /agents/acme/bot/.well-known/agent-card.json; do +for path in /docs /api/v1/mcp/servers /.well-known/jwks.json; do expect_header "${path}" Content-Security-Policy "${backend_csp}" expect_header "${path}" X-Frame-Options DENY done diff --git a/web/e2e/activity.spec.ts b/web/e2e/activity.spec.ts index 01220ad0..ace74298 100644 --- a/web/e2e/activity.spec.ts +++ b/web/e2e/activity.spec.ts @@ -123,10 +123,10 @@ test.describe('Activity feed + admin audit', () => { timeout: 15_000, }) - // Open the resource-type Select and pick "Agents" — our seeded MCP rows - // should disappear from view. + // Open the resource-type Select and pick "Publishers" — our seeded MCP + // rows should disappear from view. await page.getByLabel('Resource type').click() - await page.getByRole('option', { name: /agents/i }).click() + await page.getByRole('option', { name: /publishers/i }).click() // Wait for the filtered refetch: the seeded MCP slug must not appear. await expect( page.getByRole('link', { diff --git a/web/e2e/admin-stats.spec.ts b/web/e2e/admin-stats.spec.ts index a9c360c4..9a81dd58 100644 --- a/web/e2e/admin-stats.spec.ts +++ b/web/e2e/admin-stats.spec.ts @@ -12,7 +12,7 @@ * These tests verify that: * a) The stats panel shows numeric values (never "—") after login. * b) No error banner is rendered. - * c) All three keys (mcp_servers, agents, publishers) are present in the API + * c) Both keys (mcp_servers, publishers) are present in the API * response when called with the Bearer access token. */ @@ -34,7 +34,7 @@ test.describe('Admin Dashboard: stats panel (regression)', () => { // The large bold numbers are rendered in a

. const statValues = page.locator('.text-3xl.font-bold') const count = await statValues.count() - expect(count).toBeGreaterThanOrEqual(3) + expect(count).toBeGreaterThanOrEqual(2) for (let i = 0; i < count; i++) { const text = await statValues.nth(i).textContent() @@ -52,7 +52,6 @@ test.describe('Admin Dashboard: stats panel (regression)', () => { const body = await res.json() expect(typeof body.mcp_servers).toBe('number') - expect(typeof body.agents).toBe('number') expect(typeof body.publishers).toBe('number') }) @@ -63,7 +62,7 @@ test.describe('Admin Dashboard: stats panel (regression)', () => { // Read baseline counts. const beforeRes = await apiGet(page, '/api/v1/stats') expect(beforeRes.ok()).toBeTruthy() - const before = await beforeRes.json() as { publishers: number; mcp_servers: number; agents: number } + const before = await beforeRes.json() as { publishers: number; mcp_servers: number } const RUN_ID = Date.now().toString(36) const pubSlug = `stat-pub-${RUN_ID}` @@ -87,7 +86,7 @@ test.describe('Admin Dashboard: stats panel (regression)', () => { // Fetch stats again and verify counts went up. const afterRes = await apiGet(page, '/api/v1/stats') expect(afterRes.ok()).toBeTruthy() - const after = await afterRes.json() as { publishers: number; mcp_servers: number; agents: number } + const after = await afterRes.json() as { publishers: number; mcp_servers: number } expect(after.publishers).toBeGreaterThan(before.publishers) expect(after.mcp_servers).toBeGreaterThan(before.mcp_servers) diff --git a/web/e2e/admin.spec.ts b/web/e2e/admin.spec.ts index 5518aca2..60d2ed6a 100644 --- a/web/e2e/admin.spec.ts +++ b/web/e2e/admin.spec.ts @@ -5,7 +5,6 @@ * * 1. Publisher CRUD — create, edit, then delete a publisher. * 2. MCP Server CRUD — create, edit, visibility toggle, deprecate, delete. - * 3. Agent CRUD — create, edit, visibility toggle, delete. * * These tests run sequentially (workers: 1) because they share mutable DB * state. The setup project must run first to populate e2e/.auth/admin.json. @@ -20,8 +19,6 @@ const PUBLISHER_SLUG = `e2e-pub-${RUN_ID}` const PUBLISHER_NAME = `E2E Publisher ${RUN_ID}` const MCP_SLUG = `e2e-mcp-${RUN_ID}` const MCP_NAME = `E2E MCP ${RUN_ID}` -const AGENT_SLUG = `e2e-agent-${RUN_ID}` -const AGENT_NAME = `E2E Agent ${RUN_ID}` // ── helpers ─────────────────────────────────────────────────────────────────── @@ -211,90 +208,8 @@ test.describe('Admin: MCP Server CRUD', () => { }) }) -// ── Agent ───────────────────────────────────────────────────────────────────── - -test.describe('Admin: Agent CRUD', () => { - test('create an agent', async ({ page }) => { - await goTo(page, '/admin/agents/new') - - // Namespace is a Radix - - )} - {kind === 'mcp' ? ( - <> -

- - -
- - {runtime !== 'stdio' && ( -
- - setRemoteUrl(e.target.value)} - /> -

- Where clients reach the hosted server directly — no package - needed for a purely remote server. -

-
- )} +
+ + +
- + + setRemoteUrl(e.target.value)} /> +

+ Where clients reach the hosted server directly — no package + needed for a purely remote server. +

+ + )} -
- - Package (optional) - -
- - -
-
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
-
- - + +
+ + Package (optional) + +
+ + +
+
- -