diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f502ea7..867b88b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,3 +45,5 @@ jobs: run: pnpm example - name: Check package artifacts run: pnpm run release:check + - name: Prove authenticated agent protocol + run: pnpm run agent:proof diff --git a/AGENTS.md b/AGENTS.md index 081804c..dd3fe04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,11 +10,14 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. validation/evidence bindings, approval, publication, and retirement. - KB-01 owns pure domain work. KB-02 adds declared persistence and authorized application services. KB-03 extends the application with bounded retrieval, - authoritative confirmation, and repair; it adds no package. API/MCP and live - host interfaces remain later tasks; do not create their packages early. + authoritative confirmation, and repair; it adds no package. KB-04 adds the + optional `@pegma/knowledge-base-mcp` package for the shared five-operation + dispatcher, versioned HTTP contract, and MCP transport. Live host interfaces + remain host work; do not create later packages early. - Independent partial KB-05 source preparation adds local D1 conformance and a public synthetic composition. It does not complete KB-04 credentials or - the full KB-05 release/publication task. All three packages remain unpublished. + the full KB-05 release/publication task. KB-04 source is in progress; all four + packages remain unpublished at synchronized version `0.1.0`. - Never implement a database, authorization role model, identity/session/token system, audit log, request limiter, or durable scheduler here. Compose the corresponding Pegma package in the owning later task. @@ -44,7 +47,20 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. count, content, or citation. Whole source serialization uses the trusted local token counter; do not truncate article procedures into partial steps. - Base packages require no Support Desk, GitHub, model, framework, HTTP, or - provider SDK. Evidence is data; never execute code or fetch submitted URLs. + provider SDK. Only the optional MCP package depends on the official MCP SDK + and Zod. Evidence is data; never execute code or fetch submitted URLs. +- Initial agent access exposes exactly `getDraft`, `createDraft`, `updateDraft`, + `getValidationRequirements`, and `submitEvidence`. Reuse `knowledgePermissions` + draft-read/write/evidence-submit values as scopes; requirements need + `draftWrite` or `evidenceSubmit`, never `draftRead` or `validationManage` alone. + Agent credentials grant no staff/Admin role, collection/evidence/provenance + reads, review, publication, policy administration, or grant management. +- The host composes Agent Access with its existing human login and current + Admin-only consent. Device linking uses RFC 8628; authorization-code linking + requires S256 PKCE. Initial authoring consent is app-instance-wide; + collection-specific delegation is a future host seam. New capabilities need + explicit scope registration, policy, and fresh consent. KB owns no credential + issuer, login, role model, or request limiter. - Constrain content and links; host renderers must disable executable content and raw HTML. Staff evidence/provenance never enters customer or bot DTOs. - Use fictional fixtures only. Commercial host internals, credentials, customer @@ -60,9 +76,11 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. ## Workflow Work on a `claude/*` branch and open a PR. Required checks are -`pnpm run format:check`, `pnpm run check`, `pnpm test`, `pnpm example`, and -`pnpm run release:check`, on Node 22 and 24. Run the applicable review/security -checks for the current head. Do not bypass pending, skipped, or failing gates. +`pnpm run format:check`, `pnpm run check`, `pnpm test`, `pnpm example`, +`pnpm run release:check`, and `pnpm run agent:proof`, on Node 22 and 24. +Require a clean current-head OpenRouter review with zero actionable findings +and the applicable current-head security checks. Do not bypass pending, +skipped, or failing gates. Repository development and the TypeScript example require Node 22.6.0+ or 24. The root engine floor covers the example's `--experimental-strip-types` flag; published package engines remain `>=22`, and CI tracks current Node 22/24. @@ -71,6 +89,12 @@ Each published package needs its own README and MIT LICENSE, a build-on-prepack script, and compiled-test exclusion. Merging source does not publish packages. See [release operations](docs/RELEASING.md); first publication and external trusted-publisher configuration are separate maintainer operations. +The protocol proof may build the reviewed, pinned public AUTH-01 source in an +isolated temporary consumer with all four KB tarballs and the official SDK. +That test-only exception never authorizes an unpublished production dependency. +Agent Access publication and KB-05 publication both precede real host assembly. +Keep actual existing-login/Admin-consent and every requested client/mode proof +open in P-00 and PG-01/RG-01 until both hosts record them before activation. ## Reading order @@ -82,5 +106,8 @@ durable operations and [host composition](docs/HOST_COMPOSITION.md) before changing authorization, verifier, replay, or DTO boundaries. For KB-03, read [retrieval](docs/RETRIEVAL.md) and the declared projection layout before changing query work, citations, or repair. +For KB-04, read the [agent API](docs/AGENT_API.md) and +[agent workflow](docs/AGENT_WORKFLOW.md) before changing transport, credential, +client, or evidence-proof boundaries. For partial KB-05, read [source preparation](docs/SOURCE_PREPARATION.md) before changing local D1 fixtures, synthetic composition, or release-readiness claims. diff --git a/README.md b/README.md index 7a0868e..b10160b 100644 --- a/README.md +++ b/README.md @@ -5,20 +5,22 @@ Hosts own their users, storage, authorization policy, interfaces, and deployment Knowledge Base owns collection policy, immutable article revisions, validation, and exact publication approval. It requires no GitHub connection or AI provider. -> Development status: KB-01 provides contracts and pure domain transitions; -> KB-02 adds authorized application/persistence source, and KB-03 extends that -> application with bounded retrieval and repair. Implementation and repository -> gates determine source evidence. Independent partial KB-05 preparation adds -> local D1 conformance and a public synthetic example. KB-04 credentials and the -> full KB-05 release task remain unfinished. All three packages are unpublished -> at `0.1.0`. API/MCP and live customer/staff interfaces remain later tasks. This -> repository is not yet an operational hosted KB or a production dependency. +> Development status: KB-01 through KB-03 provide contracts, pure domain +> transitions, authorized application/persistence, and bounded retrieval/repair. +> Independent partial KB-05 preparation adds local D1 conformance and a public +> synthetic example. KB-04 source work adds the optional five-operation HTTP/MCP +> adapter and authenticated protocol proof; it is in progress until current-head +> gates and review pass. All four packages are unpublished at `0.1.0`. +> KB-05 publication and actual two-host existing-login/client acceptance remain +> separate gates. This repository is not an operational hosted KB or a +> production dependency. | Package | Scope | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | [`@pegma/knowledge-base-contracts`](packages/contracts/README.md) | Collection, article, evidence, and approval vocabulary | | [`@pegma/knowledge-base-core`](packages/core/README.md) | Pure validation and lifecycle transitions | | [`@pegma/knowledge-base-application`](packages/application/README.md) | Authorized services, bounded persistence/retrieval, private DTOs, and exact publication | +| [`@pegma/knowledge-base-mcp`](packages/mcp/README.md) | Optional bounded agent dispatcher, versioned HTTP API, and MCP adapter | Collections default to private and independently specify portal and bot-answer audiences. Articles inherit collection policy. Staff approval binds the exact @@ -26,14 +28,28 @@ revision, content, collection policy, applicability, validation requirements, and evidence. A revised guide requires fresh review; prior publication never authorizes edited content. -Core transitions accept explicit inputs and return new values. They do not -authenticate a runner or staff member, enforce host roles, fetch evidence URLs, -or execute guide steps. The application enforces current named permissions -and resource checks; hosts authenticate scoped access contexts and trusted -evidence/source facts. Private draft, evidence, provenance, and review reads -have separate DTOs. The keyed published read returns portal-safe content only. -Local agents will test guides against authorized staging and submit evidence -through the later API/MCP adapter. +Core transitions accept explicit inputs and return new values. The application +enforces current named permissions and resource checks; hosts authenticate +access contexts and evidence/source facts. Private draft, evidence, provenance, +and review reads have separate DTOs. The keyed published read returns +portal-safe content only. The three base packages remain independent of HTTP, +MCP, and provider SDKs. + +The optional adapter exposes exactly `getDraft`, `createDraft`, `updateDraft`, +`getValidationRequirements`, and `submitEvidence` over the same application. +Its scopes reuse `knowledgePermissions.draftRead`, `draftWrite`, and +`evidenceSubmit`; validation requirements need write or evidence-submit +authority. Agents receive no Admin/staff role, collection or evidence reads, +private provenance, review, publication, policy, or grant-management operations. +Read the [agent API](docs/AGENT_API.md) for the exact contract and +[agent workflow](docs/AGENT_WORKFLOW.md) for linking and draft/test/evidence use. + +Hosts compose the separate [Agent Access](https://github.com/pegma-dev/agent-access) +producer with their existing human login and current Admin consent. AUTH-01's +[merged source](https://github.com/pegma-dev/agent-access/pull/1) supplies the +source prerequisite; publication remains separate. Initial authoring grants are +app-instance-wide. Collection-specific delegation is a future host seam. +The KB does not issue credentials or implement login, roles, or a limiter. KB-02 stores normalized heads and bounded immutable history with same-partition CAS, Audit, replay receipts, and causal jobs. Application generation is separate @@ -54,9 +70,12 @@ physical work/source budgets, whole-article token accounting, and repair. Partial [source preparation](docs/SOURCE_PREPARATION.md) runs shared public KB conformance against memory, local Azurite, and real local Miniflare D1 through the released D1 adapter. The [synthetic composition](examples/composition/README.md) -demonstrates the public author/test/review/publish/retrieve flow with fictional -trust inputs. Local emulators and that example establish neither live Workers -deployment nor scoped API/MCP credentials, publication, or host acceptance. +demonstrates author/test/review/publish/retrieve with fictional trust inputs. +The separate `agent:proof` gate composes reviewed pinned AUTH-01 source and all +four packed KB artifacts in a temporary consumer with the official MCP SDK +`1.32.2`, exercising OAuth, the five tools, evidence binding, and HTTP/MCP parity. +Current-head results establish execution; these proofs establish neither actual +requested-client compatibility nor either real host's login/staging acceptance. Develop on Node 22.6.0+ or 24 with pnpm 10.34.5: @@ -67,25 +86,33 @@ pnpm run check pnpm test pnpm example pnpm run release:check +pnpm run agent:proof ``` -The npm and pnpm workspace declarations deliberately name the same source +The npm and pnpm workspace declarations deliberately name the same four source packages: pnpm links them for development, while npm supplies artifact packing. -The release check installs all three tarballs in a consumer outside either workspace -to verify dependency resolution without source links. +The release check installs all four tarballs in a consumer outside either +workspace to verify dependency resolution without source links. The Agent +Access source fixture is confined to the temporary protocol-proof consumer; +production hosts must consume exact published Agent Access and KB versions. Frozen installation permits the pinned native `workerd` install script only; test workers/timeouts and per-factory D1 disposal remain bounded. The [approved enhancement plan](https://github.com/pegma-dev/support-desk/blob/main/docs/KNOWLEDGE_AI_PLAN.md) defines KB-01 through KB-05 and the later Support Desk/host integrations. Its [P-00 handoff](https://github.com/pegma-dev/support-desk/pull/33) records -source/registry baselines, synthetic acceptance cases, and open activation -prerequisites. These two launch hosts use separate stores and policies; the -packages do not introduce a shared tenant control plane. +frozen baselines and activation prerequisites; the +[source/publication clarification](https://github.com/pegma-dev/support-desk/pull/36) +retains actual two-host acceptance in PG-01/RG-01 before activation and pilots. +Codex, Claude Code, Grok Bot's desktop hosted agent, and T3 Code's Codex-provider +mode each need real recorded runs on both hosts. SDK proof cannot close those +gates. The two hosts keep separate stores and policies without a shared control +plane. Read [AGENTS.md](AGENTS.md) before changing code and [release operations](docs/RELEASING.md) before preparing artifacts. Merging -source does not publish a package. Each new npm name needs the maintainer's -first publication and trusted-publisher setup before hosts can consume it. +source does not publish a package. Each of the four npm names needs the +maintainer's first publication and its own trusted-publisher setup before host +consumption; Agent Access follows its separate release process. Built in the open by RetireGolden, LLC. diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md new file mode 100644 index 0000000..acdb4b0 --- /dev/null +++ b/docs/AGENT_API.md @@ -0,0 +1,213 @@ +# Version 1 agent authoring boundary + +`@pegma/knowledge-base-mcp` supplies a shared dispatcher, strict Zod schemas, +an MCP adapter, and a Web Request/Response adapter. Both transports invoke the +existing `KnowledgeBaseApplication`; neither introduces +an authorization engine or another article lifecycle. These source packages are +unpublished. Passing synthetic transport tests does not establish live OAuth, +protected staging execution, publication, or host readiness. + +## Trusted host composition + +Create `createKnowledgeAgentDispatcher({ application, resource, limits? })` once. +For every call and retry the host must authenticate the credential, validate its +exact audience/resource and client, and resolve current authorization. Supply +`{ access, scopes, clientId, resource }` as a trusted `KnowledgeAgentIdentity`, +separately from the request body. The configured and authenticated `resource` +strings must match exactly. The KB is a resource server: it does not issue +credentials, implement login, store tokens, create roles, or implement a limiter. + +`knowledgeAgentScopes` reuses three existing named permissions: + +| Scope member | Exact scope and permission | +| ---------------- | ----------------------------------- | +| `draftRead` | `knowledge.article.draft.read` | +| `draftWrite` | `knowledge.article.draft.write` | +| `evidenceSubmit` | `knowledge.article.evidence.submit` | + +Register each scope with the host's existing agent-access registry, mapping it +to the same named KB permission. The transport has no runtime dependency on +Agent Access. A host may compose that package after its public release, using +its normal authenticated resolver; copied source, branch references, and local +paths are not production substitutes for a released package. + +The dispatcher intersects those three known scope strings with the supplied +current `access.permissions`. Unknown scopes grant nothing. It drops roles, +entitlements, and every other permission before invoking the application, even +when the authenticated host context contains administration or publication +authority. Collection/resource checks and command replay authorization remain +the application's responsibility. The host owns current-access freshness, +credential revocation, request timeouts, and external request limits. +Trusted scope/permission arrays have a separate 256-item ceiling, independent +of the client payload's 32-item array ceiling. A broader current host context +is attenuated to the same three permissions rather than copied into the +application call. Authority is read through own data properties; getters, +sparse arrays, symbols, and custom array prototypes do not establish grants. + +## Exact initial operation set + +Each envelope is `{ apiVersion: "1", operation, input }`. All input objects, +including nested draft/evidence objects, reject unknown fields. + +| Operation | MCP tool | Required effective permission | +| --------------------------- | ------------------------------------------ | -------------------------------- | +| `getDraft` | `knowledge_v1_get_draft` | `draftRead` | +| `createDraft` | `knowledge_v1_create_draft` | `draftWrite` | +| `updateDraft` | `knowledge_v1_update_draft` | `draftWrite` | +| `getValidationRequirements` | `knowledge_v1_get_validation_requirements` | `draftWrite` or `evidenceSubmit` | +| `submitEvidence` | `knowledge_v1_submit_evidence` | `evidenceSubmit` | + +Draft-read or validation-management authority alone does not grant author +validation requirements. There are no collection, private-evidence read, +provenance, review, publication, retirement, retrieval, or administration tools +in this initial transport surface. + +Inputs mirror the public application contracts: + +- `getDraft`: `{ articleId }`. +- `getValidationRequirements`: `{ collectionId, kind }`. +- `createDraft` and `updateDraft`: `{ commandId, correlationId, +expectedGeneration, articleId, collectionId, draft }`. Creates require + `expectedGeneration: 0`. A draft contains `kind`, `title`, `summary`, + `content: { format, text }`, `tags`, and `applicability: { productId, +productVersion, buildId?, locale? }`. +- `submitEvidence`: `{ commandId, correlationId, expectedGeneration, +articleId, evidence, receipt }`. Evidence contains `id`, `articleId`, + `articleRevision`, `contentHash`, `validationPolicy: { id, version }`, + `checkId`, `testKind`, `applicability`, `stagingBuildId`, `steps`, `result`, + `executedAt`, `runnerId`, and `artifacts: [{ id, hash }]`. The opaque receipt + is nonempty and at most 8,192 UTF-8 bytes. + +Caller-supplied context, scopes, principal, proof, evidence version/hash, or +attestation fields are rejected. Evidence's revision/content hash, policy +reference, artifact hashes, runner, execution time, and claimed result are +submission data required by the public contract. They do not authenticate +anything. The existing trusted evidence verifier must authenticate and bind the +opaque receipt; missing verification fails closed. The transport fetches no +artifact URL and executes no guide step. + +## HTTP composition + +`createKnowledgeAgentHttp({ dispatcher, apiUrl, resource, +protectedResourceMetadataUrl, allowedOrigins, authenticate, limit })` returns +`{ handle(request) }`. `handle` returns `null` for unmatched paths so the host's +router can continue. The API endpoint uses an exact canonical HTTPS `apiUrl`; +its authenticated protected resource remains the configured canonical MCP +resource URL. A matching path with a different URL authority, `Host`, or query +is rejected. Explicit `allowInsecureLoopback` is available only for local +synthetic proof. + +The trusted host `authenticate(request)` port returns a +`KnowledgeAgentIdentity` or a denial `Response`. It must validate issuer, +client, resource, expiry, credential revocation, and current principal access. +The adapter requires Bearer authorization, normalizes authentication failures, +and discards arbitrary host denial bodies and headers. Missing or invalid +credentials receive the protected-resource metadata challenge; infrastructure +failures remain unavailable. + +`limit(request, { transport })` supplies the host's existing request-admission +decision before authentication and body processing. It returns a boolean or +`{ allowed, retryAfterSeconds? }`; denial is 429 and an exception is 503. The +adapter implements no limiter storage or policy. + +Authenticated requests use POST with JSON and strict UTF-8. Stream work is +bounded to 1,024 chunks and the configured request-byte allowance, with oversized +streams cancelled. An `Origin`, when present, must exactly match an allowed +origin; native clients may omit it. Responses use `no-store`, `nosniff`, and +`no-referrer`, with CORS limited to the exact admitted origin and no credentialed +cookie mode. Hosts own cross-origin preflight routing when required; this +adapter accepts POST only. Authentication and protocol failures may use their +standard transport error shape before an application envelope is dispatched. + +## MCP composition + +`createKnowledgeAgentMcp({ dispatcher, mcpUrl, resource, +protectedResourceMetadataUrl, allowedOrigins, authenticate, limit })` returns +the same `{ handle(request) }` router interface. `mcpUrl` must exactly equal +`resource`. It uses the HTTP adapter's trusted authentication/admission ports, +URL/Host/Origin rules, protected-resource challenge, strict UTF-8 reader, and +response protections. Metadata is host-owned and is never served by this +package. Configure the same resource on the dispatcher and both transports. + +The adapter uses pinned MCP SDK `1.32.2` and Zod `4.6.7`. Each admitted POST +gets a fresh stateless SDK server and Streamable HTTP transport. It caches no +identity or protocol session: every initialize, tool listing, tool call, and +notification must pass current host admission and authentication. Only tools +are advertised, using the five names above with useful strict input JSON +schemas. Client metadata and capability objects are bounded and validated +before reaching the SDK; they grant no server authority. + +Responses use JSON rather than an SSE stream. Authenticated GET and DELETE +receive 405; an accepted initialized notification receives 202. The pinned +SDK negotiates the protocol version. Tool calls use the shared dispatcher; +one text content block contains the exact versioned response JSON, with +`isError` set for application failure. There is no parallel `structuredContent` +representation. The logical application result retains the same complete +response-byte budget; MCP's JSON string escaping/framing is separately capped +at twice that allowance plus 4,096 bytes. No transport executes article steps, +fetches evidence, or acquires review/publication authority. + +## Results and safe failures + +Success is `{ apiVersion: "1", operation, result }`. Draft reads expose the +application's author-facing `DraftArticleDto`, including revision `createdBy` +and `createdAt`, plus bounded state flags. They exclude evidence, provenance, +review records, and attestation artifacts. Validation requirements expose only +collection/governance generation, policy reference, expected staging build, +and current checks; trusted runner/attester registries remain private. +Mutations return the existing `{ value, replayed }` acknowledgement with +ID/generation, content revision, state, and content hash. Output schemas +explicitly whitelist these DTO fields. + +Failures are `{ apiVersion: "1", operation, error: { code, status, message } }`. +Invalid envelopes use `operation: null` rather than reflecting an arbitrary +caller-supplied operation. Messages are fixed and content-free: + +| Code | HTTP status | +| ----------------- | ----------- | +| `invalid_request` | 400 | +| `forbidden` | 403 | +| `not_found` | 404 | +| `conflict` | 409 | +| `capacity` | 413 | +| `prerequisite` | 412 | +| `unavailable` | 503 | + +Unknown exceptions become `unavailable`; no input, receipt, verifier message, +internal exception, stack, source reference, or proof artifact is serialized. +Hosts should log only safe operational identifiers and coarse categories. + +## Bounds and retry behavior + +Defaults bound request and response serialization to 131,072 UTF-8 bytes, +nesting to 12, graph work to 1,024 nodes, arrays to 32 items, and objects to +32 keys. The byte allowance covers the core's complete 32 KiB guide or sixteen +1,000-character evidence steps with UTF-8 expansion, metadata, opaque receipt, +and framing. Individual draft/evidence fields retain the core's ceilings. +These are component bounds, not host throughput promises. + +Optional limits may only reduce those ceilings; `maxResponseBytes` must remain +at least 2,048 bytes. This reserves a complete bounded mutation acknowledgement, +including a 200-character identifier at four UTF-8 bytes per character, two +maximum safe integers, a SHA-256 digest, and fixed versioned-envelope framing. +Smaller configurations fail before serving any operation, so a committed +command and its exact historical replay always fit the admitted byte allowance. +Oversized read results fail as a whole. Guides and procedures are never +truncated into incomplete steps. The shared JSON reader applies the complete +configured byte, depth, node, per-array item, and per-object key ceilings before +`JSON.parse`. Its bounded lexical scan respects quoted/escaped text and nested +containers; `JSON.parse` remains responsible for JSON syntax. Schemas and +parsing helpers remain internal; the public factories supply the shared +boundary. The dispatcher checks object graph bounds before Zod and detaches +and freezes input and effective authority before any application await. It +rejects getters, custom prototypes, symbols, cycles, and sparse arrays rather +than invoking coercion hooks. Zod validates transport shape; the application +still owns all semantic, lifecycle, proof, resource, and generation checks. + +For an uncertain command outcome, retry the same `commandId` and exact semantic +input, including the original `expectedGeneration`, with newly authenticated +current access. The transport forwards those fields unchanged. The application's +transactional receipt returns the original historical acknowledgement with +`replayed: true` and does not append duplicate history, Audit, or causal jobs. +Changed semantic input conflicts. A replay never restores revoked authority or +claims the acknowledged historical state remains current; read the draft anew. diff --git a/docs/AGENT_WORKFLOW.md b/docs/AGENT_WORKFLOW.md new file mode 100644 index 0000000..14a5142 --- /dev/null +++ b/docs/AGENT_WORKFLOW.md @@ -0,0 +1,149 @@ +# Agent authoring and test-evidence workflow + +KB-04 adds optional authoring transports over the existing Knowledge Base +application. Source work remains in progress until current-head gates and +review pass. All four KB packages are unpublished at `0.1.0`; this document +describes the composition and retained acceptance contract, not a live service +or a client-compatibility claim. The exact wire contract is in +[AGENT_API.md](AGENT_API.md). + +## Link through the host + +The host composes [Agent Access](https://github.com/pegma-dev/agent-access) with +its existing human login. A current Admin approves the registered client, +exact protected resource, and requested scopes. Device linking follows RFC +8628 with its human user code, polling interval, and `slow_down` handling. +Authorization-code linking requires S256 PKCE. The agent receives an opaque +machine credential rather than a browser cookie, password, or Admin role. +Only the host's current Admin browser authority can approve or manage grants. + +Before each request or replay, the host validates credential issuer, +resource/audience, client, expiry, revocation, current principal status, and +current permission authority. It supplies a trusted identity separately from +the untrusted input body. Missing or unavailable authority fails closed. The +transport uses that host authentication port and the same application services; +KB owns no credential issuer, login, roles, or limiter. + +Bind this bearer verifier to the KB resource routes. Do not add these credentials +to a generic account, staff, or browser-session authenticator; those endpoints +must reject agent credentials regardless of the approving administrator's ID. + +Initial consent covers authoring across the app instance. Existing collection +and resource checks still apply. Per-collection delegated grants remain a +future application/resource-authority seam and are not offered by this source. +A future capability needs +an explicitly registered scope, host policy, and fresh consent; changing a tool +list cannot silently widen a saved grant. + +## Use the five initial operations + +The three scope strings are the existing `knowledgePermissions` values: + +| Member | Exact scope | +| ---------------- | ----------------------------------- | +| `draftRead` | `knowledge.article.draft.read` | +| `draftWrite` | `knowledge.article.draft.write` | +| `evidenceSubmit` | `knowledge.article.evidence.submit` | + +The dispatcher intersects those known scopes with current authority and removes +roles, entitlements, and other permissions. HTTP and MCP expose the same five +operations, inputs, bounded DTOs, and application outcomes: + +| Operation | MCP tool | Required effective permission | +| --------------------------- | ------------------------------------------ | -------------------------------- | +| `getDraft` | `knowledge_v1_get_draft` | `draftRead` | +| `createDraft` | `knowledge_v1_create_draft` | `draftWrite` | +| `updateDraft` | `knowledge_v1_update_draft` | `draftWrite` | +| `getValidationRequirements` | `knowledge_v1_get_validation_requirements` | `draftWrite` or `evidenceSubmit` | +| `submitEvidence` | `knowledge_v1_submit_evidence` | `evidenceSubmit` | + +`draftRead` or `validationManage` alone cannot read author validation +requirements. There is no collection reading/listing, evidence reading, private +provenance, review submission/reading, publication/retirement, administration, +or grant-management tool. Agents cannot act as staff or Admin through this +surface. Hosts use their separately authorized staff services for review and +publication. + +## Prepare, test, and submit + +1. Obtain the target collection and article identity through the host's + authorized workflow. Read an existing draft when permitted, or create a new + one with `expectedGeneration: 0`. Mutations supply a stable `commandId` and + `correlationId`; updates use the exact current application generation. +2. Read validation requirements for the collection and article kind. The result + identifies current checks, policy reference, governance generation, and + expected staging build. It does not disclose private attester registries or + give policy-management authority. +3. Run the applicable checks against authorized staging for the exact draft + revision/content hash and product/build. Protect test artifacts through the + host's evidence channel. The KB transport executes no steps and fetches no + submitted artifact URL. +4. Submit evidence and the host's opaque receipt using the current generation. + The host attester must verify the authenticated actor and runner, exact + revision/content hash, check, staging build, result, and receipt before + returning trusted verification facts. An authenticated agent's own `passed` + string, runner ID, timestamps, or artifact hashes do not prove execution. +5. Read the draft again as needed. Evidence submission changes application + generation even when content revision stays unchanged. Editing content + changes the revision and invalidates older evidence/review authority. Staff + review and publication separately bind the exact current revision, audience, + policy, applicability, and verified evidence. + +For an uncertain mutation result, authenticate again and retry the same +`commandId` and exact semantic input, including the original +`expectedGeneration`. An accepted replay returns its historical bounded +acknowledgement without duplicate history, Audit, or jobs. Changed input +conflicts; revoked authority remains denied. The acknowledgement is not a +claim that the historical state is still current. + +## Source proof and retained host acceptance + +[AUTH-01 PR #1](https://github.com/pegma-dev/agent-access/pull/1) merged the public +credential producer source. The KB `pnpm run agent:proof` gate pins reviewed +commit `a444e2113db98455b638b2ef8aa7c2faccb16b62`, builds it only in an isolated +temporary test consumer, and installs all four KB tarballs with the official +MCP SDK `1.32.2`. It exercises OAuth and real SDK protocol calls through the +five-operation loop, host-attested evidence, HTTP/MCP parity, and rejection +cases. The fictional human session, staging run, and attester remain test +inputs. Current-head gate output establishes execution; this document records +no pass verdict. + +KB-04 source exit requires format, type, tests, synthetic example, artifact +checks, and `agent:proof` on Node 22 and 24, plus a clean current-head OpenRouter +review with zero actionable findings and the applicable security checks. It +closes only the source slice. KB-05 owns reviewed publication of the four KB +packages; Agent Access follows its separate first-publication and +trusted-publisher process. Both public releases precede production host +assembly. Branches, copied source, local paths, and unpublished production +tarballs cannot substitute for them. + +The [approved source/publication split](https://github.com/pegma-dev/support-desk/pull/36) +retains actual acceptance in P-00 and PG-01/RG-01. The initial compatibility +targets all remain unproven until actual results are recorded on both hosts: + +| Client | Initial target mode | Actual two-host proof | +| ----------- | ----------------------------------------------------------------- | --------------------- | +| Codex | Actual supported client and host credential flow | Pending | +| Claude Code | Actual supported client and host credential flow | Pending | +| Grok Bot | Desktop application with hosted agent; Grok Build CLI is excluded | Pending | +| T3 Code | Codex-provider mode; other providers remain unproven | Pending | + +For every target client/mode on each host, record discovery, existing human +login/current-Admin consent, draft read/create/update, requirements, verified +evidence submission, and matching HTTP/MCP outcomes using exact released +dependencies. Record unsupported or unavailable flows as open gaps. + +Retain explicit expiry, wrong-audience, revocation, excess-scope, current +principal/permission-change, and wrong revision/build/runner or stale-evidence +rejections. Prove initial agent credentials cannot publish, submit/read +reviews, act as staff/Admin, manage collections or validation policy, read +collections/evidence/private provenance, or link/manage grants. Test the exact +requirements permission alternatives, including denial with only `draftRead` +or only `validationManage`. + +PG-01 uses the real D1 host composition; RG-01 uses the real Azure Tables host +composition. Keep host-specific routes, credentials, configuration, customer +content, and operational evidence in their owning private systems. Actual +client runs, staff review/publication, privacy, isolation, bounded work, and +full human-workflow acceptance remain prerequisites before activation, A-01, +and either supervised pilot. Synthetic SDK success waives none of them. diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index af20268..60d6655 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -2,11 +2,13 @@ ## Status and ownership -This documents the agreed KB-02/KB-03 source API and host boundary. Implementation -and repository gates determine task completion; this document does not assert -that either real host is ready. The unpublished application composes -contracts/core with host-supplied Storage Core and Authorization Core. It is -not an HTTP server, an identity system, or an operational MCP endpoint. +This documents the KB-02/KB-03 application and KB-04 transport host boundaries. +KB-04 source is in progress until current-head gates and review pass; neither +real host is ready on that evidence alone. The unpublished application composes +contracts/core with host-supplied Storage Core and Authorization Core. The +optional `@pegma/knowledge-base-mcp` package supplies bounded HTTP/MCP adapters +over that application. All four KB packages are unpublished at `0.1.0`. +No package becomes an identity system or an operational hosted endpoint. See [declared collections](COLLECTIONS.md) for the required layout, CAS, admission, and replay design. @@ -18,7 +20,12 @@ fixture passes a real Miniflare binding directly to the released It is local consumer evidence, not a deployed Workers binding or production acceptance. The example's resolved contexts and receipt registry stand in for trusted host facts; they authenticate no real browser, agent, or staging run. -KB-04's credential/client flow and full KB-05 publication remain unfinished. +AUTH-01's [merged public source](https://github.com/pegma-dev/agent-access/pull/1) +provides KB-04's credential producer prerequisite. The separate `agent:proof` +gate uses that reviewed pinned source only in a temporary consumer with the +four KB tarballs and official SDK `1.32.2`. It tests the synthetic OAuth and +draft/evidence transport loop. Actual existing-login/client acceptance on both +hosts, Agent Access publication, and full KB-05 publication remain separate. The host owns identity verification, scoped local-agent credentials, current authorization resolution, browser/transport protections, store construction, @@ -43,14 +50,36 @@ the host's identity or policy system during an in-flight call. Resolve access anew for each call/replay and bound operation duration and authority freshness to the host's required revocation behavior. -API/MCP author credentials initially permit draft authoring and evidence -submission. They do not acquire review/publication or collection-management -authority by declaring a runner, reviewer, attester, or permission string. -Hosts map named KB permissions into existing policy and role administration; -the KB does not issue credentials, create roles, parse cookies, or implement -OAuth. Existing public catalog MCP connectivity is not private authoring -authentication. The live credential/protected-resource proofs remain -KB-04/host activation prerequisites. +Compose Agent Access through the adapter's host authentication port. It owns +credential issuance, expiry, refresh, replay handling, and revocation; the KB +transport consumes its authenticated restricted identity. The host validates +issuer, exact protected resource/audience, registered client, and current +principal/permission authority for each call. It also owns protected-resource +discovery, browser-route protections, origin/CORS configuration, and durable +request admission through its existing limiter. Public catalog MCP connectivity +does not authenticate private authoring. + +Linking uses the host's existing human login and current Admin-only consent. +The device flow follows RFC 8628, including user code, polling interval, and +`slow_down`; the authorization-code flow requires S256 PKCE. Agents receive +neither a browser session nor the consenting Admin's role. A bearer cannot +link, approve, or manage grants. Initial consent is app-instance-wide authoring; +per-collection delegated consent remains a future host seam, while current KB +collection/resource checks continue to apply. + +Register only `knowledge.article.draft.read`, `knowledge.article.draft.write`, +and `knowledge.article.evidence.submit`, using the existing `knowledgePermissions` +values. The dispatcher intersects consented known scopes with current permission +authority and strips roles, entitlements, and other permissions. It exposes +exactly `getDraft`, `createDraft`, `updateDraft`, `getValidationRequirements`, +and `submitEvidence`. Validation requirements need `draftWrite` or +`evidenceSubmit`; `draftRead` or `validationManage` alone is insufficient. +There are no collection/evidence/provenance reads, review/publication, +administration, or grant-management tools. New capabilities require explicit +scope registration, host policy, and fresh consent; adding a tool never silently +widens an existing grant. The KB does not issue credentials, create roles, +parse login cookies, implement OAuth, or supply a request limiter. +See the [agent API](AGENT_API.md) and [agent workflow](AGENT_WORKFLOW.md). For each operation, check its named permission and current resource scope. An article's collection is authoritative data loaded by the application, not @@ -300,7 +329,14 @@ Hosts remain responsible for authorized evidence downloads, retention/deletion, backup/recovery, blob orphan cleanup, safe Markdown/plain-text rendering, rate limits, and worker scheduling/checkpoints. Signed-in web/API integration and a supervised deployment require their own task evidence. Passing local -application tests does not establish MCP authentication, -provider ZDR configuration, either real host, or production readiness. +application tests does not establish live MCP authentication, +provider ZDR configuration, either real host, or production readiness. The +synthetic actual-SDK proof closes only its source protocol evidence when gates +pass. PG-01/RG-01 must consume exact published Agent Access and KB dependencies, +then record existing-login/current-Admin consent and every requested client/mode +against each host's real staging evidence attester before activation. Keep this +acceptance open in P-00 and the parent plan; source proof does not waive staff +review/publication, privacy, isolation, bounded work, or full human-workflow +acceptance before A-01 and either pilot. Built in the open by RetireGolden, LLC. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index e347790..bf2af65 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -2,17 +2,27 @@ ## Source status -`@pegma/knowledge-base-contracts`, `@pegma/knowledge-base-core`, and -`@pegma/knowledge-base-application` are prepared at synchronized source version -`0.1.0`. All three package names are unpublished. KB-01 through KB-03 establish -domain, authorized application, and bounded retrieval source plus packaging -checks; their repository gates determine task completion. They do not publish, create tags/releases, -configure credentials, or enable a publish workflow. +`@pegma/knowledge-base-contracts`, `@pegma/knowledge-base-core`, +`@pegma/knowledge-base-application`, and `@pegma/knowledge-base-mcp` use +synchronized source version `0.1.0`. All four package names are unpublished. +KB-01 through KB-03 establish domain, authorized application, and bounded +retrieval source. KB-04 adds the optional five-operation HTTP/MCP adapter and +authenticated source protocol proof; this work remains in progress until its +current-head gates and review pass. Source changes do not publish, create +tags/releases, configure production credentials, or enable a publish workflow. Independent partial KB-05 [source preparation](SOURCE_PREPARATION.md) adds the local Miniflare D1 consumer fixture, shared three-backend conformance, and a -public synthetic example. This is not completion of KB-04 or full KB-05. No -package is added or published; all three remain unpublished at `0.1.0`. +public synthetic example. That earlier slice added no package. KB-04 now adds +the fourth package; full KB-05 publication remains pending. + +[AUTH-01 merged source](https://github.com/pegma-dev/agent-access/pull/1) is the +KB-04 source prerequisite. `agent:proof` builds its reviewed public commit +`a444e2113db98455b638b2ef8aa7c2faccb16b62` only in an isolated temporary +consumer with all four KB tarballs and official MCP SDK `1.32.2`. This proves +source protocol behavior when its current-head gate passes, without publishing +Agent Access. Its first publication and trusted-publisher setup belong to its +own release process, not this repository's four-package release. Hosts must wait for an exact public registry release. Git branches, copied source, local paths, and unpublished production tarballs are not substitutes. @@ -31,9 +41,10 @@ pnpm run check pnpm test pnpm example pnpm run release:check +pnpm run agent:proof ``` -`release:check` packs contracts, core, then application using npm. Each package's +`release:check` packs contracts, core, application, then MCP using npm. Each package's `prepack` builds its own output, so a package cannot silently ship a stale distribution. The checker verifies: @@ -45,8 +56,9 @@ distribution. The checker verifies: and JavaScript/declaration output and maps under `dist`, with compiled tests excluded and both entry-point files present; - the actual tarball bytes against npm's reported SHA-1 and SHA-512 integrity; -- an isolated consumer installation of all three tarballs and successful ESM - imports of all three public packages. +- an isolated consumer installation of all four tarballs and successful ESM + imports of all four public packages, including the optional adapter's SDK + dependency resolution. The consumer disables install scripts, audit, and funding requests and obtains released external dependencies from the public npm registry. It has no workspace @@ -63,12 +75,21 @@ pnpm run release:pack ``` This runs the same checks, then writes a new `.release/knowledge-base-*` -directory containing the three tarballs and `manifest.json` with their inventory +directory containing the four tarballs and `manifest.json` with their inventory and integrity values. Existing artifact directories are preserved. These files are local preparation artifacts, not proof of a released version or provenance. The checker does not verify a source tag, main ancestry, registry publication, or trusted-publisher configuration. Those are release prerequisites below. +`agent:proof` is a separate gate from artifact inventory/import checks. It uses +the real Agent Access implementation and official SDK against a test-only +synthetic composition for OAuth, the five draft/evidence operations, HTTP/MCP +parity, and rejected credential/evidence cases. It establishes neither actual +requested-client compatibility nor real existing-login/host staging acceptance. +Both source gates and the synthetic composition run on Node 22 and 24, with a +clean current-head OpenRouter review containing zero actionable findings and +the applicable security checks before source exit. + ## Maintainer prerequisites before first publication These operations remain pending and must be recorded when completed: @@ -76,12 +97,14 @@ Recheck npm's current [trusted-publishing guidance](https://docs.npmjs.com/trust when implementing the release workflow; this checklist records the Pegma release procedure, not proof that external publisher settings exist. -- [ ] Confirm package-name ownership and organization publishing permissions. +- [ ] Confirm ownership and organization publishing permissions for all four + package names. - [ ] Complete KB-05's advertised package/adapter and dual-store release criteria. Partial source preparation supplies a real local D1 consumer - fixture and synthetic composition subject to current-head gates. It does - not establish KB-04's authenticated real-client flow, live Workers/host - acceptance, or complete package/bootstrap/publication readiness. + fixture and synthetic composition subject to current-head gates. KB-04 + must close its separate source exit with actual-SDK synthetic transport + proof. Actual requested-client/existing-login/host acceptance remains a + later PG-01/RG-01 activation gate; no source run can close it. Do not publish empty packages. - [ ] Merge reviewed release source and exact version/pin changes to protected `origin/main`; require every current-head review, test, build, security, @@ -89,11 +112,12 @@ release procedure, not proof that external publisher settings exist. - [ ] Configure protection for immutable `v*` tags and approved release signers. - [ ] Prepare and verify the exact artifacts from a protected signed annotated `vX.Y.Z` tag whose commit is already on `origin/main`. -- [ ] The maintainer performs the new package names' one-time manual 2FA - publication of those exact verified tarballs. Choose and document the +- [ ] The maintainer performs each of the four new package names' one-time + manual 2FA publication of those exact verified tarballs. Choose and document the bootstrap/first advertised release procedure before this operation. -- [ ] Configure npm trusted publishers for this repository, the reviewed future - publish workflow, and its protected publishing environment. +- [ ] Separately configure an npm trusted publisher for each of the four package + names, this repository's reviewed future publish workflow, and its + protected publishing environment. - [ ] Establish the future workflow: unprivileged signature/main/gate/pack preparation, followed by a minimal environment-approved OIDC publish job receiving only the exact prepared artifacts. @@ -107,3 +131,11 @@ annotated tag and trusted-publisher path, preserve published version immutabilit and recover partial publication by verifying identical existing artifacts rather than overwriting a version. Define that workflow in the release task before enabling publication. + +Before real host assembly, verify both the exact KB release set and the +separately published Agent Access dependency. Preserve P-00 and PG-01/RG-01's +actual existing-login/current-Admin consent, every requested client/mode, +host-attested staging evidence, and failure-case acceptance until both hosts +record it. Those gates, staff review/publication, privacy, isolation, bounded +work, and full human workflows remain required before activation, A-01, and +either supervised pilot. No release artifact alone proves host readiness. diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index e8dac88..244d153 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -5,15 +5,17 @@ This is an independent, partial KB-05 source-preparation slice. It adds a real local D1 consumer fixture and a public synthetic composition example over the existing contracts/core/application packages. It does not finish KB-04 or the -full KB-05 release task. All three KB packages remain unpublished at source -version `0.1.0`. +full KB-05 release task. KB-04 now adds the optional HTTP/MCP package and its +separate authenticated protocol proof; that source work is in progress until +current-head gates and review pass. All four KB packages remain unpublished at +synchronized source version `0.1.0`. | Evidence area | This source slice | Separate remaining proof | | ---------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | | Storage consumer | Shared public KB suites on memory, local Azurite, and local Miniflare D1 | Production Azure/Workers configuration, operations, and host acceptance | -| Composition | Runnable fictional author/evidence/review/publication/retrieval flow | Real host identity, staging verification, scoped API/MCP credentials, and UI | -| Artifacts | Existing three-package pack/import checks | First publication, trusted-publisher setup, registry integrity/provenance, and released consumers | -| Task readiness | Current-head repository gates establish this slice's evidence | KB-04 credential/client proof and all remaining KB-05 exit criteria | +| Composition | Runnable fictional author/evidence/review/publication/retrieval flow | Real host identity, staging verification, existing-login/client acceptance, and UI | +| Artifacts | Four-package pack/import checks, extended by KB-04 | First publication, trusted-publisher setup, registry integrity/provenance, and released consumers | +| Task readiness | Current-head repository gates establish this slice's evidence | KB-04 source exit, actual two-host/client acceptance, and remaining KB-05 exit criteria | No test counts or pass verdicts are implied by this document. Record verified current-head gate results before treating the source slice as validated. @@ -102,11 +104,13 @@ pnpm run check pnpm test pnpm example pnpm run release:check +pnpm run agent:proof ``` -The CI workflow runs those checks, including the synthetic example, on Node -22 and 24. A local run does not substitute for required current-head CI or -reviews. Adapter conformance also does not certify production throughput, +The CI workflow runs those checks, including the synthetic example and KB-04's +separate protocol proof, on Node 22 and 24. A local run does not substitute for +required current-head CI, a clean OpenRouter review with zero actionable +findings, or applicable security checks. Adapter conformance does not certify production throughput, retention, backups, network protections, or distributed deployment behavior. ## Public synthetic composition @@ -138,17 +142,39 @@ evidence, author publication authority, private-data exclusion, bot-only citations, and retirement with old projection hints. Current-head gate results remain the evidence of execution. +## Separate authenticated transport proof + +The partial KB-05 composition above still uses synthetic resolved contexts. +KB-04's `pnpm run agent:proof` separately composes the real +[AUTH-01 source](https://github.com/pegma-dev/agent-access/pull/1), pinned to +reviewed public commit `a444e2113db98455b638b2ef8aa7c2faccb16b62`, with all four +KB tarballs and official MCP SDK `1.32.2` in an isolated temporary consumer. +The pinned source build is test-only. It does not become an unpublished +production dependency or authorize host installation. + +That gate exercises OAuth and the exact five-tool draft/read/write/requirements/ +evidence flow, shared HTTP/MCP behavior, and rejection cases. The evidence +attester must bind the authenticated actor and runner to the exact article +revision/content hash, staging build, execution result, and opaque receipt; +an authenticated agent's claimed `passed` result remains untrusted data. +Current-head results establish execution; this document claims no passing run. +See [agent workflow](AGENT_WORKFLOW.md) for the retained source and host gates. + ## Remaining gates -KB-04 must still establish the real scoped/revocable/audience-bound author -credential and protected-resource/client flow. Manually supplied fixture -contexts do not close that prerequisite. The optional API/MCP contract and -real local-client author/test/evidence loop require their own task evidence. +KB-04's source exit needs its implementation, Node 22/24 gates, clean review, +and security checks. Actual clients and two-host authentication/staging +acceptance remain open in P-00 and PG-01/RG-01. Every requested client/mode must +record discovery, existing-login/current-Admin consent, the five operations, +and credential/evidence failures on each host using published dependencies. +Synthetic source/SDK success cannot close those activation prerequisites. The full KB-05 release candidate still needs its advertised package/adapter and client criteria, reviewed bootstrap/trusted-publisher configuration, exact registry publication, artifact/provenance verification, and released consumer -checks. See [release operations](RELEASING.md). No empty adapter package, -release tag, publication, or host activation is created by this source slice. +checks. See [release operations](RELEASING.md). KB-04 implements the fourth +package rather than an empty adapter; neither source slice creates a release +tag, publication, or host activation. Agent Access has its own first-publication +and trusted-publisher prerequisites, also required before host assembly. Hosts must wait for exact released artifacts rather than adopting branches, copied source, local paths, or unpublished production tarballs. diff --git a/examples/agent/README.md b/examples/agent/README.md new file mode 100644 index 0000000..fca3484 --- /dev/null +++ b/examples/agent/README.md @@ -0,0 +1,128 @@ +# Packed local agent protocol proof + +Run `pnpm run agent:proof` from the repository after +`pnpm install --frozen-lockfile`, on Node 22.6+ or Node 24. Git and npm must be +available. The proof needs public GitHub and npm registry access and binds an +ephemeral listener to `127.0.0.1` only. Both component configurations explicitly +enable `allowInsecureLoopback` for this test. + +This is an independently reproducible, **test-only source composition**. It +exercises the actual MCP TypeScript SDK `1.32.2`, Sessions `0.2.0`, Authorization +Core `0.4.0`, Storage Core `0.4.0`, Agent Access and all four KB tarballs. It does +not establish any of the four target client applications, a deployed host, +real browser login, real staging execution, first publication, or host activation. +Those acceptance tasks remain open. + +## Artifact boundary + +The [orchestrator](../../scripts/agent-protocol-proof.mjs): + +1. Bootstraps exactly `pnpm@10.34.5` inside its bounded temporary directory. +2. Runs KB `release:check`, then packs contracts, core, application and MCP. +3. Clones the public + [Agent Access repository](https://github.com/pegma-dev/agent-access), checks out + the reviewed, publicly merged commit + [`a444e2113db98455b638b2ef8aa7c2faccb16b62`](https://github.com/pegma-dev/agent-access/commit/a444e2113db98455b638b2ef8aa7c2faccb16b62), + verifies its exact HEAD and declared package manager, installs its frozen + lockfile, builds, and packs its package. +4. Installs those five tarballs and the exact released SDK/Pegma dependencies + into a fresh npm consumer, with installation scripts disabled. +5. Copies only the [protocol fixture](../../scripts/agent-protocol-fixture.mjs) + into that consumer and executes it. Component code is loaded exclusively + through installed public package entrypoints. +6. Closes native client and server resources and removes the verified owned + temporary directory, including producer, toolchain, consumer and tarballs. + +Agent Access is currently unpublished. Its immutable producer is a dev fixture, +not a root dependency, runtime dependency, workspace package, copied auth source, +lockfile substitution, or production release substitute. The proof performs no +deployment, tagging, release creation or publication. It does not claim that +the producer's own review/validation gates were rerun; its immutable public merge +is the producer provenance boundary. + +For a preexisting local checkout, the optional `AGENT_ACCESS_SOURCE` environment +variable avoids a network clone. Its HEAD must equal that same exact reviewed +commit. The script clones its committed Git objects into the temporary directory; +it never installs, builds, checks out, or edits the supplied checkout, and never +consumes its uncommitted files. Omitting this variable uses the public repository. + +## Actual protocol and application path + +The fixture composes `createAgentAccess`, `createAgentAccessHttp` and +`createProtectedResourceAuthenticator` with released Sessions, Authorization Core +and Storage Core. The seeded fictional Admin browser session represents a login +already completed by a host. Cookie/session lookup, same-origin approval and a +per-session CSRF value guard approval; a desktop bearer cannot establish browser +identity. The required request-limiter port is explicitly an always-allow +synthetic input, with no distributed-limiting claim. + +The host registers a public client and the three exact `knowledgeAgentScopes` +values, mapping each scope to the same named KB permission. Every protected +request and command retry receives newly authenticated Agent Access authority: +`{ access, scopes, clientId, resource }`. No request body supplies access context. +Current Admin demotion invalidates active credentials at the real issuer. + +An actual SDK `Client` and `StreamableHTTPClientTransport`, using an +`OAuthClientProvider` for the pre-registered public client, perform: + +- An unauthenticated MCP initialization, protected-resource and issuer discovery, + S256 PKCE authorization, fictional browser consent, a loopback callback, and + authorization-code exchange using the saved SDK verifier. +- Initialization and `tools/list`, asserting exactly the five v1 tools and no + review, publication, provenance, private-evidence read or administration tools. +- Draft creation, authorized draft read, revision-creating update, validation + requirement read and exact-revision evidence submission through actual MCP. +- HTTP/MCP DTO parity and identical-command historical retry acknowledgements + across both transports. +- Wrong-resource token, expired credential, revoked credential and current + Admin-demotion rejection before either transport invokes the application, + including attempted command replays. A separate code exchange checks wrong + PKCE rejection. Actual SDK refresh rotates both access and refresh credentials. +- Separate HTTP device authorization, pending and slow-down responses, + browser-session consent, actual token redemption and protected KB read. + +The KB's actual application bootstraps a private collection, validation policy +and governance configuration. The synthetic runner independently recognizes the +exact known revision/build/procedure and executes a small fictional CSV export +check. Only that runner writes an opaque receipt registry. The verifier compares +the authenticated actor, trusted runner, build, complete article, complete +submission and authoritative governance against that registry before returning +an attestation. It rejects modified runner/build/result/steps/artifact claims; +it never authenticates evidence by echoing a caller's `passed` string. This +registry remains a fictional host trust input, not real staging-run evidence. + +Draft DTO checks exclude private evidence, attestation, provenance and review +records. No review or publication is performed. Guides and evidence content, +receipts, tokens, codes, verifiers, browser cookies and full authorization URLs +are never printed. + +## Safe result and failure diagnostics + +Success prints one JSON receipt containing only booleans and numeric counts, +including `packedPackages: 5`, `tools: 5`, `draftRevision: 2`, +`liveHostsProven: false` and `targetClientAppsProven: 0`. Native command output is +captured and suppressed. Failure prints only `passed: false` and a numeric +`stage`, plus a numeric `fixtureStage` when available: + +| Stage | Work | +| ------------- | ------------------------------------------------ | +| 1 | Isolated pinned pnpm bootstrap | +| 2 | KB release check and tarballs | +| 3 | Immutable Agent Access preparation | +| 4 | Clean consumer installation | +| 5 | Protocol fixture | +| Fixture 10–18 | Host/application bootstrap | +| Fixture 20 | SDK discovery, browser approval and exchange | +| Fixture 30 | Tools, drafts, retries and DTO parity | +| Fixture 40 | Validation requirements and receipt verification | +| Fixture 50 | Wrong resource and wrong PKCE | +| Fixture 60 | Expiry, refresh and revocation | +| Fixture 70 | Device authorization | +| Fixture 80 | Current Admin demotion | + +Bootstrap substages are application factory 11, collection 12, validation +policy 13, governance 14, session 15, listener 16, issuer 17 and adapters 18. + +The repository CI runs this same proof on Node 22 and Node 24. Real-host +activation and the four target-client compatibility records require separate +supervised evidence. diff --git a/package.json b/package.json index 7d529b0..7f515c7 100644 --- a/package.json +++ b/package.json @@ -20,15 +20,19 @@ "test": "pnpm run build && vitest run", "release:check": "node scripts/release-packages.mjs check", "release:pack": "node scripts/release-packages.mjs pack", - "example": "pnpm run build && node --experimental-strip-types examples/composition/run.ts" + "example": "pnpm run build && node --experimental-strip-types examples/composition/run.ts", + "agent:proof": "node scripts/agent-protocol-proof.mjs" }, "devDependencies": { "@azure/data-tables": "13.3.2", + "@cfworker/json-schema": "4.1.6", "@cloudflare/workers-types": "5.20260730.1", + "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", "@pegma/knowledge-base-application": "0.1.0", "@pegma/knowledge-base-contracts": "0.1.0", "@pegma/knowledge-base-core": "0.1.0", + "@pegma/knowledge-base-mcp": "0.1.0", "@pegma/spine": "0.1.2", "@pegma/storage-azure-tables": "0.4.0", "@pegma/storage-cloudflare-d1": "0.4.1", @@ -38,7 +42,8 @@ "miniflare": "4.20260730.0", "prettier": "3.9.10", "typescript": "7.0.2", - "vitest": "5.0.5" + "vitest": "5.0.5", + "zod": "4.6.7" }, "packageManager": "pnpm@10.34.5" } diff --git a/packages/application/README.md b/packages/application/README.md index dcd6ece..09b53cf 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -10,8 +10,9 @@ before durable operations. [Host composition](https://github.com/pegma-dev/knowl authentication, current-resource authorization, verified-evidence, and privacy boundaries. [Retrieval](https://github.com/pegma-dev/knowledge-base/blob/main/docs/RETRIEVAL.md) documents bounded lexical lookup, authoritative confirmation, citations, and -repair. API/MCP, real-host acceptance, and production activation remain later -tasks. +repair. The optional `@pegma/knowledge-base-mcp` package adds HTTP/MCP adapters +over this API; it supplies no login or token issuer. Real-host acceptance and +production activation remain separately gated. GitHub links in this unpublished README track development `main`; they are not frozen version documentation. KB-05 release preparation must pin those diff --git a/packages/mcp/LICENSE b/packages/mcp/LICENSE new file mode 100644 index 0000000..833a7d0 --- /dev/null +++ b/packages/mcp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Pegma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/mcp/README.md b/packages/mcp/README.md new file mode 100644 index 0000000..c8c5738 --- /dev/null +++ b/packages/mcp/README.md @@ -0,0 +1,82 @@ +# @pegma/knowledge-base-mcp + +Optional KB-04 agent transport source for Pegma Knowledge Base. This package +adapts the authorized application API to bounded agent commands and the Model +Context Protocol. It is unpublished at `0.1.0`; merging its source does not +publish it or establish a live hosted Knowledge Base. + +The contracts, core, and application packages remain independent of MCP, HTTP, +provider SDKs, and login flows. Hosts choose this adapter when exposing agent +access. The adapter pins `@modelcontextprotocol/sdk` at `1.32.2` and `zod` at +`4.6.7`; it composes the same exact `0.1.0` Knowledge Base packages. + +The MCP adapter explicitly uses the SDK's Workers-compatible JSON Schema +validator, which requires no generated code. Its `@cfworker/json-schema` +dependency is pinned at `4.1.6` and required by this package even though the +SDK declares it as an optional peer. Packed consumers receive the validator +without needing to discover or install that peer themselves. + +## Trust and composition + +The host owns credential issuance, authentication, resource binding, current +authorization, and evidence verification. Compose the adapter with the +Knowledge Base application and host authentication ports. Agent Access is a +separate producer; it is not a runtime dependency of this package. An opaque +credential, caller-supplied actor, or claimed evidence result does not establish +an authenticated `AccessContext` or trusted evidence. + +Agent operations use the same current-resource authorization, application +generation, immutable evidence, replay, and publication rules as other +application callers. Agents can prepare drafts and submit evidence through the +declared tool surface. Review and publication remain separate staff authority. +The adapter never executes article steps, fetches evidence URLs, provisions a +runner, or creates a second database or identity system. + +`createKnowledgeAgentDispatcher` provides the shared operation boundary. +`knowledgeAgentScopes`, `knowledgeAgentOperations`, and +`knowledgeAgentToolNames` declare its finite surface. Inputs are validated +against shared internal schemas and fixed component ceilings before dispatch. +Errors use bounded public responses rather than exposing internal exceptions +or private evidence and provenance. + +`createKnowledgeAgentHttp` and `createKnowledgeAgentMcp` expose that dispatcher +through host-configured protected endpoints. Both require fresh host +authentication and admission control on every request; neither issues tokens. + +The [host composition contract](https://github.com/pegma-dev/knowledge-base/blob/main/docs/HOST_COMPOSITION.md) +describes authenticated contexts, trusted evidence, replay, and safe DTOs. The +[retrieval contract](https://github.com/pegma-dev/knowledge-base/blob/main/docs/RETRIEVAL.md) +describes authoritative current-publication confirmation and audience boundaries. + +## Local verification and release + +Repository development uses Node 22.6.0+ or 24 with pnpm 10.34.5: + +```sh +pnpm install --frozen-lockfile +pnpm run format:check +pnpm run check +pnpm test +pnpm example +pnpm run release:check +pnpm run agent:proof +``` + +`release:check` packs and installs all four unpublished Knowledge Base packages +in an isolated temporary consumer, verifies their actual artifact bytes and +inventory, and imports their public entry points without workspace links. +`agent:proof` exercises the authenticated SDK path with a pinned public Agent +Access producer packed only into a temporary test consumer. That producer +source is a test fixture, not a production release substitute or package +dependency. These local checks establish neither live host acceptance nor npm +publication. + +Each package has its own README, MIT LICENSE, build-on-prepack hook, and +compiled-test exclusion. All four package versions remain synchronized at +`0.1.0`. First publication, release tags, trusted-publisher configuration, and +host activation are separate maintainer operations in the +[release procedure](https://github.com/pegma-dev/knowledge-base/blob/main/docs/RELEASING.md). +Development links above track `main`; release preparation must pin verified +release documentation before first publication. + +Built in the open by RetireGolden, LLC. diff --git a/packages/mcp/package.json b/packages/mcp/package.json new file mode 100644 index 0000000..f1cded5 --- /dev/null +++ b/packages/mcp/package.json @@ -0,0 +1,45 @@ +{ + "name": "@pegma/knowledge-base-mcp", + "version": "0.1.0", + "description": "Optional MCP transport for authorized Pegma knowledge authoring and validation.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/knowledge-base.git", + "directory": "packages/mcp" + }, + "dependencies": { + "@cfworker/json-schema": "4.1.6", + "@modelcontextprotocol/sdk": "1.32.2", + "@pegma/authorization-core": "0.4.0", + "@pegma/knowledge-base-application": "0.1.0", + "@pegma/knowledge-base-contracts": "0.1.0", + "@pegma/knowledge-base-core": "0.1.0", + "zod": "4.6.7" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run --silent build" + } +} diff --git a/packages/mcp/src/dispatcher.ts b/packages/mcp/src/dispatcher.ts new file mode 100644 index 0000000..d8952e5 --- /dev/null +++ b/packages/mcp/src/dispatcher.ts @@ -0,0 +1,223 @@ +import type { AccessContext } from "@pegma/authorization-core"; + +import { + createKnowledgeAgentErrorResponse, + KnowledgeAgentBoundaryError, + mapKnowledgeAgentError, +} from "./errors.js"; +import { + knowledgeAgentEnvelopeSchema, + knowledgeAgentResultSchemas, + resolveKnowledgeAgentLimits, + snapshotKnowledgeAgentJson, +} from "./schemas.js"; +import { + knowledgeAgentScopes, + type KnowledgeAgentDispatcher, + type KnowledgeAgentDispatcherOptions, + type KnowledgeAgentEnvelope, + type KnowledgeAgentIdentity, + type KnowledgeAgentOperation, + type KnowledgeAgentSuccess, +} from "./types.js"; + +const initialPermissions = Object.freeze(Object.values(knowledgeAgentScopes)); +// Trusted host authority is independently bounded. Client payload array limits +// must not reject an administrator's broad context before it can be attenuated. +const maximumAuthorityItems = 256; +const maximumAuthorityCharacters = 1_024; + +function own(value: unknown, key: string): unknown { + if ( + value === null || + typeof value !== "object" || + ![Object.prototype, null].includes(Object.getPrototypeOf(value)) + ) { + throw new KnowledgeAgentBoundaryError("forbidden"); + } + const descriptor = Object.getOwnPropertyDescriptor(value, key); + if (descriptor === undefined || !("value" in descriptor)) + throw new KnowledgeAgentBoundaryError("forbidden"); + return descriptor.value; +} + +function trustedText(value: unknown, maximum: number): string { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > maximum || + value.trim() !== value || + /[\u0000-\u001f\u007f\ud800-\udfff]/u.test(value) + ) { + throw new KnowledgeAgentBoundaryError("forbidden"); + } + return value; +} + +function knownPermissions(value: unknown): ReadonlySet { + if ( + !Array.isArray(value) || + Object.getPrototypeOf(value) !== Array.prototype + ) { + throw new KnowledgeAgentBoundaryError("forbidden"); + } + const length = Object.getOwnPropertyDescriptor(value, "length"); + if ( + length === undefined || + !("value" in length) || + typeof length.value !== "number" || + length.value > maximumAuthorityItems || + Reflect.ownKeys(value).length !== length.value + 1 + ) { + throw new KnowledgeAgentBoundaryError("forbidden"); + } + const result = new Set(); + for (let index = 0; index < length.value; index += 1) { + const descriptor = Object.getOwnPropertyDescriptor(value, String(index)); + if ( + descriptor === undefined || + !("value" in descriptor) || + !descriptor.enumerable + ) { + throw new KnowledgeAgentBoundaryError("forbidden"); + } + const permission: unknown = descriptor.value; + if ( + typeof permission !== "string" || + permission.length > maximumAuthorityCharacters + ) { + throw new KnowledgeAgentBoundaryError("forbidden"); + } + if (initialPermissions.some((known) => known === permission)) + result.add(permission); + } + return result; +} + +/** Snapshot the exact least-authority context without reading host role data. */ +function effectiveAccess( + identity: KnowledgeAgentIdentity, + resource: string, +): AccessContext { + if (trustedText(own(identity, "resource"), 2_048) !== resource) + throw new KnowledgeAgentBoundaryError("forbidden"); + trustedText(own(identity, "clientId"), 200); + const scopes = knownPermissions(own(identity, "scopes")); + const access = own(identity, "access"); + const principalId = trustedText(own(access, "principalId"), 200); + const policyVersion = trustedText(own(access, "policyVersion"), 200); + const currentPermissions = knownPermissions(own(access, "permissions")); + return Object.freeze({ + principalId, + policyVersion, + roles: Object.freeze([]), + entitlements: Object.freeze([]), + permissions: Object.freeze( + initialPermissions.filter( + (permission) => + scopes.has(permission) && currentPermissions.has(permission), + ), + ), + }); +} + +function requireOperation( + access: AccessContext, + operation: KnowledgeAgentOperation, +): void { + const has = (permission: string) => access.permissions.includes(permission); + const allowed = + operation === "getValidationRequirements" + ? has(knowledgeAgentScopes.draftWrite) || + has(knowledgeAgentScopes.evidenceSubmit) + : has( + operation === "getDraft" + ? knowledgeAgentScopes.draftRead + : operation === "submitEvidence" + ? knowledgeAgentScopes.evidenceSubmit + : knowledgeAgentScopes.draftWrite, + ); + if (!allowed) throw new KnowledgeAgentBoundaryError("forbidden"); +} + +/** + * One versioned least-authority boundary shared by HTTP and MCP. Authentication, + * credential issuance, current access resolution, and rate limits are host work. + */ +export function createKnowledgeAgentDispatcher( + options: KnowledgeAgentDispatcherOptions, +): KnowledgeAgentDispatcher { + const limits = resolveKnowledgeAgentLimits(options.limits); + const resource = trustedText(options.resource, 2_048); + const application = options.application; + return Object.freeze({ + limits, + async dispatch(identity: KnowledgeAgentIdentity, request: unknown) { + let operation: KnowledgeAgentOperation | null = null; + try { + // All caller-owned objects are detached before the first application + // await. The application still performs current resource/replay checks. + const access = effectiveAccess(identity, resource); + const snapshot = snapshotKnowledgeAgentJson(request, limits); + const parsed = knowledgeAgentEnvelopeSchema.safeParse(snapshot); + if (!parsed.success) + throw new KnowledgeAgentBoundaryError("invalid_request"); + const envelope = snapshotKnowledgeAgentJson( + parsed.data, + limits, + ) as KnowledgeAgentEnvelope; + operation = envelope.operation; + requireOperation(access, operation); + let result: unknown; + switch (envelope.operation) { + case "getDraft": + result = await application.getDraft(access, envelope.input); + break; + case "createDraft": + result = await application.createDraft(access, envelope.input); + break; + case "updateDraft": + result = await application.updateDraft(access, envelope.input); + break; + case "getValidationRequirements": + result = await application.getValidationRequirements( + access, + envelope.input, + ); + break; + case "submitEvidence": + result = await application.submitEvidence(access, envelope.input); + break; + } + let detached: unknown; + try { + detached = snapshotKnowledgeAgentJson( + result, + limits, + limits.maxResponseBytes, + ); + } catch (error) { + if ( + error instanceof KnowledgeAgentBoundaryError && + error.code === "capacity" + ) { + throw error; + } + throw new KnowledgeAgentBoundaryError("unavailable"); + } + const safe = knowledgeAgentResultSchemas[operation].safeParse(detached); + if (!safe.success) throw new KnowledgeAgentBoundaryError("unavailable"); + return snapshotKnowledgeAgentJson( + { apiVersion: "1", operation, result: safe.data }, + limits, + limits.maxResponseBytes, + ) as KnowledgeAgentSuccess; + } catch (error) { + return createKnowledgeAgentErrorResponse( + mapKnowledgeAgentError(error).code, + operation, + ); + } + }, + }); +} diff --git a/packages/mcp/src/errors.ts b/packages/mcp/src/errors.ts new file mode 100644 index 0000000..8b74175 --- /dev/null +++ b/packages/mcp/src/errors.ts @@ -0,0 +1,86 @@ +import { + KnowledgeBaseAuthorizationError, + KnowledgeBaseNotFoundError, + KnowledgeBasePrerequisiteError, + RepositoryCapacityError, + RepositoryConflictError, +} from "@pegma/knowledge-base-application"; +import { KnowledgeBaseError } from "@pegma/knowledge-base-core"; + +import type { + KnowledgeAgentError, + KnowledgeAgentErrorCode, + KnowledgeAgentFailure, + KnowledgeAgentOperation, +} from "./types.js"; + +const errors: Readonly> = + Object.freeze({ + invalid_request: Object.freeze({ + code: "invalid_request", + status: 400, + message: "Invalid knowledge request.", + }), + forbidden: Object.freeze({ + code: "forbidden", + status: 403, + message: "Knowledge access is forbidden.", + }), + not_found: Object.freeze({ + code: "not_found", + status: 404, + message: "Knowledge resource is unavailable.", + }), + conflict: Object.freeze({ + code: "conflict", + status: 409, + message: "Knowledge command conflicts with current state.", + }), + capacity: Object.freeze({ + code: "capacity", + status: 413, + message: "Knowledge request or result exceeds capacity.", + }), + prerequisite: Object.freeze({ + code: "prerequisite", + status: 412, + message: "Knowledge prerequisite is not ready.", + }), + unavailable: Object.freeze({ + code: "unavailable", + status: 503, + message: "Knowledge service is unavailable.", + }), + }); + +/** Internal classification only; never exposes an exception or its message. */ +export class KnowledgeAgentBoundaryError extends Error { + constructor(readonly code: KnowledgeAgentErrorCode) { + super("Knowledge agent boundary rejected data"); + this.name = "KnowledgeAgentBoundaryError"; + } +} + +/** Unknown application/storage/verifier failures become content-free 503s. */ +export function mapKnowledgeAgentError(error: unknown): KnowledgeAgentError { + if (error instanceof KnowledgeAgentBoundaryError) return errors[error.code]; + if (error instanceof KnowledgeBaseAuthorizationError) return errors.forbidden; + if (error instanceof KnowledgeBaseNotFoundError) return errors.not_found; + if (error instanceof RepositoryConflictError) return errors.conflict; + if (error instanceof RepositoryCapacityError) return errors.capacity; + if (error instanceof KnowledgeBasePrerequisiteError) + return errors.prerequisite; + if (error instanceof KnowledgeBaseError) { + if (error.code === "invalid") return errors.invalid_request; + if (error.code === "conflict") return errors.conflict; + return errors.prerequisite; + } + return errors.unavailable; +} + +export function createKnowledgeAgentErrorResponse( + code: KnowledgeAgentErrorCode, + operation: KnowledgeAgentOperation | null = null, +): KnowledgeAgentFailure { + return Object.freeze({ apiVersion: "1", operation, error: errors[code] }); +} diff --git a/packages/mcp/src/http.ts b/packages/mcp/src/http.ts new file mode 100644 index 0000000..dc05e88 --- /dev/null +++ b/packages/mcp/src/http.ts @@ -0,0 +1,72 @@ +import type { KnowledgeAgentDispatcher } from "./types.js"; +import { + authorizeKnowledgeAgentRequest, + knowledgeAgentJsonResponse, + knowledgeAgentRequestMatches, + knowledgeAgentTransportError, + readKnowledgeAgentJsonRequest, + secureKnowledgeAgentResponse, + validateKnowledgeAgentTransportOptions, +} from "./transport-common.js"; +import type { KnowledgeAgentTransportOptions } from "./transport-common.js"; + +export interface KnowledgeAgentHttpOptions extends KnowledgeAgentTransportOptions { + /** Exact canonical versioned API URL; the protected resource remains MCP. */ + readonly apiUrl: string; + readonly dispatcher: KnowledgeAgentDispatcher; +} + +export interface KnowledgeAgentHttp { + /** Null leaves unmatched paths to the host's router. */ + handle(request: Request): Promise; +} + +/** Portable Fetch adapter: host credentials and admission, shared application law. */ +export function createKnowledgeAgentHttp( + options: KnowledgeAgentHttpOptions, +): KnowledgeAgentHttp { + const configuration = validateKnowledgeAgentTransportOptions( + options, + options.apiUrl, + "http", + ); + const dispatcher = options.dispatcher; + return Object.freeze({ + async handle(request: Request): Promise { + if (!knowledgeAgentRequestMatches(request, configuration)) return null; + const identity = await authorizeKnowledgeAgentRequest( + request, + configuration, + ); + if (identity instanceof Response) return identity; + if (request.method !== "POST") + return knowledgeAgentTransportError( + "method_not_allowed", + request, + configuration, + ); + const parsed = await readKnowledgeAgentJsonRequest( + request, + dispatcher.limits, + ); + if (parsed instanceof Response) + return secureKnowledgeAgentResponse(parsed, request, configuration); + try { + const response = await dispatcher.dispatch(identity, parsed.value); + return knowledgeAgentJsonResponse( + response, + "error" in response ? response.error.status : 200, + dispatcher.limits.maxResponseBytes, + request, + configuration, + ); + } catch { + return knowledgeAgentTransportError( + "unavailable", + request, + configuration, + ); + } + }, + }); +} diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts new file mode 100644 index 0000000..b190514 --- /dev/null +++ b/packages/mcp/src/index.ts @@ -0,0 +1,17 @@ +export { createKnowledgeAgentDispatcher } from "./dispatcher.js"; +export { createKnowledgeAgentHttp } from "./http.js"; +export { createKnowledgeAgentMcp } from "./mcp.js"; +export { + defaultKnowledgeAgentLimits, + knowledgeAgentOperations, + knowledgeAgentScopes, + knowledgeAgentToolNames, +} from "./types.js"; +export type * from "./types.js"; +export type * from "./http.js"; +export type * from "./mcp.js"; +export type { + KnowledgeAgentLimitDecision, + KnowledgeAgentTransport, + KnowledgeAgentTransportOptions, +} from "./transport-common.js"; diff --git a/packages/mcp/src/mcp.ts b/packages/mcp/src/mcp.ts new file mode 100644 index 0000000..24228f9 --- /dev/null +++ b/packages/mcp/src/mcp.ts @@ -0,0 +1,421 @@ +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; +import { + CallToolRequestSchema, + ListToolsRequestSchema, + ToolSchema, + type CallToolResult, +} from "@modelcontextprotocol/sdk/types.js"; +import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker"; +import { z } from "zod"; + +import { + createKnowledgeAgentErrorResponse, + mapKnowledgeAgentError, +} from "./errors.js"; +import { + knowledgeAgentInputSchemas, + snapshotKnowledgeAgentJson, +} from "./schemas.js"; +import { + authorizeKnowledgeAgentRequest, + knowledgeAgentJsonResponse, + knowledgeAgentRequestMatches, + knowledgeAgentTransportError, + readKnowledgeAgentJsonRequest, + secureKnowledgeAgentResponse, + validateKnowledgeAgentTransportOptions, + type KnowledgeAgentTransportOptions, +} from "./transport-common.js"; +import { + knowledgeAgentOperations, + knowledgeAgentToolNames, + type KnowledgeAgentDispatcher, + type KnowledgeAgentOperation, + type KnowledgeAgentResponse, +} from "./types.js"; + +export interface KnowledgeAgentMcpOptions extends KnowledgeAgentTransportOptions { + /** Exact MCP endpoint; it must equal the canonical protected resource. */ + readonly mcpUrl: string; + readonly dispatcher: KnowledgeAgentDispatcher; +} + +export interface KnowledgeAgentMcp { + /** Null leaves unmatched paths to the host's router. */ + handle(request: Request): Promise; +} + +const requestId = z.union([ + z.string().max(128), + z.number().int().min(Number.MIN_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER), +]); +const empty = z.object({}).strict(); +const metadata = z.object({ progressToken: requestId.optional() }).strict(); +const basicParams = z.object({ _meta: metadata.optional() }).strict(); +const featureMap = z.record( + z.string().max(128), + z.record(z.string().max(128), z.unknown()), +); + +// Client capabilities are descriptive, never an authorization source. Accept +// the pinned protocol vocabulary without enabling any corresponding server API. +const clientCapabilities = z + .object({ + experimental: featureMap.optional(), + extensions: featureMap.optional(), + sampling: z + .object({ context: empty.optional(), tools: empty.optional() }) + .strict() + .optional(), + elicitation: z + .object({ + form: z + .object({ applyDefaults: z.boolean().optional() }) + .strict() + .optional(), + url: empty.optional(), + }) + .strict() + .optional(), + roots: z + .object({ listChanged: z.boolean().optional() }) + .strict() + .optional(), + tasks: z + .object({ + list: empty.optional(), + cancel: empty.optional(), + requests: z + .object({ + sampling: z + .object({ createMessage: empty.optional() }) + .strict() + .optional(), + elicitation: z + .object({ create: empty.optional() }) + .strict() + .optional(), + }) + .strict() + .optional(), + }) + .strict() + .optional(), + }) + .strict(); +const clientInfo = z + .object({ + name: z.string().min(1).max(256), + version: z.string().min(1).max(128), + title: z.string().max(256).optional(), + description: z.string().max(1_024).optional(), + websiteUrl: z.string().max(2_048).optional(), + icons: z + .array( + z + .object({ + src: z.string().max(2_048), + mimeType: z.string().max(128).optional(), + sizes: z.array(z.string().max(32)).max(16).optional(), + theme: z.enum(["light", "dark"]).optional(), + }) + .strict(), + ) + .max(16) + .optional(), + }) + .strict(); +const base = { jsonrpc: z.literal("2.0"), id: requestId }; +const rpcHeader = z + .object({ + ...base, + method: z.string().min(1).max(128), + params: z.record(z.string(), z.unknown()).optional(), + }) + .strict(); +const methods = new Set([ + "initialize", + "ping", + "tools/list", + "tools/call", + "notifications/initialized", +]); +const cancelledParams = basicParams.extend({ + requestId, + reason: z.string().max(1_024).optional(), +}); +// Idless envelopes use only SDK notification handlers, even for a tool method. +// Unknown notifications are ignored; cancellation is best-effort and stateless. +const rpcNotification = z + .object({ + jsonrpc: z.literal("2.0"), + method: z.string().min(1).max(128), + params: z.record(z.string(), z.unknown()).optional(), + }) + .strict() + .refine((notification) => { + if (notification.method === "notifications/initialized") + return ( + notification.params === undefined || + basicParams.safeParse(notification.params).success + ); + if (notification.method === "notifications/cancelled") + return cancelledParams.safeParse(notification.params).success; + return true; + }); +const rpcRequest = z.union([ + z + .object({ + ...base, + method: z.literal("initialize"), + params: basicParams.extend({ + protocolVersion: z.string().min(1).max(64), + capabilities: clientCapabilities, + clientInfo, + }), + }) + .strict(), + z + .object({ + ...base, + method: z.literal("ping"), + params: basicParams.optional(), + }) + .strict(), + z + .object({ + ...base, + method: z.literal("tools/list"), + params: basicParams.optional(), + }) + .strict(), + z + .object({ + ...base, + method: z.literal("tools/call"), + params: basicParams.extend({ + name: z.string().min(1).max(256), + arguments: z.record(z.string(), z.unknown()).optional(), + }), + }) + .strict(), + rpcNotification, +]); + +const descriptions: Readonly> = { + getDraft: "Read an authorized knowledge draft.", + createDraft: + "Create a knowledge draft using a replay-safe command identifier.", + updateDraft: + "Update a knowledge draft at its expected application generation.", + getValidationRequirements: + "Read current validation requirements for a draft.", + submitEvidence: + "Submit evidence with a host-verifiable receipt for an exact revision.", +}; +const tools = knowledgeAgentOperations.map((operation) => + ToolSchema.parse({ + name: knowledgeAgentToolNames[operation], + description: descriptions[operation], + inputSchema: z.toJSONSchema(knowledgeAgentInputSchemas[operation], { + unrepresentable: "any", + }), + annotations: { + readOnlyHint: + operation === "getDraft" || operation === "getValidationRequirements", + destructiveHint: false, + openWorldHint: false, + }, + }), +); + +function operationForTool(name: string): KnowledgeAgentOperation | null { + return ( + knowledgeAgentOperations.find( + (operation) => knowledgeAgentToolNames[operation] === name, + ) ?? null + ); +} + +function toolResult(response: KnowledgeAgentResponse): CallToolResult { + return { + content: [{ type: "text", text: JSON.stringify(response) }], + isError: "error" in response, + }; +} + +function protocolError(id: string | number | null, code = -32600): unknown { + const message = + code === -32601 + ? "MCP method is unavailable." + : code === -32603 + ? "MCP service is unavailable." + : code === -32000 + ? "MCP response exceeds capacity." + : "Invalid MCP request."; + return { + jsonrpc: "2.0", + id, + error: { code, message }, + }; +} + +/** + * Stateless, JSON-response Streamable HTTP. Every request resolves fresh host + * authority and owns a short-lived SDK server; no session or credential is cached. + */ +export function createKnowledgeAgentMcp( + options: KnowledgeAgentMcpOptions, +): KnowledgeAgentMcp { + const configuration = validateKnowledgeAgentTransportOptions( + options, + options.mcpUrl, + "mcp", + ); + const dispatcher = options.dispatcher; + // The logical response is identical to HTTP. JSON text inside JSON-RPC can + // double its escaping; bounded framing must not reject a complete valid guide. + const wireBudget = dispatcher.limits.maxResponseBytes * 2 + 4_096; + return Object.freeze({ + async handle(request: Request): Promise { + if (!knowledgeAgentRequestMatches(request, configuration)) return null; + const identity = await authorizeKnowledgeAgentRequest( + request, + configuration, + ); + if (identity instanceof Response) return identity; + if (request.method !== "POST") + return knowledgeAgentTransportError( + "method_not_allowed", + request, + configuration, + ); + const parsed = await readKnowledgeAgentJsonRequest( + request, + dispatcher.limits, + ); + if (parsed instanceof Response) + return secureKnowledgeAgentResponse(parsed, request, configuration); + const json = (value: unknown, status: number) => + knowledgeAgentJsonResponse( + value, + status, + wireBudget, + request, + configuration, + ); + let snapshot: unknown; + try { + snapshot = snapshotKnowledgeAgentJson(parsed.value, dispatcher.limits); + } catch (error) { + return knowledgeAgentTransportError( + mapKnowledgeAgentError(error).code === "capacity" + ? "capacity" + : "invalid_request", + request, + configuration, + ); + } + const validated = rpcRequest.safeParse(snapshot); + if (!validated.success) { + const header = rpcHeader.safeParse(snapshot); + if (header.success && !methods.has(header.data.method)) + return json(protocolError(header.data.id, -32601), 200); + return json(protocolError(header.success ? header.data.id : null), 400); + } + const rpc = validated.data; + const id = "id" in rpc ? rpc.id : null; + const transport = new WebStandardStreamableHTTPServerTransport({ + enableJsonResponse: true, + // An omitted generator is the SDK's explicit stateless mode. + maxRequestBodySize: dispatcher.limits.maxRequestBytes, + }); + const server = new Server( + { name: "@pegma/knowledge-base-mcp", version: "0.1.0" }, + { + capabilities: { tools: {} }, + // Workers prohibit the runtime code generation used by SDK-default AJV. + jsonSchemaValidator: new CfWorkerJsonSchemaValidator(), + }, + ); + server.setRequestHandler(ListToolsRequestSchema, () => ({ tools })); + server.setRequestHandler(CallToolRequestSchema, async (call) => { + const operation = operationForTool(call.params.name); + if (operation === null) + return toolResult( + createKnowledgeAgentErrorResponse("invalid_request"), + ); + try { + return toolResult( + await dispatcher.dispatch(identity, { + apiVersion: "1", + operation, + input: call.params.arguments, + }), + ); + } catch { + return toolResult( + createKnowledgeAgentErrorResponse("unavailable", operation), + ); + } + }); + try { + await server.connect(transport); + // In the pinned SDK, JSON mode resolves only after the asynchronous + // request handler has sent its complete result. Buffer before close. + const response = await transport.handleRequest(request, { + parsedBody: rpc, + }); + const bytes = await response.arrayBuffer(); + if (bytes.byteLength > wireBudget) { + if ("id" in rpc && rpc.method === "tools/call") + return json( + { + jsonrpc: "2.0", + id, + result: toolResult( + createKnowledgeAgentErrorResponse( + "capacity", + operationForTool(rpc.params.name), + ), + ), + }, + 200, + ); + return json(protocolError(id, -32000), 413); + } + if (response.status === 202) + return secureKnowledgeAgentResponse( + new Response(null, { status: 202 }), + request, + configuration, + ); + const value: unknown = JSON.parse(new TextDecoder().decode(bytes)); + if ( + response.status !== 200 || + (value !== null && typeof value === "object" && "error" in value) + ) + return json( + protocolError(id), + response.status === 200 ? 200 : response.status, + ); + return json(value, 200); + } catch { + return json(protocolError(id, -32603), 503); + } finally { + // Server.close owns transport cleanup. Await it after the JSON body is + // complete, including for failures and initialized notifications. + try { + await server.close(); + } catch { + try { + await transport.close(); + } catch { + // Cleanup failures never replace the bounded public response. + } + } + } + }, + }); +} diff --git a/packages/mcp/src/schemas.ts b/packages/mcp/src/schemas.ts new file mode 100644 index 0000000..43d6ce8 --- /dev/null +++ b/packages/mcp/src/schemas.ts @@ -0,0 +1,450 @@ +import { articleKinds } from "@pegma/knowledge-base-contracts"; +import { knowledgeLimits } from "@pegma/knowledge-base-core"; +import { z } from "zod"; + +import { KnowledgeAgentBoundaryError } from "./errors.js"; +import { + defaultKnowledgeAgentLimits, + minimumKnowledgeAgentResponseBytes, + type KnowledgeAgentLimits, +} from "./types.js"; + +const boundedText = (maximum: number) => + z + .string() + .min(1) + .max(maximum) + .regex( + /^[^\s\u0000-\u001f\u007f](?:[^\u0000-\u001f\u007f]*[^\s\u0000-\u001f\u007f])?$/u, + ) + .regex(/^[^\ud800-\udfff]*$/u); +const identifier = boundedText(knowledgeLimits.identifierCharacters); +const generation = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER); +const positiveInteger = z.number().int().min(1).max(Number.MAX_SAFE_INTEGER); +const hash = z.string().regex(/^[a-f0-9]{64}$/u); +const kind = z.enum(articleKinds); + +const applicability = z + .object({ + productId: identifier, + productVersion: identifier, + buildId: identifier.optional(), + locale: z.string().min(1).max(64).optional(), + }) + .strict(); +const content = z + .object({ + format: z.enum(["markdown", "plain_text"]), + text: z.string().min(1).max(knowledgeLimits.contentBytes), + }) + .strict(); +const validationPolicy = z + .object({ id: identifier, version: positiveInteger }) + .strict(); + +const articleDraft = z + .object({ + kind, + title: z.string().min(1).max(knowledgeLimits.titleCharacters), + summary: z.string().min(1).max(knowledgeLimits.summaryCharacters), + content, + tags: z + .array(z.string().min(1).max(knowledgeLimits.tagCharacters)) + .max(knowledgeLimits.tags), + applicability, + }) + .strict(); + +const evidenceSubmission = z + .object({ + id: identifier, + articleId: identifier, + articleRevision: positiveInteger, + contentHash: hash, + validationPolicy, + checkId: identifier, + testKind: identifier, + applicability, + stagingBuildId: identifier, + steps: z + .array(z.string().min(1).max(knowledgeLimits.stepCharacters)) + .min(1) + .max(knowledgeLimits.steps), + result: z.enum(["passed", "failed", "inconclusive"]), + executedAt: z.string().min(1).max(64), + runnerId: identifier, + artifacts: z + .array(z.object({ id: identifier, hash }).strict()) + .max(knowledgeLimits.artifacts), + }) + .strict(); + +const command = { + commandId: identifier, + correlationId: identifier, + expectedGeneration: generation, +}; + +/** Shared strict schemas; HTTP and MCP must use the same dispatcher. */ +export const knowledgeAgentInputSchemas = Object.freeze({ + getDraft: z.object({ articleId: identifier }).strict(), + createDraft: z + .object({ + ...command, + expectedGeneration: z.literal(0), + articleId: identifier, + collectionId: identifier, + draft: articleDraft, + }) + .strict(), + updateDraft: z + .object({ + ...command, + articleId: identifier, + collectionId: identifier, + draft: articleDraft, + }) + .strict(), + getValidationRequirements: z + .object({ collectionId: identifier, kind }) + .strict(), + submitEvidence: z + .object({ + ...command, + articleId: identifier, + evidence: evidenceSubmission, + receipt: boundedText(8_192).refine( + (value) => new TextEncoder().encode(value).byteLength <= 8_192, + ), + }) + .strict(), +}); + +export const knowledgeAgentEnvelopeSchema = z.discriminatedUnion("operation", [ + z + .object({ + apiVersion: z.literal("1"), + operation: z.literal("getDraft"), + input: knowledgeAgentInputSchemas.getDraft, + }) + .strict(), + z + .object({ + apiVersion: z.literal("1"), + operation: z.literal("createDraft"), + input: knowledgeAgentInputSchemas.createDraft, + }) + .strict(), + z + .object({ + apiVersion: z.literal("1"), + operation: z.literal("updateDraft"), + input: knowledgeAgentInputSchemas.updateDraft, + }) + .strict(), + z + .object({ + apiVersion: z.literal("1"), + operation: z.literal("getValidationRequirements"), + input: knowledgeAgentInputSchemas.getValidationRequirements, + }) + .strict(), + z + .object({ + apiVersion: z.literal("1"), + operation: z.literal("submitEvidence"), + input: knowledgeAgentInputSchemas.submitEvidence, + }) + .strict(), +]); + +// Output schemas deliberately construct purpose-specific DTOs. Extra private +// fields from an application wrapper never become transport response fields. +const articleState = z.enum(["draft", "in-review", "published", "retired"]); +const revision = articleDraft + .extend({ + articleId: identifier, + number: positiveInteger, + collectionId: identifier, + validationPolicy: validationPolicy.strip(), + contentHash: hash, + createdBy: identifier, + createdAt: z.string().min(1).max(64), + content: content.strip(), + applicability: applicability.strip(), + }) + .strip(); +const acknowledgement = z + .object({ + value: z + .object({ + id: identifier, + generation: positiveInteger, + articleRevision: positiveInteger, + state: articleState, + contentHash: hash, + }) + .strip(), + replayed: z.boolean(), + }) + .strip(); + +export const knowledgeAgentResultSchemas = Object.freeze({ + getDraft: z + .object({ + articleId: identifier, + generation: positiveInteger, + state: articleState, + revision, + hasPendingReview: z.boolean(), + hasPublication: z.boolean(), + publicationHeld: z.boolean(), + }) + .strip(), + createDraft: acknowledgement, + updateDraft: acknowledgement, + getValidationRequirements: z + .object({ + collectionId: identifier, + governanceGeneration: positiveInteger, + validationPolicy: validationPolicy.strip(), + expectedStagingBuildId: identifier, + checks: z + .array( + z + .object({ + id: identifier, + testKind: identifier, + maxAgeMilliseconds: positiveInteger, + }) + .strip(), + ) + .max(knowledgeLimits.requirements), + }) + .strip(), + submitEvidence: acknowledgement, +}); + +export function resolveKnowledgeAgentLimits( + requested: Partial = {}, +): KnowledgeAgentLimits { + if ( + requested === null || + typeof requested !== "object" || + ![Object.prototype, null].includes(Object.getPrototypeOf(requested)) + ) { + throw new TypeError("Invalid knowledge agent limits"); + } + const result = { ...defaultKnowledgeAgentLimits }; + for (const key of Reflect.ownKeys(requested)) { + if (typeof key !== "string" || !Object.hasOwn(result, key)) { + throw new TypeError("Unknown knowledge agent limit"); + } + const descriptor = Object.getOwnPropertyDescriptor(requested, key); + if (descriptor === undefined || !("value" in descriptor)) { + throw new TypeError("Invalid knowledge agent limit"); + } + const value: unknown = descriptor.value; + const name = key as keyof KnowledgeAgentLimits; + if ( + typeof value !== "number" || + !Number.isSafeInteger(value) || + value <= 0 || + value > defaultKnowledgeAgentLimits[name] || + (name === "maxResponseBytes" && + value < minimumKnowledgeAgentResponseBytes) + ) { + throw new TypeError("Knowledge agent limits may only reduce ceilings"); + } + result[name] = value; + } + return Object.freeze(result); +} + +/** + * Detach only plain JSON data properties, with work/encoded-byte accounting + * before Zod reads them. Accessors, sparse arrays, cycles, symbols, and custom + * prototypes are rejected without invoking JSON coercion or a getter. + */ +export function snapshotKnowledgeAgentJson( + value: unknown, + limits: KnowledgeAgentLimits, + maximumBytes = limits.maxRequestBytes, +): unknown { + const ancestors = new Set(); + let nodes = 0; + let bytes = 0; + const reserve = (count: number) => { + bytes += count; + if (bytes > maximumBytes) throw new KnowledgeAgentBoundaryError("capacity"); + }; + const encodedText = (item: string) => { + if (item.length > maximumBytes) + throw new KnowledgeAgentBoundaryError("capacity"); + const encoded = JSON.stringify(item); + if (encoded.length > maximumBytes) + throw new KnowledgeAgentBoundaryError("capacity"); + reserve(new TextEncoder().encode(encoded).byteLength); + }; + const visit = (item: unknown, depth: number): unknown => { + nodes += 1; + if (nodes > limits.maxNodes || depth > limits.maxDepth) + throw new KnowledgeAgentBoundaryError("capacity"); + if (item === null) { + reserve(4); + return item; + } + if (typeof item === "string") { + encodedText(item); + return item; + } + if (typeof item === "boolean") { + reserve(item ? 4 : 5); + return item; + } + if (typeof item === "number" && Number.isFinite(item)) { + reserve(String(item).length); + return item; + } + if (typeof item !== "object" || ancestors.has(item)) + throw new KnowledgeAgentBoundaryError("invalid_request"); + ancestors.add(item); + try { + if (Array.isArray(item)) { + if (item.length > limits.maxArrayLength) + throw new KnowledgeAgentBoundaryError("capacity"); + const keys = Reflect.ownKeys(item); + if (keys.length !== item.length + 1) + throw new KnowledgeAgentBoundaryError("invalid_request"); + reserve(2 + Math.max(0, item.length - 1)); + const output: unknown[] = []; + for (let index = 0; index < item.length; index += 1) { + const property = Object.getOwnPropertyDescriptor(item, String(index)); + if ( + property === undefined || + !("value" in property) || + !property.enumerable + ) { + throw new KnowledgeAgentBoundaryError("invalid_request"); + } + output.push(visit(property.value, depth + 1)); + } + return Object.freeze(output); + } + if (![Object.prototype, null].includes(Object.getPrototypeOf(item))) + throw new KnowledgeAgentBoundaryError("invalid_request"); + const keys = Reflect.ownKeys(item); + if (keys.length > limits.maxObjectKeys) + throw new KnowledgeAgentBoundaryError("capacity"); + reserve(2 + Math.max(0, keys.length - 1)); + const output: Record = Object.create(null); + for (const key of keys) { + if (typeof key !== "string") + throw new KnowledgeAgentBoundaryError("invalid_request"); + const property = Object.getOwnPropertyDescriptor(item, key); + if ( + property === undefined || + !("value" in property) || + !property.enumerable + ) { + throw new KnowledgeAgentBoundaryError("invalid_request"); + } + encodedText(key); + reserve(1); + output[key] = visit(property.value, depth + 1); + } + return Object.freeze(output); + } finally { + ancestors.delete(item); + } + }; + return visit(value, 0); +} + +/** Bound UTF-8 bytes and every structural ceiling before invoking JSON.parse. */ +export function parseKnowledgeAgentJson( + source: string, + requested?: Partial, +): unknown { + const limits = resolveKnowledgeAgentLimits(requested); + if (typeof source !== "string") + throw new KnowledgeAgentBoundaryError("invalid_request"); + if ( + source.length > limits.maxRequestBytes || + new TextEncoder().encode(source).byteLength > limits.maxRequestBytes + ) { + throw new KnowledgeAgentBoundaryError("capacity"); + } + type Frame = + | { kind: "array"; entries: number; expectsValue: boolean } + | { kind: "object"; keys: number }; + const frames: Frame[] = []; + const beginValue = () => { + const frame = frames.at(-1); + if (frame?.kind === "array" && frame.expectsValue) { + frame.entries += 1; + frame.expectsValue = false; + if (frame.entries > limits.maxArrayLength) + throw new KnowledgeAgentBoundaryError("capacity"); + } + }; + let nodes = 0; + let quoted = false; + let escaped = false; + let primitive = false; + for (const character of source) { + if (quoted) { + if (escaped) escaped = false; + else if (character === "\\") escaped = true; + else if (character === '"') quoted = false; + continue; + } + if (character === '"') { + beginValue(); + quoted = true; + primitive = false; + nodes += 1; + } else if (character === "{" || character === "[") { + beginValue(); + frames.push( + character === "[" + ? { kind: "array", entries: 0, expectsValue: true } + : { kind: "object", keys: 0 }, + ); + nodes += 1; + primitive = false; + } else if (character === "}" || character === "]") { + frames.pop(); + primitive = false; + } else if (character === ",") { + const frame = frames.at(-1); + if (frame?.kind === "array") frame.expectsValue = true; + primitive = false; + } else if (character === ":") { + // For valid JSON, each structural colon belongs to exactly one object + // key. Counting physical keys also bounds duplicate-key parse work. + const frame = frames.at(-1); + if (frame?.kind === "object") { + frame.keys += 1; + if (frame.keys > limits.maxObjectKeys) + throw new KnowledgeAgentBoundaryError("capacity"); + } + primitive = false; + } else if (/\s/u.test(character)) { + primitive = false; + } else if (!primitive) { + beginValue(); + primitive = true; + nodes += 1; + } + if (frames.length > limits.maxDepth || nodes > limits.maxNodes) + throw new KnowledgeAgentBoundaryError("capacity"); + } + let parsed: unknown; + try { + parsed = JSON.parse(source); + } catch { + throw new KnowledgeAgentBoundaryError("invalid_request"); + } + return snapshotKnowledgeAgentJson(parsed, limits); +} diff --git a/packages/mcp/src/transport-common.ts b/packages/mcp/src/transport-common.ts new file mode 100644 index 0000000..e00c5fe --- /dev/null +++ b/packages/mcp/src/transport-common.ts @@ -0,0 +1,573 @@ +import type { KnowledgeAgentIdentity, KnowledgeAgentLimits } from "./types.js"; +import { KnowledgeAgentBoundaryError } from "./errors.js"; +import { parseKnowledgeAgentJson } from "./schemas.js"; + +export type KnowledgeAgentTransport = "http" | "mcp"; + +export interface KnowledgeAgentLimitDecision { + readonly allowed: boolean; + readonly retryAfterSeconds?: number; +} + +/** Ports receive the original request; neither a cookie nor body is authority. */ +export interface KnowledgeAgentTransportOptions { + /** Canonical protected MCP resource, shared by both agent transports. */ + readonly resource: string; + /** Host-owned Agent Access protected-resource metadata; never served here. */ + readonly protectedResourceMetadataUrl: string; + /** Exact serialized origins. Originless native clients are also accepted. */ + readonly allowedOrigins: readonly string[]; + /** + * Authenticate the bearer credential, issuer, client, exact resource, expiry, + * revocation and current principal. Re-resolve authority on every request. + * Rejections are normalized: response bodies and host headers are discarded. + */ + readonly authenticate: ( + request: Request, + ) => + | KnowledgeAgentIdentity + | Response + | Promise; + /** Required host admission port, called before authentication or body reads. */ + readonly limit: ( + request: Request, + context: Readonly<{ transport: KnowledgeAgentTransport }>, + ) => + | boolean + | KnowledgeAgentLimitDecision + | Promise; + /** For synthetic loopback composition only; production endpoints use HTTPS. */ + readonly allowInsecureLoopback?: boolean; +} + +export interface KnowledgeAgentTransportConfiguration { + readonly transport: KnowledgeAgentTransport; + readonly endpointUrl: string; + readonly endpointOrigin: string; + readonly endpointPath: string; + readonly endpointHost: string; + readonly endpointProtocol: string; + readonly resource: string; + readonly protectedResourceMetadataUrl: string; + readonly allowedOrigins: readonly string[]; + readonly authenticate: KnowledgeAgentTransportOptions["authenticate"]; + readonly limit: KnowledgeAgentTransportOptions["limit"]; +} + +export type KnowledgeAgentTransportErrorCode = + | "invalid_request" + | "invalid_token" + | "forbidden" + | "temporarily_unavailable" + | "unavailable" + | "capacity" + | "method_not_allowed" + | "unsupported_media_type"; + +const transportErrors = Object.freeze({ + invalid_request: [400, "Invalid knowledge request."], + invalid_token: [401, "Knowledge authentication is required."], + forbidden: [403, "Knowledge access is forbidden."], + temporarily_unavailable: [ + 429, + "Knowledge service is temporarily unavailable.", + ], + unavailable: [503, "Knowledge service is unavailable."], + capacity: [413, "Knowledge request or result exceeds capacity."], + method_not_allowed: [405, "Knowledge endpoint requires POST."], + unsupported_media_type: [415, "Knowledge endpoint requires UTF-8 JSON."], +} as const); + +const encoder = new TextEncoder(); +const maxBodyChunks = 1_024; +const maxAuthorityItems = 256; +const maxAuthorityCharacters = 1_024; + +function cancelStream( + stream: { cancel(): Promise } | null | undefined, +): void { + try { + // A peer's cancellation hook must not hold the rejection response open. + void stream?.cancel().catch(() => {}); + } catch { + // Cancellation can throw for a locked stream; no content is consumed. + } +} + +function configurationError(): never { + throw new TypeError("Invalid knowledge agent transport configuration."); +} + +function configuredUrl(value: string, allowLoopback: boolean): URL { + if (typeof value !== "string" || value.length > 2_048) + return configurationError(); + let url: URL; + try { + url = new URL(value); + } catch { + return configurationError(); + } + const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + if ( + (url.protocol !== "https:" && + !(allowLoopback && loopback && url.protocol === "http:")) || + url.username !== "" || + url.password !== "" || + value !== `${url.origin}${url.pathname}` + ) + return configurationError(); + return url; +} + +/** Validate and snapshot host configuration once, before accepting requests. */ +export function validateKnowledgeAgentTransportOptions( + options: KnowledgeAgentTransportOptions, + endpointUrl: string, + transport: KnowledgeAgentTransport, +): KnowledgeAgentTransportConfiguration { + const allowLoopback = options.allowInsecureLoopback === true; + const endpoint = configuredUrl(endpointUrl, allowLoopback); + configuredUrl(options.resource, allowLoopback); + configuredUrl(options.protectedResourceMetadataUrl, allowLoopback); + if ( + (transport !== "http" && transport !== "mcp") || + (transport === "mcp" && endpointUrl !== options.resource) || + typeof options.authenticate !== "function" || + typeof options.limit !== "function" || + !Array.isArray(options.allowedOrigins) || + options.allowedOrigins.length > 64 || + (options.allowInsecureLoopback !== undefined && + typeof options.allowInsecureLoopback !== "boolean") + ) + return configurationError(); + const origins = options.allowedOrigins.map((origin) => { + const parsed = configuredUrl(`${origin}/`, allowLoopback); + if (parsed.origin !== origin) return configurationError(); + return origin; + }); + return Object.freeze({ + transport, + endpointUrl, + endpointOrigin: endpoint.origin, + endpointPath: endpoint.pathname, + endpointHost: endpoint.host, + endpointProtocol: endpoint.protocol, + resource: options.resource, + protectedResourceMetadataUrl: options.protectedResourceMetadataUrl, + allowedOrigins: Object.freeze([...new Set(origins)]), + authenticate: options.authenticate, + limit: options.limit, + }); +} + +/** A matching path is claimed so a hostile authority cannot bypass admission. */ +export function knowledgeAgentRequestMatches( + request: Request, + configuration: KnowledgeAgentTransportConfiguration, +): boolean { + try { + return new URL(request.url).pathname === configuration.endpointPath; + } catch { + return false; + } +} + +function baseHeaders(): Headers { + return new Headers({ + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + }); +} + +/** Replace implicit CORS and caching with this endpoint's explicit policy. */ +export function secureKnowledgeAgentResponse( + response: Response, + request: Request, + configuration: KnowledgeAgentTransportConfiguration, +): Response { + const headers = new Headers(response.headers); + for (const key of [...headers.keys()]) { + if (key.toLowerCase().startsWith("access-control-")) headers.delete(key); + } + for (const [key, value] of baseHeaders()) headers.set(key, value); + headers.delete("Set-Cookie"); + const vary = new Set( + (headers.get("Vary") ?? "") + .split(",") + .map((value) => value.trim()) + .filter(Boolean), + ); + vary.add("Origin"); + headers.set("Vary", [...vary].join(", ")); + const origin = request.headers.get("Origin"); + if (origin !== null && configuration.allowedOrigins.includes(origin)) { + headers.set("Access-Control-Allow-Origin", origin); + headers.set( + "Access-Control-Expose-Headers", + "WWW-Authenticate, Retry-After", + ); + } + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }); +} + +function rawTransportError( + code: KnowledgeAgentTransportErrorCode, + retryAfterSeconds?: number, +): Response { + const [status, message] = transportErrors[code]; + const headers = baseHeaders(); + headers.set("Content-Type", "application/json; charset=utf-8"); + if (code === "method_not_allowed") headers.set("Allow", "POST"); + if ( + code === "temporarily_unavailable" && + retryAfterSeconds !== undefined && + Number.isSafeInteger(retryAfterSeconds) && + retryAfterSeconds >= 0 && + retryAfterSeconds <= 86_400 + ) + headers.set("Retry-After", String(retryAfterSeconds)); + return new Response( + JSON.stringify({ + apiVersion: "1", + operation: null, + error: { code, status, message }, + }), + { status, headers }, + ); +} + +export function knowledgeAgentTransportError( + code: KnowledgeAgentTransportErrorCode, + request: Request, + configuration: KnowledgeAgentTransportConfiguration, + retryAfterSeconds?: number, +): Response { + const response = rawTransportError(code, retryAfterSeconds); + if (code === "invalid_token" || code === "forbidden") { + const error = + code === "invalid_token" ? "invalid_token" : "insufficient_scope"; + response.headers.set( + "WWW-Authenticate", + `Bearer error="${error}", resource_metadata="${configuration.protectedResourceMetadataUrl}"`, + ); + } + return secureKnowledgeAgentResponse(response, request, configuration); +} + +function validHost( + request: Request, + configuration: KnowledgeAgentTransportConfiguration, +): boolean { + const host = request.headers.get("Host"); + // Fetch runtimes may omit Host: the absolute request URL remains mandatory. + if (host === null) return true; + try { + const parsed = new URL(`${configuration.endpointProtocol}//${host}`); + return ( + parsed.host === configuration.endpointHost && + parsed.username === "" && + parsed.password === "" && + parsed.pathname === "/" && + parsed.search === "" && + parsed.hash === "" && + !/[\s/@?#\\]/u.test(host) + ); + } catch { + return false; + } +} + +function authorityString(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= maxAuthorityCharacters && + !/[\u0000-\u001f\u007f]/u.test(value) + ); +} + +function authorityRecord(value: unknown): value is object { + if (value === null || typeof value !== "object") return false; + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) return false; + const keys = Reflect.ownKeys(value); + if (keys.length > 32) return false; + for (let index = 0; index < keys.length; index += 1) { + if (typeof keys[index] !== "string") return false; + } + return true; +} + +function ownAuthorityData(value: object, key: string): unknown { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + return descriptor !== undefined && "value" in descriptor + ? descriptor.value + : undefined; +} + +function authorityList(value: unknown): readonly string[] | null { + if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) + return null; + const length = ownAuthorityData(value, "length"); + if ( + typeof length !== "number" || + !Number.isSafeInteger(length) || + length < 0 || + length > maxAuthorityItems || + Reflect.ownKeys(value).length !== length + 1 + ) + return null; + const output: string[] = []; + for (let index = 0; index < length; index += 1) { + const descriptor = Object.getOwnPropertyDescriptor(value, String(index)); + if ( + descriptor === undefined || + !("value" in descriptor) || + !descriptor.enumerable || + !authorityString(descriptor.value) + ) + return null; + output[index] = descriptor.value; + } + return Object.freeze(output); +} + +/** Detach bounded trusted facts so later host mutation cannot change authority. */ +function snapshotIdentity( + value: KnowledgeAgentIdentity, + resource: string, +): KnowledgeAgentIdentity | null { + if (!authorityRecord(value)) return null; + const clientId = ownAuthorityData(value, "clientId"); + const scopes = authorityList(ownAuthorityData(value, "scopes")); + const access = ownAuthorityData(value, "access"); + if ( + ownAuthorityData(value, "resource") !== resource || + !authorityString(clientId) || + scopes === null || + !authorityRecord(access) + ) + return null; + const principalId = ownAuthorityData(access, "principalId"); + const policyVersion = ownAuthorityData(access, "policyVersion"); + const permissions = authorityList(ownAuthorityData(access, "permissions")); + if ( + !authorityString(principalId) || + !authorityString(policyVersion) || + permissions === null + ) + return null; + return Object.freeze({ + clientId, + resource, + scopes, + access: Object.freeze({ + principalId, + policyVersion, + roles: Object.freeze([]), + entitlements: Object.freeze([]), + permissions, + }), + }); +} + +/** Shared HTTP/MCP admission. No untrusted body is read by this function. */ +export async function authorizeKnowledgeAgentRequest( + request: Request, + configuration: KnowledgeAgentTransportConfiguration, +): Promise { + const reject = ( + code: KnowledgeAgentTransportErrorCode, + retryAfterSeconds?: number, + ) => + knowledgeAgentTransportError( + code, + request, + configuration, + retryAfterSeconds, + ); + let url: URL; + try { + url = new URL(request.url); + } catch { + return reject("invalid_request"); + } + if ( + url.href !== configuration.endpointUrl || + !validHost(request, configuration) + ) + return reject("invalid_request"); + const origin = request.headers.get("Origin"); + if (origin !== null && !configuration.allowedOrigins.includes(origin)) + return reject("forbidden"); + + try { + const decision = await configuration.limit(request, { + transport: configuration.transport, + }); + if (decision === false) return reject("temporarily_unavailable"); + if (decision !== true) { + if ( + decision === null || + typeof decision !== "object" || + typeof decision.allowed !== "boolean" + ) + return reject("unavailable"); + if (!decision.allowed) + return reject("temporarily_unavailable", decision.retryAfterSeconds); + } + } catch { + return reject("unavailable"); + } + + const authorization = request.headers.get("Authorization"); + if ( + authorization === null || + authorization.length > 8_192 || + !/^Bearer +[A-Za-z0-9._~+/-]+=*$/i.test(authorization) + ) + return reject("invalid_token"); + try { + const authenticated = await configuration.authenticate(request); + if (authenticated instanceof Response) { + // Host error messages, cookies, redirects and custom challenges are private. + cancelStream(authenticated.body); + if (authenticated.status === 401) return reject("invalid_token"); + if (authenticated.status === 403) return reject("forbidden"); + return reject("unavailable"); + } + const identity = snapshotIdentity(authenticated, configuration.resource); + return identity ?? reject("invalid_token"); + } catch { + return reject("unavailable"); + } +} + +/** Read actual bytes/chunks before decoding or parsing; never trust Length alone. */ +export async function readKnowledgeAgentJsonRequest( + request: Request, + limits: KnowledgeAgentLimits, +): Promise<{ readonly value: unknown } | Response> { + const maxBytes = limits.maxRequestBytes; + if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) + return rawTransportError("unavailable"); + const contentType = request.headers.get("Content-Type") ?? ""; + if ( + !/^application\/json(?:\s*;\s*charset\s*=\s*(?:utf-8|"utf-8"))?\s*$/iu.test( + contentType, + ) + ) + return rawTransportError("unsupported_media_type"); + const encoding = request.headers.get("Content-Encoding"); + if (encoding !== null && encoding.toLowerCase() !== "identity") + return rawTransportError("unsupported_media_type"); + const declared = request.headers.get("Content-Length"); + if ( + declared !== null && + (!/^\d+$/u.test(declared) || !Number.isSafeInteger(Number(declared))) + ) + return rawTransportError("invalid_request"); + if (declared !== null && Number(declared) > maxBytes) { + cancelStream(request.body); + return rawTransportError("capacity"); + } + if (request.body === null) return rawTransportError("invalid_request"); + let reader: ReadableStreamDefaultReader; + try { + reader = request.body.getReader(); + } catch { + return rawTransportError("invalid_request"); + } + try { + const chunks: Uint8Array[] = []; + let bytes = 0; + let count = 0; + while (true) { + const next = await reader.read(); + if (next.done) break; + count += 1; + bytes += next.value.byteLength; + if (bytes > maxBytes || count > maxBodyChunks) { + cancelStream(reader); + return rawTransportError("capacity"); + } + chunks.push(next.value.slice()); + } + if (declared !== null && Number(declared) !== bytes) + return rawTransportError("invalid_request"); + const body = new Uint8Array(bytes); + let offset = 0; + for (const chunk of chunks) { + body.set(chunk, offset); + offset += chunk.byteLength; + } + const text = new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true, + }).decode(body); + return { + value: parseKnowledgeAgentJson(text, limits), + }; + } catch (error) { + if ( + error instanceof KnowledgeAgentBoundaryError && + error.code === "capacity" + ) + return rawTransportError("capacity"); + return rawTransportError("invalid_request"); + } finally { + reader.releaseLock(); + } +} + +/** Serialize only complete bounded messages; never truncate application results. */ +export function knowledgeAgentJsonResponse( + value: unknown, + status: number, + maxBytes: number, + request: Request, + configuration: KnowledgeAgentTransportConfiguration, +): Response { + try { + const body = JSON.stringify(value); + if ( + body === undefined || + !Number.isSafeInteger(maxBytes) || + maxBytes <= 0 || + encoder.encode(body).byteLength > maxBytes + ) + throw new TypeError("Knowledge response exceeds capacity"); + return secureKnowledgeAgentResponse( + new Response(body, { + status, + headers: { "Content-Type": "application/json; charset=utf-8" }, + }), + request, + configuration, + ); + } catch { + const fallback = rawTransportError("unavailable"); + // Even reduced budgets that cannot fit the fixed error remain bounded. + const fixedBytes = encoder.encode( + JSON.stringify({ + apiVersion: "1", + operation: null, + error: { + code: "unavailable", + status: 503, + message: "Knowledge service is unavailable.", + }, + }), + ).byteLength; + return secureKnowledgeAgentResponse( + fixedBytes <= maxBytes ? fallback : new Response(null, { status: 503 }), + request, + configuration, + ); + } +} diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts new file mode 100644 index 0000000..880bcbc --- /dev/null +++ b/packages/mcp/src/types.ts @@ -0,0 +1,160 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import type { + ArticleAcknowledgement, + ArticleReadInput, + CommandResult, + CreateDraftInput, + DraftArticleDto, + KnowledgeBaseApplication, + SubmitEvidenceInput, + UpdateDraftInput, + ValidationRequirementsDto, + ValidationRequirementsReadInput, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { knowledgeLimits } from "@pegma/knowledge-base-core"; + +/** Scopes are existing application permission names, never a second role model. */ +export const knowledgeAgentScopes = Object.freeze({ + draftRead: knowledgePermissions.draftRead, + draftWrite: knowledgePermissions.draftWrite, + evidenceSubmit: knowledgePermissions.evidenceSubmit, +}); + +export const knowledgeAgentOperations = Object.freeze([ + "getDraft", + "createDraft", + "updateDraft", + "getValidationRequirements", + "submitEvidence", +] as const); + +export type KnowledgeAgentOperation = (typeof knowledgeAgentOperations)[number]; + +export const knowledgeAgentToolNames = Object.freeze({ + getDraft: "knowledge_v1_get_draft", + createDraft: "knowledge_v1_create_draft", + updateDraft: "knowledge_v1_update_draft", + getValidationRequirements: "knowledge_v1_get_validation_requirements", + submitEvidence: "knowledge_v1_submit_evidence", +} as const satisfies Record); + +/** Authenticated by the host, supplied separately from every untrusted body. */ +export interface KnowledgeAgentIdentity { + readonly access: AccessContext; + readonly scopes: readonly string[]; + readonly clientId: string; + readonly resource: string; +} + +export interface KnowledgeAgentInputMap { + readonly getDraft: ArticleReadInput; + readonly createDraft: CreateDraftInput; + readonly updateDraft: UpdateDraftInput; + readonly getValidationRequirements: ValidationRequirementsReadInput; + readonly submitEvidence: SubmitEvidenceInput; +} + +export interface KnowledgeAgentResultMap { + readonly getDraft: DraftArticleDto; + readonly createDraft: CommandResult; + readonly updateDraft: CommandResult; + readonly getValidationRequirements: ValidationRequirementsDto; + readonly submitEvidence: CommandResult; +} + +export type KnowledgeAgentEnvelope = { + [Operation in KnowledgeAgentOperation]: { + readonly apiVersion: "1"; + readonly operation: Operation; + readonly input: KnowledgeAgentInputMap[Operation]; + }; +}[KnowledgeAgentOperation]; + +export type KnowledgeAgentSuccess = { + [Operation in KnowledgeAgentOperation]: { + readonly apiVersion: "1"; + readonly operation: Operation; + readonly result: KnowledgeAgentResultMap[Operation]; + }; +}[KnowledgeAgentOperation]; + +export type KnowledgeAgentErrorCode = + | "invalid_request" + | "forbidden" + | "not_found" + | "conflict" + | "capacity" + | "prerequisite" + | "unavailable"; + +export interface KnowledgeAgentError { + readonly code: KnowledgeAgentErrorCode; + readonly status: number; + readonly message: string; +} + +export interface KnowledgeAgentFailure { + readonly apiVersion: "1"; + /** Invalid envelopes never reflect an unrecognized caller-supplied name. */ + readonly operation: KnowledgeAgentOperation | null; + readonly error: KnowledgeAgentError; +} + +export type KnowledgeAgentResponse = + KnowledgeAgentSuccess | KnowledgeAgentFailure; + +export interface KnowledgeAgentLimits { + readonly maxRequestBytes: number; + readonly maxResponseBytes: number; + readonly maxDepth: number; + readonly maxNodes: number; + readonly maxArrayLength: number; + readonly maxObjectKeys: number; +} + +// A complete 32 KiB guide or sixteen 1,000-character evidence steps, including +// UTF-8 expansion, receipt, metadata, and JSON framing. Never truncate a guide. +const completeMessageBytes = knowledgeLimits.contentBytes * 4; + +// Reserve a complete mutation acknowledgement before any operation can run. +// Four UTF-8 bytes per identifier character is conservative for the core's +// character bound; JSON escapes are smaller. Generation/revision, SHA-256, and +// 512 bytes of fixed keys/version/operation/state framing fit the remainder. +// Round that ceiling up to a whole KiB (currently 2,048 bytes), so lowering the +// response budget cannot strand either a new commit or a historical replay. +const maximumMutationAcknowledgementBytes = + knowledgeLimits.identifierCharacters * 4 + + String(Number.MAX_SAFE_INTEGER).length * 2 + + 64 + + 512; +export const minimumKnowledgeAgentResponseBytes = + Math.ceil(maximumMutationAcknowledgementBytes / 1_024) * 1_024; + +export const defaultKnowledgeAgentLimits: KnowledgeAgentLimits = Object.freeze({ + maxRequestBytes: completeMessageBytes, + maxResponseBytes: completeMessageBytes, + maxDepth: 12, + maxNodes: 1_024, + maxArrayLength: knowledgeLimits.requirements, + maxObjectKeys: 32, +}); + +export interface KnowledgeAgentDispatcherOptions { + readonly application: KnowledgeBaseApplication; + /** Exact protected-resource identifier configured by this host. */ + readonly resource: string; + /** + * Positive safe integers may only reduce the fixed component ceilings. + * maxResponseBytes must reserve at least 2,048 bytes for acknowledgements. + */ + readonly limits?: Partial; +} + +export interface KnowledgeAgentDispatcher { + readonly limits: KnowledgeAgentLimits; + dispatch( + identity: KnowledgeAgentIdentity, + envelope: unknown, + ): Promise; +} diff --git a/packages/mcp/tsconfig.json b/packages/mcp/tsconfig.json new file mode 100644 index 0000000..cca8c9c --- /dev/null +++ b/packages/mcp/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo" + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"], + "references": [ + { "path": "../contracts" }, + { "path": "../core" }, + { "path": "../application" } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 630d7f0..4435bac 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11,9 +11,15 @@ importers: '@azure/data-tables': specifier: 13.3.2 version: 13.3.2 + '@cfworker/json-schema': + specifier: 4.1.6 + version: 4.1.6 '@cloudflare/workers-types': specifier: 5.20260730.1 version: 5.20260730.1 + '@modelcontextprotocol/sdk': + specifier: 1.32.2 + version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7) '@pegma/authorization-core': specifier: 0.4.0 version: 0.4.0 @@ -26,6 +32,9 @@ importers: '@pegma/knowledge-base-core': specifier: 0.1.0 version: link:packages/core + '@pegma/knowledge-base-mcp': + specifier: 0.1.0 + version: link:packages/mcp '@pegma/spine': specifier: 0.1.2 version: 0.1.2 @@ -56,6 +65,9 @@ importers: vitest: specifier: 5.0.5 version: 5.0.5(@opentelemetry/api@1.10.0)(@types/node@26.6.6)(vite@8.3.6(@types/node@26.6.6)(yaml@2.9.1)) + zod: + specifier: 4.6.7 + version: 4.6.7 packages/application: dependencies: @@ -90,6 +102,30 @@ importers: specifier: 0.1.0 version: link:../contracts + packages/mcp: + dependencies: + '@cfworker/json-schema': + specifier: 4.1.6 + version: 4.1.6 + '@modelcontextprotocol/sdk': + specifier: 1.32.2 + version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7) + '@pegma/authorization-core': + specifier: 0.4.0 + version: 0.4.0 + '@pegma/knowledge-base-application': + specifier: 0.1.0 + version: link:../application + '@pegma/knowledge-base-contracts': + specifier: 0.1.0 + version: link:../contracts + '@pegma/knowledge-base-core': + specifier: 0.1.0 + version: link:../core + zod: + specifier: 4.6.7 + version: 4.6.7 + packages: '@azure-rest/core-client@2.9.0': @@ -196,6 +232,9 @@ packages: resolution: {integrity: sha512-FJCHWlMA//XMs5rxf1z/mN0gaWPbJhlAVw5l4IxKhEtZX2bgNERlqbdBWXNjjkok+nTh0UcKqV5G0rrCupo+4A==} engines: {node: '>=20.0.0'} + '@cfworker/json-schema@4.1.6': + resolution: {integrity: sha512-YzVGTHXf4bzlyAL5KAvHYCdNbbt6zM5cYkAgxqxQPDQM6aZ4ShIIN5yJ+6q7YeonnevxT8k/LmD2tJi/jOiKkg==} + '@cloudflare/workerd-darwin-64@1.20260730.1': resolution: {integrity: sha512-+MBHmPaiTe2KajryW0T24rZvWFxb41hD3d8anNzQqHzft6vSEb18+sp0znSwxgij7ApPhSM1+vhkNg4f3YMguA==} engines: {node: '>=16'} @@ -256,6 +295,12 @@ packages: engines: {node: '>=6'} hasBin: true + '@hono/node-server@2.1.6': + resolution: {integrity: sha512-p/KH9MnfNcsm3sR6x4lNgm5j+QN4Et8srKredl9DZfXiyZ1UQ3aQ2YVpFLbqktYN5JI+DB+VZFKM2PqE5hLKjQ==} + engines: {node: '>=20'} + peerDependencies: + hono: ^4 || ^5.0.0-0 + '@img/colour@1.1.0': resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} @@ -440,6 +485,16 @@ packages: '@microsoft/applicationinsights-web-snippet@1.2.3': resolution: {integrity: sha512-59ex4x1/PabGQIg+o0GKG5olqAJYBvMOiXec/9HCD3hK2y36YMWT0ivq5mequvtS5+21kco3SOnMB6QyScLPIA==} + '@modelcontextprotocol/sdk@1.32.2': + resolution: {integrity: sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==} + engines: {node: '>=18'} + peerDependencies: + '@cfworker/json-schema': ^4.1.1 + zod: ^3.25 || ^4.0 + peerDependenciesMeta: + '@cfworker/json-schema': + optional: true + '@nodable/entities@3.1.0': resolution: {integrity: sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==} @@ -1132,6 +1187,17 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} + ajv-formats@3.0.1: + resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -1269,6 +1335,10 @@ packages: resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==} engines: {node: '>=18'} + content-type@1.0.5: + resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} + engines: {node: '>= 0.6'} + content-type@2.1.0: resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} engines: {node: '>=18'} @@ -1285,6 +1355,14 @@ packages: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} + cors@2.8.6: + resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} + engines: {node: '>= 0.10'} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + debug@2.6.9: resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} peerDependencies: @@ -1401,14 +1479,34 @@ packages: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} + eventsource-parser@3.1.1: + resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} + engines: {node: '>=18.0.0'} + + eventsource@3.0.7: + resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} + engines: {node: '>=18.0.0'} + expect-type@1.4.0: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} + express-rate-limit@8.7.3: + resolution: {integrity: sha512-zPLqDI2f0gV2WmGnacLf9XSSqn4VldRyP5LCzOwx0BKH40mO6+2PCFkoSsRO2jePx87/Kf6NUF6P2QOTKXHbQA==} + engines: {node: '>= 16'} + peerDependencies: + express: '>= 4.11' + express@5.3.0: resolution: {integrity: sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==} engines: {node: '>= 18'} + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-uri@3.1.9: + resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} + fast-xml-builder@1.3.1: resolution: {integrity: sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==} @@ -1516,6 +1614,10 @@ packages: resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} engines: {node: '>= 0.4'} + hono@4.13.17: + resolution: {integrity: sha512-vZIcbkvjOR5hHRWERbGkr8fGfF0GGM1ooYkuH448iO3b2AdVEr3AXZSw4Z3Kn+1L5z0CVoVeyV29VGYmFh05kQ==} + engines: {node: '>=16.9.0'} + http-errors@2.0.1: resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} engines: {node: '>= 0.8'} @@ -1553,6 +1655,10 @@ packages: inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + ip-address@10.7.6: + resolution: {integrity: sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==} + engines: {node: '>= 12'} + ipaddr.js@1.9.1: resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} engines: {node: '>= 0.10'} @@ -1592,9 +1698,21 @@ packages: resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==} engines: {node: '>=16'} + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jose@6.2.15: + resolution: {integrity: sha512-qdF6ewcZARtef63fJ9AKKZPgxw+t7USH6HLXYcD4CrdmSvDp79rpJSPFEKc90QBeGS63u1KQtN2MZQHC0yDIzA==} + js-md4@0.3.2: resolution: {integrity: sha512-/GDnfQYsltsjRswQhN9fhv3EMw2sCpUdrdxyWDOUK7eyD++r3gRhzgiQgc/x4MAv2i1iuQ4lxO5mvqM3vj4bwA==} + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + json-schema-typed@8.0.2: + resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} + jsonfile@6.2.1: resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} @@ -1827,6 +1945,10 @@ packages: encoding: optional: true + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + object-inspect@1.13.4: resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} engines: {node: '>= 0.4'} @@ -1861,6 +1983,10 @@ packages: resolution: {integrity: sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==} engines: {node: '>=14.0.0'} + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + path-to-regexp@8.4.2: resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} @@ -1885,6 +2011,10 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + pkce-challenge@5.0.1: + resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} + engines: {node: '>=16.20.0'} + postcss@8.5.32: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} @@ -1954,6 +2084,10 @@ packages: resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} engines: {node: '>=0.10.0'} + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + require-in-the-middle@8.0.1: resolution: {integrity: sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==} engines: {node: '>=9.3.0 || >=8.10.0 <9.0.0'} @@ -2048,6 +2182,14 @@ packages: resolution: {integrity: sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==} engines: {node: '>=20.9.0'} + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + side-channel-list@1.0.1: resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} engines: {node: '>= 0.4'} @@ -2284,6 +2426,11 @@ packages: whatwg-url@5.0.0: resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + why-is-node-running@3.2.1: resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} engines: {node: '>=20.11'} @@ -2371,6 +2518,14 @@ packages: youch@4.1.0-beta.10: resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} + zod-to-json-schema@3.25.2: + resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} + peerDependencies: + zod: ^3.25.28 || ^4 + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + snapshots: '@azure-rest/core-client@2.9.0': @@ -2631,6 +2786,8 @@ snapshots: transitivePeerDependencies: - supports-color + '@cfworker/json-schema@4.1.6': {} + '@cloudflare/workerd-darwin-64@1.20260730.1': optional: true @@ -2679,6 +2836,10 @@ snapshots: protobufjs: 7.6.6 yargs: 17.7.3 + '@hono/node-server@2.1.6(hono@4.13.17)': + dependencies: + hono: 4.13.17 + '@img/colour@1.1.0': {} '@img/sharp-darwin-arm64@0.35.2': @@ -2805,6 +2966,30 @@ snapshots: '@microsoft/applicationinsights-web-snippet@1.2.3': {} + '@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)': + dependencies: + '@hono/node-server': 2.1.6(hono@4.13.17) + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + content-type: 1.0.5 + cors: 2.8.6 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.1 + express: 5.3.0 + express-rate-limit: 8.7.3(express@5.3.0) + hono: 4.13.17 + jose: 6.2.15 + json-schema-typed: 8.0.2 + pkce-challenge: 5.0.1 + raw-body: 3.0.2 + zod: 4.6.7 + zod-to-json-schema: 3.25.2(zod@4.6.7) + optionalDependencies: + '@cfworker/json-schema': 4.1.6 + transitivePeerDependencies: + - supports-color + '@nodable/entities@3.1.0': {} '@opentelemetry/api-logs@0.211.0': @@ -3452,6 +3637,17 @@ snapshots: agent-base@7.1.4: {} + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.9 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + ansi-regex@5.0.1: {} ansi-styles@3.2.1: @@ -3650,6 +3846,8 @@ snapshots: content-disposition@2.0.1: {} + content-type@1.0.5: {} + content-type@2.1.0: {} cookie-signature@1.2.2: {} @@ -3658,6 +3856,17 @@ snapshots: cookie@1.1.1: {} + cors@2.8.6: + dependencies: + object-assign: 4.1.1 + vary: 1.1.2 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + debug@2.6.9: dependencies: ms: 2.0.0 @@ -3738,8 +3947,22 @@ snapshots: events@3.3.0: {} + eventsource-parser@3.1.1: {} + + eventsource@3.0.7: + dependencies: + eventsource-parser: 3.1.1 + expect-type@1.4.0: {} + express-rate-limit@8.7.3(express@5.3.0): + dependencies: + debug: 4.4.3 + express: 5.3.0 + ip-address: 10.7.6 + transitivePeerDependencies: + - supports-color + express@5.3.0: dependencies: accepts: 2.0.0 @@ -3773,6 +3996,10 @@ snapshots: transitivePeerDependencies: - supports-color + fast-deep-equal@3.1.3: {} + + fast-uri@3.1.9: {} + fast-xml-builder@1.3.1: dependencies: path-expression-matcher: 1.6.2 @@ -3884,6 +4111,8 @@ snapshots: dependencies: function-bind: 1.1.2 + hono@4.13.17: {} + http-errors@2.0.1: dependencies: depd: 2.0.0 @@ -3936,6 +4165,8 @@ snapshots: inherits@2.0.4: {} + ip-address@10.7.6: {} + ipaddr.js@1.9.1: {} is-docker@3.0.0: {} @@ -3960,8 +4191,16 @@ snapshots: dependencies: is-inside-container: 1.0.0 + isexe@2.0.0: {} + + jose@6.2.15: {} + js-md4@0.3.2: {} + json-schema-traverse@1.0.0: {} + + json-schema-typed@8.0.2: {} + jsonfile@6.2.1: dependencies: universalify: 2.0.1 @@ -4170,6 +4409,8 @@ snapshots: dependencies: whatwg-url: 5.0.0 + object-assign@4.1.1: {} + object-inspect@1.13.4: {} obug@3.0.0: {} @@ -4201,6 +4442,8 @@ snapshots: path-expression-matcher@1.6.2: {} + path-key@3.1.1: {} + path-to-regexp@8.4.2: {} pg-connection-string@2.14.1: {} @@ -4221,6 +4464,8 @@ snapshots: picomatch@4.0.7: {} + pkce-challenge@5.0.1: {} + postcss@8.5.32: dependencies: nanoid: 3.3.20 @@ -4294,6 +4539,8 @@ snapshots: require-directory@2.1.1: {} + require-from-string@2.0.2: {} + require-in-the-middle@8.0.1: dependencies: debug: 4.4.3 @@ -4433,6 +4680,12 @@ snapshots: '@img/sharp-win32-ia32': 0.35.2 '@img/sharp-win32-x64': 0.35.2 + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + side-channel-list@1.0.1: dependencies: es-errors: 1.3.0 @@ -4624,6 +4877,10 @@ snapshots: tr46: 0.0.3 webidl-conversions: 3.0.1 + which@2.0.2: + dependencies: + isexe: 2.0.0 + why-is-node-running@3.2.1: {} winston-transport@4.9.0: @@ -4717,3 +4974,9 @@ snapshots: '@speed-highlight/core': 1.2.24 cookie: 1.1.1 youch-core: 0.3.3 + + zod-to-json-schema@3.25.2(zod@4.6.7): + dependencies: + zod: 4.6.7 + + zod@4.6.7: {} diff --git a/scripts/agent-protocol-fixture.mjs b/scripts/agent-protocol-fixture.mjs new file mode 100644 index 0000000..7c99494 --- /dev/null +++ b/scripts/agent-protocol-fixture.mjs @@ -0,0 +1,1122 @@ +/** + * Executed ONLY after this file is copied into the isolated tarball consumer. + * Every component import below resolves through an installed public entrypoint. + * The existing browser login, limiter and staging runner remain fictional seams. + */ +import assert from "node:assert/strict"; +import { createHash, randomUUID } from "node:crypto"; +import { createServer } from "node:http"; +import { isDeepStrictEqual } from "node:util"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { + auth, + UnauthorizedError, +} from "@modelcontextprotocol/sdk/client/auth.js"; +import { + createAgentAccess, + createAgentAccessHttp, + createProtectedResourceAuthenticator, +} from "@pegma/agent-access"; +import { hasPermission, resolveAccess } from "@pegma/authorization-core"; +import { createKnowledgeBaseApplication } from "@pegma/knowledge-base-application"; +import { + articleKinds, + knowledgePermissions, +} from "@pegma/knowledge-base-contracts"; +import { + createKnowledgeAgentDispatcher, + createKnowledgeAgentHttp, + createKnowledgeAgentMcp, + knowledgeAgentScopes, + knowledgeAgentToolNames, +} from "@pegma/knowledge-base-mcp"; +import { createSessionStore } from "@pegma/sessions"; +import { createMemoryStore } from "@pegma/storage-core"; + +const CLIENT_ID = "fictional-pre-registered-kb-agent"; +const PRINCIPAL = "fictional/staff/admin"; +const RUNNER = "fictional/runner/loopback"; +const ATTESTER = "fictional/verifier/registry"; +const LINK = "agent.access.link"; +const COLLECTION = "fictional/collection/workshop"; +const ARTICLE = "fictional/article/export"; +const BUILD = "fictional-loopback-build-42"; +const COOKIE = "fictional_existing_session"; +const scopes = Object.values(knowledgeAgentScopes); +const command = (name, expectedGeneration) => ({ + commandId: `fictional/protocol/${name}`, + correlationId: "fictional/protocol-proof", + expectedGeneration, +}); +const guide = Object.freeze({ + kind: "walkthrough", + title: "Download a fictional workshop export", + summary: "Save the fictional workspace as a CSV spreadsheet.", + content: { + format: "markdown", + text: "1. Open Workspace.\n2. Choose Export.\n3. Download the CSV spreadsheet.", + }, + tags: ["export", "csv"], + applicability: { + productId: "fictional-workshop", + productVersion: "1.0", + buildId: BUILD, + locale: "en-US", + }, +}); +let stage = 0; + +async function request(url, init = {}) { + const timeout = AbortSignal.timeout(5_000); + return fetch(url, { + ...init, + signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout, + }); +} + +function response(status) { + return new Response(null, { + status, + headers: { + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + }, + }); +} + +async function formPost(url, values, headers = {}) { + return request(url, { + method: "POST", + redirect: "manual", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + ...headers, + }, + body: new URLSearchParams(values), + }); +} + +async function createHost() { + const store = createMemoryStore(); + let milliseconds = Date.now(); + let administrator = true; + const clock = { now: () => new Date(milliseconds).toISOString() }; + const currentAccess = () => + resolveAccess( + { principalId: PRINCIPAL, roles: administrator ? ["Admin"] : ["Viewer"] }, + { + version: "fictional-kb-protocol-1", + roles: { + Admin: [LINK, ...Object.values(knowledgePermissions)], + Viewer: [], + }, + }, + ); + const policy = { + id: "fictional/validation/workshop", + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: `${kind}-content`, + kind, + testKind: "content", + maxAgeMilliseconds: 60_000, + trustedRunnerIds: [RUNNER], + })), + { + id: "walkthrough-workflow", + kind: "walkthrough", + testKind: "workflow", + maxAgeMilliseconds: 60_000, + trustedRunnerIds: [RUNNER], + }, + ], + }; + const governance = { + validationPolicy: { id: policy.id, version: policy.version }, + expectedStagingBuildId: BUILD, + trustedAttesterIds: [ATTESTER], + }; + const executions = new Map(); + const counts = { + applicationCalls: 0, + authenticatedRequests: 0, + verifiedReceipts: 0, + callbacks: 0, + }; + stage = 11; + const application = createKnowledgeBaseApplication({ + store, + clock, + evidenceVerifier: { + async verify(proof) { + const execution = executions.get(proof.receipt); + if ( + !execution || + proof.access.principalId !== execution.actor || + execution.runner !== RUNNER || + execution.build !== BUILD || + !isDeepStrictEqual(proof.article, execution.article) || + !isDeepStrictEqual(proof.submission, execution.submission) || + !isDeepStrictEqual(proof.configuration, governance) + ) + return null; + counts.verifiedReceipts += 1; + return { + id: execution.id, + verifiedBy: ATTESTER, + verifiedAt: clock.now(), + }; + }, + }, + }); + // Bootstrap through the actual application. No public audience is enabled. + stage = 12; + const created = await application.createCollection(currentAccess(), { + ...command("bootstrap-collection", 0), + collectionId: COLLECTION, + name: "Fictional private workshop guides", + }); + stage = 13; + await application.putValidationPolicy(currentAccess(), { + ...command("bootstrap-validation", 0), + policy, + }); + stage = 14; + await application.putGovernanceConfiguration(currentAccess(), { + ...command("bootstrap-governance", created.value.generation), + collectionId: COLLECTION, + configuration: governance, + }); + + // An existing host login is the explicit fixture seam. Sessions owns records; + // this fixture implements neither credentials nor a login/identity provider. + stage = 15; + const sessions = createSessionStore(store, { clock }); + const sessionId = randomUUID(); + const csrf = randomUUID(); + await sessions.create(sessionId, { + principalId: PRINCIPAL, + data: JSON.stringify({ csrf }), + }); + const browserCookie = `${COOKIE}=${sessionId}`; + let origin = ""; + let route = async () => response(503); + const sockets = new Set(); + const server = createServer((incoming, outgoing) => { + void (async () => { + const chunks = []; + let bytes = 0; + for await (const chunk of incoming) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + bytes += buffer.byteLength; + if (bytes > 262_144) { + outgoing.writeHead(413); + outgoing.end(); + return; + } + chunks.push(buffer); + } + const headers = new Headers(); + for (const [name, value] of Object.entries(incoming.headers)) + if (value !== undefined) + headers.set(name, Array.isArray(value) ? value.join(", ") : value); + const method = incoming.method ?? "GET"; + const result = await route( + new Request(new URL(incoming.url ?? "/", origin), { + method, + headers, + ...(method === "GET" || method === "HEAD" + ? {} + : { body: Buffer.concat(chunks) }), + }), + ); + outgoing.writeHead(result.status, Object.fromEntries(result.headers)); + outgoing.end(Buffer.from(await result.arrayBuffer())); + })().catch(() => { + // Request URLs and errors can contain credentials. Never serialize them. + if (!outgoing.headersSent) outgoing.writeHead(503); + outgoing.end(); + }); + }); + server.on("connection", (socket) => { + sockets.add(socket); + socket.on("close", () => sockets.delete(socket)); + }); + server.requestTimeout = 5_000; + server.headersTimeout = 5_000; + async function close() { + for (const socket of sockets) socket.destroy(); + if (server.listening) + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + } + + try { + stage = 16; + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + server.off("error", reject); + resolve(); + }); + }); + const address = server.address(); + assert.ok(address && typeof address !== "string"); + origin = `http://127.0.0.1:${address.port}`; + const resource = `${origin}/mcp`; + const apiUrl = `${origin}/api/knowledge/v1`; + const redirectUri = `${origin}/native/callback`; + const configuration = { + issuer: origin, + resource, + allowInsecureLoopback: true, + approvalPermission: LINK, + endpoints: { + authorize: `${origin}/authorize`, + deviceAuthorization: `${origin}/device_authorization`, + token: `${origin}/token`, + revocation: `${origin}/revoke`, + verification: `${origin}/host/device`, + approval: `${origin}/host/consent`, + resourceMetadata: `${origin}/.well-known/oauth-protected-resource/mcp`, + }, + clients: [ + { + clientId: CLIENT_ID, + name: "Fictional SDK knowledge author", + redirectUris: [redirectUri], + allowedScopes: scopes, + grantTypes: ["authorization_code", "device_code"], + }, + ], + scopes: scopes.map((name) => ({ + name, + description: `Fictional KB permission ${name}`, + version: "1", + permissions: [name], + })), + limits: { accessLifetimeSeconds: 30, deviceLifetimeSeconds: 60 }, + }; + stage = 17; + const service = createAgentAccess({ + configuration, + store, + clock, + resolvePrincipal: async (principalId) => + principalId === PRINCIPAL ? currentAccess() : null, + }); + async function authenticateBrowser(browserRequest, options) { + const cookies = (browserRequest.headers.get("Cookie") ?? "") + .split(";") + .map((part) => part.trim()); + const candidates = cookies.filter((part) => + part.startsWith(`${COOKIE}=`), + ); + if (candidates.length !== 1) return response(401); + const session = await sessions.get( + candidates[0].slice(COOKIE.length + 1), + ); + if (!session || session.principalId !== PRINCIPAL) return response(401); + const access = currentAccess(); + if (!hasPermission(access, LINK)) return response(403); + if (options.mutation) { + let saved; + try { + saved = JSON.parse(session.data); + } catch { + return response(503); + } + if (!saved || typeof saved.csrf !== "string" || !saved.csrf) + return response(503); + if ( + browserRequest.headers.get("Origin") !== origin || + browserRequest.headers.get("X-CSRF-Token") !== saved.csrf + ) + return response(403); + } + return { authentication: "browser-session", access }; + } + // Required injection, explicitly synthetic: no real limiter acceptance claim. + const limit = async () => true; + const issuer = createAgentAccessHttp({ + service, + configuration, + authenticateBrowser, + limit, + }); + const authenticator = createProtectedResourceAuthenticator({ + service, + configuration, + }); + const trackedApplication = Object.fromEntries( + [ + "getDraft", + "createDraft", + "updateDraft", + "getValidationRequirements", + "submitEvidence", + ].map((method) => [ + method, + async (...arguments_) => { + counts.applicationCalls += 1; + return application[method](...arguments_); + }, + ]), + ); + stage = 18; + const dispatcher = createKnowledgeAgentDispatcher({ + application: trackedApplication, + resource, + }); + const common = { + resource, + protectedResourceMetadataUrl: configuration.endpoints.resourceMetadata, + allowedOrigins: [origin], + allowInsecureLoopback: true, + limit, + async authenticate(protectedRequest) { + // Agent Access rechecks current principal, client, exact resource, expiry, + // revocation and selected permissions on EVERY transport call and retry. + const delegated = await authenticator.authenticate(protectedRequest); + if (delegated instanceof Response) return delegated; + counts.authenticatedRequests += 1; + return { + access: delegated.access, + scopes: delegated.scopes, + clientId: delegated.clientId, + resource: delegated.resource, + }; + }, + }; + const mcp = createKnowledgeAgentMcp({ + ...common, + mcpUrl: resource, + dispatcher, + }); + const http = createKnowledgeAgentHttp({ ...common, apiUrl, dispatcher }); + // Same actual issuer/store, distinct resource. The fixture obtains this + // credential through Agent Access's public device API, never by making up + // token bytes, then presents it to the real KB HTTP and MCP boundaries. + const otherResource = `${origin}/other-resource`; + const otherService = createAgentAccess({ + configuration: { ...configuration, resource: otherResource }, + store, + clock, + resolvePrincipal: async (principalId) => + principalId === PRINCIPAL ? currentAccess() : null, + }); + route = async (incoming) => { + const url = new URL(incoming.url); + if (url.pathname === "/native/callback" && incoming.method === "GET") { + counts.callbacks += 1; + return response(200); + } + if ( + ["/host/consent", "/host/device"].includes(url.pathname) && + incoming.method === "GET" + ) { + const browser = await authenticateBrowser(incoming, { + mutation: false, + }); + if (browser instanceof Response) return browser; + const userCode = url.searchParams.get("user_code"); + const view = + url.pathname === "/host/consent" + ? await service.getAuthorizationApproval( + browser, + url.searchParams.get("request_id") ?? "", + ) + : userCode + ? await service.getDeviceApproval(browser, userCode) + : null; + return Response.json( + { syntheticBrowser: true, view }, + { headers: { "Cache-Control": "no-store" } }, + ); + } + if (url.pathname === "/host/approve" && incoming.method === "POST") { + const form = new URLSearchParams(await incoming.text()); + if ( + [...new Set(form.keys())].some((key) => form.getAll(key).length !== 1) + ) + return response(400); + const browserRequest = new Request(incoming.url, { + method: "POST", + headers: incoming.headers, + }); + browserRequest.headers.set("X-CSRF-Token", form.get("csrf") ?? ""); + const browser = await authenticateBrowser(browserRequest, { + mutation: true, + }); + if (browser instanceof Response) return browser; + const userCode = form.get("user_code"); + const view = userCode + ? await service.getDeviceApproval(browser, userCode) + : await service.getAuthorizationApproval( + browser, + form.get("request_id") ?? "", + ); + const decision = form.get("decision"); + if (decision !== "approve" && decision !== "deny") return response(400); + const result = await service.approve(browser, { + requestId: view.requestId, + decision, + approvedScopes: view.requestedScopes.map(({ name }) => name), + ...(userCode ? { userCode } : {}), + }); + return result.flow === "authorization_code" + ? new Response(null, { + status: 303, + headers: { + Location: result.redirectUri, + "Cache-Control": "no-store", + }, + }) + : response(200); + } + return ( + (await mcp.handle(incoming)) ?? + (await http.handle(incoming)) ?? + (await issuer.handle(incoming)) ?? + response(404) + ); + }; + + return { + origin, + resource, + apiUrl, + redirectUri, + configuration, + counts, + browser: { cookie: browserCookie, csrf }, + close, + advance: (seconds) => { + milliseconds += seconds * 1_000; + }, + demote: () => { + administrator = false; + }, + async wrongResourceCredential() { + const issued = await otherService.beginDeviceAuthorization({ + clientId: CLIENT_ID, + resource: otherResource, + scopes, + }); + const browser = { + authentication: "browser-session", + access: currentAccess(), + }; + const view = await otherService.getDeviceApproval( + browser, + issued.user_code, + ); + await otherService.approve(browser, { + requestId: view.requestId, + decision: "approve", + approvedScopes: scopes, + userCode: issued.user_code, + }); + return otherService.pollDeviceToken({ + clientId: CLIENT_ID, + resource: otherResource, + deviceCode: issued.device_code, + }); + }, + executeFixtureCheck(current) { + // A trusted fictional runner recognizes this exact fixture and executes + // an independent CSV export check. It accepts no claimed pass/result, + // runner identity, submission, artifact or receipt from its caller. + assert.equal(current.articleId, ARTICLE); + assert.equal(current.revision.number, 2); + assert.equal(current.revision.createdBy, PRINCIPAL); + assert.equal(current.revision.applicability.buildId, BUILD); + assert.deepEqual(current.revision.content, guide.content); + const rows = [ + ["workspace", "records"], + ["fictional-workshop", "3"], + ]; + const csv = rows.map((row) => row.join(",")).join("\n"); + assert.equal(csv, "workspace,records\nfictional-workshop,3"); + const artifactHash = createHash("sha256").update(csv).digest("hex"); + const submission = { + id: "fictional/evidence/content", + articleId: ARTICLE, + articleRevision: current.revision.number, + contentHash: current.revision.contentHash, + validationPolicy: current.revision.validationPolicy, + checkId: "walkthrough-content", + testKind: "content", + applicability: current.revision.applicability, + stagingBuildId: BUILD, + steps: [ + "SYNTHETIC_PRIVATE_EVIDENCE: exact fictional CSV export verified locally.", + ], + result: "passed", + executedAt: clock.now(), + runnerId: RUNNER, + artifacts: [ + { id: "fictional/private/csv-output", hash: artifactHash }, + ], + }; + const receipt = randomUUID(); + executions.set( + receipt, + structuredClone({ + id: "fictional/attestation/execution-1", + actor: PRINCIPAL, + runner: RUNNER, + build: BUILD, + article: current.revision, + submission, + }), + ); + return { evidence: structuredClone(submission), receipt }; + }, + }; + } catch (error) { + await close(); + throw error; + } +} + +function createProvider(host) { + let savedTokens; + let verifier; + let authorizationUrl; + let discovery; + const state = randomUUID(); + const provider = { + redirectUrl: host.redirectUri, + clientMetadata: { + client_name: "Fictional packed KB SDK proof", + redirect_uris: [host.redirectUri], + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: "none", + scope: scopes.join(" "), + }, + clientInformation: () => ({ + client_id: CLIENT_ID, + issuer: host.configuration.issuer, + }), + state: () => state, + tokens: () => savedTokens, + saveTokens: (value) => { + savedTokens = value; + }, + saveCodeVerifier: (value) => { + verifier = value; + }, + codeVerifier: () => { + assert.ok(verifier); + return verifier; + }, + redirectToAuthorization: (value) => { + authorizationUrl = value; + }, + discoveryState: () => discovery, + saveDiscoveryState: (value) => { + discovery = value; + }, + invalidateCredentials: (kind) => { + if (kind === "all" || kind === "tokens") savedTokens = undefined; + }, + }; + return { + provider, + tokens: () => { + assert.ok(savedTokens); + return savedTokens; + }, + authorizationUrl: () => { + assert.ok(authorizationUrl); + return authorizationUrl; + }, + discovery: () => { + assert.ok(discovery); + return discovery; + }, + callbackCode(callback) { + assert.equal(callback.origin, host.origin); + assert.equal(callback.pathname, "/native/callback"); + for (const key of ["code", "state", "iss"]) + assert.equal(callback.searchParams.getAll(key).length, 1); + assert.equal(callback.searchParams.has("error"), false); + assert.equal(callback.searchParams.get("state"), state); + assert.equal(callback.searchParams.get("iss"), host.configuration.issuer); + const code = callback.searchParams.get("code"); + assert.ok(code); + return code; + }, + }; +} + +async function approve(host, authorizationUrl, checkProtections = false) { + assert.equal(authorizationUrl.origin, host.origin); + assert.equal(authorizationUrl.pathname, "/authorize"); + assert.equal( + authorizationUrl.searchParams.get("code_challenge_method"), + "S256", + ); + assert.equal(authorizationUrl.searchParams.get("resource"), host.resource); + assert.equal(authorizationUrl.searchParams.get("client_id"), CLIENT_ID); + if (checkProtections) { + const missing = await request(authorizationUrl, { redirect: "manual" }); + assert.equal(missing.status, 401); + await missing.body?.cancel(); + } + const started = await request(authorizationUrl, { + redirect: "manual", + headers: { Cookie: host.browser.cookie }, + }); + assert.equal(started.status, 303); + const consent = new URL(started.headers.get("Location"), host.origin); + assert.equal(consent.origin, host.origin); + assert.equal(consent.pathname, "/host/consent"); + const consentPage = await request(consent, { + headers: { Cookie: host.browser.cookie }, + }); + assert.equal(consentPage.status, 200); + const view = (await consentPage.json()).view; + assert.equal(view.resource, host.resource); + assert.deepEqual( + view.requestedScopes.map(({ name }) => name).sort(), + [...scopes].sort(), + ); + const values = { + request_id: consent.searchParams.get("request_id"), + decision: "approve", + csrf: host.browser.csrf, + }; + if (checkProtections) { + assert.equal( + ( + await formPost(`${host.origin}/host/approve`, values, { + Cookie: host.browser.cookie, + Origin: "https://foreign.example.test", + }) + ).status, + 403, + ); + assert.equal( + ( + await formPost( + `${host.origin}/host/approve`, + { ...values, csrf: "incorrect" }, + { Cookie: host.browser.cookie, Origin: host.origin }, + ) + ).status, + 403, + ); + } + const approved = await formPost(`${host.origin}/host/approve`, values, { + Cookie: host.browser.cookie, + Origin: host.origin, + }); + assert.equal(approved.status, 303); + const callback = new URL(approved.headers.get("Location")); + assert.equal(callback.origin, host.origin); + assert.equal(callback.pathname, "/native/callback"); + const completed = await request(callback); + assert.equal(completed.status, 200); + await completed.body?.cancel(); + return callback; +} + +async function httpCall(host, token, operation, input) { + return request(host.apiUrl, { + method: "POST", + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ apiVersion: "1", operation, input }), + }); +} + +async function mcpCall(client, operation, input) { + const result = await client.callTool( + { name: knowledgeAgentToolNames[operation], arguments: input }, + undefined, + { timeout: 5_000 }, + ); + assert.equal(result.content.length, 1); + assert.equal(result.content[0].type, "text"); + return JSON.parse(result.content[0].text); +} + +async function rejectedCredential(host, token, replay) { + const before = host.counts.applicationCalls; + const http = await httpCall(host, token, "createDraft", replay); + assert.equal(http.status, 401); + assert.ok( + http.headers.get("WWW-Authenticate")?.includes("resource_metadata="), + ); + await http.body?.cancel(); + const mcp = await request(host.resource, { + method: "POST", + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 99, + method: "tools/call", + params: { name: knowledgeAgentToolNames.createDraft, arguments: replay }, + }), + }); + assert.equal(mcp.status, 401); + await mcp.body?.cancel(); + assert.equal(host.counts.applicationCalls, before); +} + +async function authorization(host, owned, checkProtections = false) { + const provider = createProvider(host); + const initial = new StreamableHTTPClientTransport(new URL(host.resource), { + authProvider: provider.provider, + fetch: request, + }); + const bootstrap = new Client( + { name: "fictional-kb-sdk-proof", version: "1.0.0" }, + { capabilities: {} }, + ); + bootstrap.onerror = () => {}; + owned.push(initial, bootstrap); + let redirected = false; + try { + await bootstrap.connect(initial); + } catch (error) { + assert.ok(error instanceof UnauthorizedError); + redirected = true; + } + assert.equal(redirected, true); + const callback = await approve( + host, + provider.authorizationUrl(), + checkProtections, + ); + const code = provider.callbackCode(callback); + await initial.finishAuth(code); + assert.equal(provider.discovery().resourceMetadata.resource, host.resource); + assert.equal( + provider.discovery().authorizationServerMetadata.issuer, + host.configuration.issuer, + ); + const transport = new StreamableHTTPClientTransport(new URL(host.resource), { + authProvider: provider.provider, + fetch: request, + }); + const client = new Client( + { name: "fictional-kb-sdk-proof", version: "1.0.0" }, + { capabilities: {} }, + ); + client.onerror = () => {}; + owned.push(transport, client); + await client.connect(transport); + return { ...provider, client }; +} + +async function deviceProof(host) { + const issuance = await formPost( + host.configuration.endpoints.deviceAuthorization, + { + client_id: CLIENT_ID, + resource: host.resource, + scope: scopes.join(" "), + }, + ); + assert.equal(issuance.status, 200); + const device = await issuance.json(); + const verification = new URL(device.verification_uri); + assert.equal(verification.origin, host.origin); + verification.searchParams.set("user_code", device.user_code); + const page = await request(verification, { + headers: { Cookie: host.browser.cookie }, + }); + assert.equal(page.status, 200); + assert.equal((await page.json()).view.resource, host.resource); + const poll = () => + formPost(host.configuration.endpoints.token, { + grant_type: "urn:ietf:params:oauth:grant-type:device_code", + client_id: CLIENT_ID, + resource: host.resource, + device_code: device.device_code, + }); + assert.equal((await (await poll()).json()).error, "authorization_pending"); + assert.equal((await (await poll()).json()).error, "slow_down"); + const approved = await formPost( + `${host.origin}/host/approve`, + { + user_code: device.user_code, + decision: "approve", + csrf: host.browser.csrf, + }, + { Cookie: host.browser.cookie, Origin: host.origin }, + ); + assert.equal(approved.status, 200); + host.advance(device.interval + 5); + const exchanged = await poll(); + assert.equal(exchanged.status, 200); + const tokens = await exchanged.json(); + const read = await httpCall(host, tokens.access_token, "getDraft", { + articleId: ARTICLE, + }); + assert.equal(read.status, 200); + assert.equal((await read.json()).result.revision.number, 2); + return { pending: true, slowDown: true, protectedRead: true }; +} + +async function runProof() { + stage = 10; + const host = await createHost(); + const owned = []; + try { + stage = 20; + const session = await authorization(host, owned, true); + stage = 30; + const tools = await session.client.listTools(); + assert.deepEqual( + tools.tools.map(({ name }) => name).sort(), + Object.values(knowledgeAgentToolNames).sort(), + ); + assert.equal(tools.tools.length, 5); + const creation = { + ...command("draft-create", 0), + articleId: ARTICLE, + collectionId: COLLECTION, + draft: guide, + }; + const created = await mcpCall(session.client, "createDraft", creation); + assert.equal(created.result.replayed, false); + assert.equal(created.result.value.articleRevision, 1); + const retry = await httpCall( + host, + session.tokens().access_token, + "createDraft", + creation, + ); + assert.equal(retry.status, 200); + const retried = await retry.json(); + assert.deepEqual(retried.result.value, created.result.value); + assert.equal(retried.result.replayed, true); + const retryAgain = await mcpCall(session.client, "createDraft", creation); + assert.deepEqual(retryAgain, retried); + const read = await mcpCall(session.client, "getDraft", { + articleId: ARTICLE, + }); + assert.equal(read.result.revision.createdBy, PRINCIPAL); + const httpRead = await httpCall( + host, + session.tokens().access_token, + "getDraft", + { articleId: ARTICLE }, + ); + assert.equal(httpRead.status, 200); + assert.deepEqual(await httpRead.json(), read); + const update = { + ...command("draft-update", read.result.generation), + articleId: ARTICLE, + collectionId: COLLECTION, + draft: { + ...guide, + summary: "Save the exact fictional workspace as a CSV spreadsheet.", + }, + }; + const updated = await mcpCall(session.client, "updateDraft", update); + assert.equal(updated.result.value.articleRevision, 2); + const current = ( + await mcpCall(session.client, "getDraft", { articleId: ARTICLE }) + ).result; + stage = 40; + const requirementsInput = { collectionId: COLLECTION, kind: "walkthrough" }; + const requirements = await mcpCall( + session.client, + "getValidationRequirements", + requirementsInput, + ); + assert.equal(requirements.result.expectedStagingBuildId, BUILD); + assert.equal(requirements.result.checks.length, 2); + const httpRequirements = await httpCall( + host, + session.tokens().access_token, + "getValidationRequirements", + requirementsInput, + ); + assert.deepEqual(await httpRequirements.json(), requirements); + assert.equal("trustedAttesterIds" in requirements.result, false); + assert.equal("trustedRunnerIds" in requirements.result.checks[0], false); + const execution = host.executeFixtureCheck(current); + const submission = { + ...command("evidence-submit", current.generation), + articleId: ARTICLE, + ...execution, + }; + // A registered receipt cannot authenticate modified result/runner/build or + // any other evidence field. Compare every complete submission field below. + const forgeries = [ + { ...execution.evidence, runnerId: "fictional/runner/impostor" }, + { ...execution.evidence, stagingBuildId: "fictional-other-build" }, + { ...execution.evidence, result: "failed" }, + { ...execution.evidence, steps: ["forged caller assertion"] }, + { + ...execution.evidence, + artifacts: [{ id: "forged", hash: "f".repeat(64) }], + }, + ]; + for (const [index, evidence] of forgeries.entries()) { + const forged = await mcpCall(session.client, "submitEvidence", { + ...submission, + ...command(`forged-evidence-${index}`, current.generation), + evidence, + }); + assert.ok(forged.error); + } + const submitted = await mcpCall( + session.client, + "submitEvidence", + submission, + ); + assert.equal(submitted.result.replayed, false); + assert.equal(submitted.result.value.articleRevision, 2); + const evidenceRetry = await httpCall( + host, + session.tokens().access_token, + "submitEvidence", + submission, + ); + const acknowledgement = await evidenceRetry.json(); + assert.deepEqual(acknowledgement.result.value, submitted.result.value); + assert.equal(acknowledgement.result.replayed, true); + assert.ok(host.counts.verifiedReceipts > 0); + const safeDraft = await mcpCall(session.client, "getDraft", { + articleId: ARTICLE, + }); + for (const forbidden of [ + "evidence", + "attestation", + "provenance", + "review", + "published", + ]) + assert.equal(forbidden in safeDraft.result, false); + assert.equal( + JSON.stringify(safeDraft).includes("SYNTHETIC_PRIVATE_EVIDENCE"), + false, + ); + + stage = 50; + const wrongResource = await host.wrongResourceCredential(); + await rejectedCredential(host, wrongResource.access_token, creation); + + const badPkce = createProvider(host); + assert.equal( + await auth(badPkce.provider, { + serverUrl: host.resource, + fetchFn: request, + }), + "REDIRECT", + ); + const callback = await approve(host, badPkce.authorizationUrl()); + const rejected = await formPost(host.configuration.endpoints.token, { + grant_type: "authorization_code", + client_id: CLIENT_ID, + resource: host.resource, + redirect_uri: host.redirectUri, + code: badPkce.callbackCode(callback), + code_verifier: "Z".repeat(43), + }); + assert.equal(rejected.status, 400); + assert.equal((await rejected.json()).error, "invalid_grant"); + + stage = 60; + const initialTokens = session.tokens(); + host.advance(31); + await rejectedCredential(host, initialTokens.access_token, creation); + assert.equal( + await auth(session.provider, { + serverUrl: host.resource, + fetchFn: request, + }), + "AUTHORIZED", + ); + const rotated = session.tokens(); + assert.notEqual(rotated.access_token, initialTokens.access_token); + assert.notEqual(rotated.refresh_token, initialTokens.refresh_token); + const afterRefresh = await httpCall( + host, + rotated.access_token, + "getDraft", + { articleId: ARTICLE }, + ); + assert.equal(afterRefresh.status, 200); + await afterRefresh.body?.cancel(); + const revoked = await formPost(host.configuration.endpoints.revocation, { + client_id: CLIENT_ID, + token: rotated.refresh_token, + token_type_hint: "refresh_token", + }); + assert.equal(revoked.status, 200); + await rejectedCredential(host, rotated.access_token, creation); + + stage = 70; + const device = await deviceProof(host); + stage = 80; + const fresh = await authorization(host, owned); + host.demote(); + await rejectedCredential(host, fresh.tokens().access_token, creation); + return { + passed: true, + liveHostsProven: false, + targetClientAppsProven: 0, + sdkDiscovery: true, + s256Pkce: true, + browserSession: true, + csrfAndOrigin: true, + callbackHops: host.counts.callbacks, + tools: tools.tools.length, + draftRevision: 2, + exactReceipt: true, + tamperedReceiptsRejected: forgeries.length, + httpMcpParity: true, + replayAcknowledgements: true, + privateEvidenceExcluded: true, + wrongResourceRejected: true, + wrongPkceRejected: true, + expiredRejected: true, + refreshRotated: true, + revokedRejected: true, + adminDemotionRejected: true, + device, + }; + } finally { + // Reverse ownership order closes native client transports before listener. + // No component-owned MCP resource escapes a request in the stateless adapter. + let cleanupFailed = false; + try { + for (const resource of owned.reverse()) { + try { + await resource.close(); + } catch { + cleanupFailed = true; + } + } + } finally { + await host.close(); + } + assert.equal(cleanupFailed, false, "Native client cleanup failed."); + } +} + +try { + console.log(JSON.stringify(await runProof())); +} catch { + console.error(JSON.stringify({ passed: false, stage })); + process.exitCode = 1; +} diff --git a/scripts/agent-protocol-proof.mjs b/scripts/agent-protocol-proof.mjs new file mode 100644 index 0000000..f7efabf --- /dev/null +++ b/scripts/agent-protocol-proof.mjs @@ -0,0 +1,295 @@ +/** TEST ONLY: immutable public producer -> packed consumer -> loopback SDK proof. */ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { + access, + copyFile, + mkdir, + mkdtemp, + readFile, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, delimiter, dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const reviewedAgentAccess = "a444e2113db98455b638b2ef8aa7c2faccb16b62"; +const publicProducer = "https://github.com/pegma-dev/agent-access.git"; +const packageManagerVersion = "10.34.5"; +const packages = ["contracts", "core", "application", "mcp"]; +let stage = 0; +let fixtureStage; + +function run(command, arguments_, cwd, env = process.env) { + const result = spawnSync(command, arguments_, { + cwd, + env, + shell: false, + encoding: "utf8", + timeout: 600_000, + maxBuffer: 16 * 1024 * 1024, + windowsHide: true, + }); + // Native command output can contain URLs or credentials. Never relay it. + if (stage === 5 && result.status !== 0) { + try { + const failure = JSON.parse(result.stderr.trim()); + if (failure.passed === false && Number.isSafeInteger(failure.stage)) + fixtureStage = failure.stage; + } catch { + /* Suppress every non-receipt command diagnostic. */ + } + } + assert.equal(result.error, undefined, "Proof command could not complete."); + assert.equal(result.status, 0, "Proof command failed."); + return result.stdout.trim(); +} + +async function exists(path) { + try { + await access(path); + return true; + } catch { + return false; + } +} + +async function npmCliPath() { + const directories = [ + dirname(process.execPath), + ...(process.env.PATH ?? "").split(delimiter).filter(Boolean), + ]; + const candidates = directories.map((directory) => + join(directory, "node_modules", "npm", "bin", "npm-cli.js"), + ); + if (basename(process.env.npm_execpath ?? "") === "npm-cli.js") + candidates.unshift(process.env.npm_execpath); + for (const directory of directories) { + const executable = join(directory, "npm"); + if (await exists(executable)) { + const target = await realpath(executable); + if (basename(target) === "npm-cli.js") candidates.push(target); + } + } + for (const candidate of candidates) + if (await exists(candidate)) return candidate; + throw new Error("npm CLI unavailable."); +} + +async function pack(directory, destination, expectedName, npm, env) { + const records = JSON.parse( + run( + process.execPath, + [npm, "pack", "--json", "--pack-destination", destination], + directory, + env, + ), + ); + assert.equal(records.length, 1); + const artifact = records[0]; + assert.equal(artifact.name, expectedName); + assert.equal(basename(artifact.filename), artifact.filename); + assert.ok(artifact.files.some(({ path }) => path === "dist/index.js")); + assert.ok(artifact.files.some(({ path }) => path === "README.md")); + assert.ok(artifact.files.some(({ path }) => path === "LICENSE")); + assert.ok(!artifact.files.some(({ path }) => /\.(test|spec)\./u.test(path))); + return [ + artifact.name, + pathToFileURL(join(destination, artifact.filename)).href, + ]; +} + +function safeReceipt(value) { + assert.ok( + value !== null && typeof value === "object" && !Array.isArray(value), + ); + for (const entry of Object.values(value)) { + if (entry !== null && typeof entry === "object") safeReceipt(entry); + else assert.ok(typeof entry === "boolean" || Number.isSafeInteger(entry)); + } + return value; +} + +async function proof() { + const temporaryParent = await realpath(tmpdir()); + const temporary = await mkdtemp( + join(temporaryParent, "pegma-kb-agent-proof-"), + ); + try { + stage = 1; + const npm = await npmCliPath(); + const npmrc = join(temporary, "npmrc"); + await writeFile(npmrc, "registry=https://registry.npmjs.org/\n"); + let env = { + ...process.env, + npm_config_userconfig: npmrc, + npm_config_registry: "https://registry.npmjs.org/", + }; + // Pin the producer's toolchain even when invoked directly with `node`. + const toolchain = join(temporary, "toolchain"); + await mkdir(toolchain); + await writeFile(join(toolchain, "package.json"), '{"private":true}\n'); + run( + process.execPath, + [ + npm, + "install", + "--ignore-scripts", + "--package-lock=false", + "--no-audit", + "--no-fund", + `pnpm@${packageManagerVersion}`, + ], + toolchain, + env, + ); + const pnpm = join(toolchain, "node_modules", "pnpm", "bin", "pnpm.cjs"); + assert.equal( + run(process.execPath, [pnpm, "--version"], toolchain, env), + packageManagerVersion, + ); + const inheritedPath = + Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] ?? + ""; + env = Object.fromEntries( + Object.entries(env).filter(([key]) => key.toLowerCase() !== "path"), + ); + env.PATH = `${join(toolchain, "node_modules", ".bin")}${delimiter}${inheritedPath}`; + + stage = 2; + // The repository release checker builds/packs and verifies all four KB + // inventories and their clean-consumer public entrypoints first. + run(process.execPath, [pnpm, "run", "release:check"], root, env); + const artifacts = join(temporary, "artifacts"); + await mkdir(artifacts); + const dependencies = []; + for (const directory of packages) { + dependencies.push( + await pack( + join(root, "packages", directory), + artifacts, + `@pegma/knowledge-base-${directory}`, + npm, + env, + ), + ); + } + + stage = 3; + const suppliedSource = process.env.AGENT_ACCESS_SOURCE; + if (suppliedSource) { + // Read only. Clone committed Git objects; never copy a dirty source tree + // or install/build in the user's checkout. + assert.equal( + run("git", ["rev-parse", "HEAD"], suppliedSource, env), + reviewedAgentAccess, + ); + } + const producer = join(temporary, "agent-access-producer"); + run( + "git", + [ + "clone", + "--no-local", + "--no-checkout", + suppliedSource ?? publicProducer, + producer, + ], + temporary, + env, + ); + run("git", ["checkout", "--detach", reviewedAgentAccess], producer, env); + assert.equal( + run("git", ["rev-parse", "HEAD"], producer, env), + reviewedAgentAccess, + ); + const manifest = JSON.parse( + await readFile(join(producer, "package.json"), "utf8"), + ); + assert.equal(manifest.packageManager, `pnpm@${packageManagerVersion}`); + run( + process.execPath, + [pnpm, "install", "--frozen-lockfile"], + producer, + env, + ); + run(process.execPath, [pnpm, "run", "build"], producer, env); + dependencies.push( + await pack( + join(producer, "packages", "agent-access"), + artifacts, + "@pegma/agent-access", + npm, + env, + ), + ); + + stage = 4; + const consumer = join(temporary, "consumer"); + await mkdir(consumer); + await writeFile( + join(consumer, "package.json"), + JSON.stringify({ + name: "pegma-kb-packed-agent-protocol-proof", + private: true, + type: "module", + dependencies: { + ...Object.fromEntries(dependencies), + "@modelcontextprotocol/sdk": "1.32.2", + "@pegma/sessions": "0.2.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/storage-core": "0.4.0", + "@pegma/spine": "0.1.2", + }, + }), + ); + run( + process.execPath, + [ + npm, + "install", + "--ignore-scripts", + "--package-lock=false", + "--no-audit", + "--no-fund", + ], + consumer, + env, + ); + await copyFile( + join(root, "scripts", "agent-protocol-fixture.mjs"), + join(consumer, "proof.mjs"), + ); + stage = 5; + const receipt = safeReceipt( + JSON.parse(run(process.execPath, ["proof.mjs"], consumer, env)), + ); + assert.equal(receipt.passed, true); + return { + packedPackages: dependencies.length, + immutableProducer: true, + ...receipt, + }; + } finally { + const cleanup = await realpath(temporary); + assert.equal(dirname(cleanup), temporaryParent); + assert.ok(basename(cleanup).startsWith("pegma-kb-agent-proof-")); + await rm(cleanup, { recursive: true, force: true }); + } +} + +try { + console.log(JSON.stringify(await proof())); +} catch { + console.error( + JSON.stringify({ + passed: false, + stage, + ...(fixtureStage === undefined ? {} : { fixtureStage }), + }), + ); + process.exitCode = 1; +} diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index fec8277..947d212 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -17,9 +17,30 @@ import { fileURLToPath, pathToFileURL } from "node:url"; const root = fileURLToPath(new URL("../", import.meta.url)); const packages = [ - { directory: "contracts", name: "@pegma/knowledge-base-contracts" }, - { directory: "core", name: "@pegma/knowledge-base-core" }, - { directory: "application", name: "@pegma/knowledge-base-application" }, + { + directory: "contracts", + name: "@pegma/knowledge-base-contracts", + runtimeExport: "knowledgePermissions", + runtimeExportType: "object", + }, + { + directory: "core", + name: "@pegma/knowledge-base-core", + runtimeExport: "createArticle", + runtimeExportType: "function", + }, + { + directory: "application", + name: "@pegma/knowledge-base-application", + runtimeExport: "createKnowledgeBaseApplication", + runtimeExportType: "function", + }, + { + directory: "mcp", + name: "@pegma/knowledge-base-mcp", + runtimeExport: "createKnowledgeAgentDispatcher", + runtimeExportType: "function", + }, ]; const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; @@ -105,18 +126,28 @@ async function validatePackages() { }); assert.deepEqual( manifest.dependencies, - specification.directory === "application" + specification.directory === "mcp" ? { - "@pegma/audit": "0.2.0", + "@cfworker/json-schema": "4.1.6", + "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", + "@pegma/knowledge-base-application": manifest.version, "@pegma/knowledge-base-contracts": manifest.version, "@pegma/knowledge-base-core": manifest.version, - "@pegma/spine": "0.1.2", - "@pegma/storage-core": "0.4.0", + zod: "4.6.7", } - : specification.directory === "core" - ? { "@pegma/knowledge-base-contracts": manifest.version } - : { "@pegma/spine": "0.1.2" }, + : specification.directory === "application" + ? { + "@pegma/audit": "0.2.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/knowledge-base-contracts": manifest.version, + "@pegma/knowledge-base-core": manifest.version, + "@pegma/spine": "0.1.2", + "@pegma/storage-core": "0.4.0", + } + : specification.directory === "core" + ? { "@pegma/knowledge-base-contracts": manifest.version } + : { "@pegma/spine": "0.1.2" }, ); for (const document of ["README.md", "LICENSE"]) { const content = await readFile(join(directory, document), "utf8"); @@ -250,9 +281,80 @@ async function prepare(mode) { [ "--input-type=module", "--eval", - packages - .map(({ name }) => `await import(${JSON.stringify(name)});`) - .join("\n"), + [ + 'import assert from "node:assert/strict";', + 'import { readFile } from "node:fs/promises";', + 'import { createMemoryStore } from "@pegma/storage-core";', + 'import { createKnowledgeBaseApplication } from "@pegma/knowledge-base-application";', + 'import { createKnowledgeAgentDispatcher, createKnowledgeAgentMcp } from "@pegma/knowledge-base-mcp";', + ...packages.map( + ({ name, runtimeExport, runtimeExportType }, index) => + `const package${index} = await import(${JSON.stringify(name)});\nassert.equal(typeof package${index}[${JSON.stringify(runtimeExport)}], ${JSON.stringify(runtimeExportType)});`, + ), + ` +const mcpManifest = JSON.parse(await readFile( + new URL("../package.json", import.meta.resolve("@pegma/knowledge-base-mcp")), + "utf8", +)); +const resource = "https://knowledge-artifact.example/mcp"; +const application = createKnowledgeBaseApplication({ + store: createMemoryStore(), + clock: { now: () => "2026-11-07T12:00:00.000Z" }, +}); +const dispatcher = createKnowledgeAgentDispatcher({ application, resource }); +const identity = { + clientId: "synthetic-artifact-client", + resource, + scopes: [], + access: { + principalId: "synthetic/artifact-principal", + policyVersion: "synthetic-artifact-policy-1", + roles: [], + entitlements: [], + permissions: [], + }, +}; +const mcp = createKnowledgeAgentMcp({ + dispatcher, + resource, + mcpUrl: resource, + protectedResourceMetadataUrl: + "https://knowledge-artifact.example/.well-known/oauth-protected-resource/mcp", + allowedOrigins: [], + limit: () => true, + authenticate(request) { + assert.equal(request.headers.get("Authorization"), "Bearer synthetic-artifact-smoke"); + return identity; + }, +}); +const initialized = await mcp.handle(new Request(resource, { + method: "POST", + headers: { + Authorization: "Bearer synthetic-artifact-smoke", + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: {}, + clientInfo: { name: "knowledge-base-artifact-smoke", version: "1.0.0" }, + }, + }), +})); +assert.ok(initialized instanceof Response); +assert.equal(initialized.status, 200); +const initializedBody = await initialized.json(); +assert.equal(initializedBody.jsonrpc, "2.0"); +assert.equal(initializedBody.id, 1); +assert.equal(initializedBody.error, undefined); +assert.equal(initializedBody.result.serverInfo.name, mcpManifest.name); +assert.equal(initializedBody.result.serverInfo.version, mcpManifest.version); +`, + ].join("\n"), ], consumer, env, @@ -271,7 +373,7 @@ async function prepare(mode) { console.log(`Prepared verified artifacts in ${destination}`); } console.log( - `Verified packaging and clean-consumer imports for ${artifacts.length} packages.`, + `Verified packaging and clean-consumer imports for ${artifacts.length} packages, including MCP server metadata.`, ); } finally { const cleanup = await realpath(temporary); diff --git a/test/README.md b/test/README.md index 207776e..597dfec 100644 --- a/test/README.md +++ b/test/README.md @@ -72,9 +72,12 @@ and isolation suites plus `pnpm example` and artifact checks. A current-head gate report supplies pass counts and verdicts; configured fixtures alone do not assert a passing run. -These suites exercise KB-02/KB-03 source and partial KB-05 consumer preparation. -Passing synthetic resolved contexts does not establish KB-04's real OAuth/MCP -credential/client flow. Local storage tests establish no browser UI, live +The domain/storage suites exercise KB-02/KB-03 source and partial KB-05 consumer +preparation. Agent transport suites add KB-04 HTTP/MCP parity and boundary +coverage; `pnpm run agent:proof` separately exercises the actual SDK and reviewed +Agent Access artifacts in an isolated synthetic consumer. These results do not +establish actual site logins or target-client application acceptance. +Local storage tests establish no browser UI, live Workers/host acceptance, model-provider settings, production throughput, or -retention operations. All three KB packages remain unpublished; the full +retention operations. All four KB packages remain unpublished; the full KB-05 release/publication and host activation gates remain required. diff --git a/test/agent-fixtures.ts b/test/agent-fixtures.ts new file mode 100644 index 0000000..de05289 --- /dev/null +++ b/test/agent-fixtures.ts @@ -0,0 +1,201 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { + createKnowledgeAgentDispatcher, + createKnowledgeAgentHttp, + createKnowledgeAgentMcp, + knowledgeAgentScopes, + knowledgeAgentToolNames, + type KnowledgeAgentHttpOptions, + type KnowledgeAgentIdentity, + type KnowledgeAgentInputMap, + type KnowledgeAgentLimits, + type KnowledgeAgentOperation, + type KnowledgeAgentResponse, + type KnowledgeAgentResultMap, +} from "@pegma/knowledge-base-mcp"; +import type { Store } from "@pegma/storage-core"; +import { expect, onTestFinished, vi } from "vitest"; +import { applicationFixture, author } from "./application-fixtures.js"; + +export const agentResource = "https://knowledge.example/agent/mcp"; +export const agentApiUrl = "https://knowledge.example/agent/v1"; +export const agentMetadataUrl = + "https://knowledge.example/.well-known/oauth-protected-resource/agent/mcp"; +export const agentOrigin = "https://author.example"; +export const agentChannels = ["HTTP", "MCP"] as const; +export type AgentChannel = (typeof agentChannels)[number]; + +export function agentIdentity(): KnowledgeAgentIdentity { + return { + access: author, + scopes: Object.values(knowledgeAgentScopes), + clientId: "synthetic-local-agent", + resource: agentResource, + }; +} + +/** Current scripted host facts. This is deliberately not an OAuth proof. */ +export function agentFixture( + store: Store, + limits?: Partial, +) { + const f = applicationFixture(store); + const authority: { + current: KnowledgeAgentIdentity; + rejected?: Response; + unavailable: boolean; + } = { current: agentIdentity(), unavailable: false }; + const authenticate = vi.fn(async (_request: Request) => { + if (authority.unavailable) + throw new Error("PRIVATE_AUTHORITY_BACKEND_OUTAGE"); + return authority.rejected ?? authority.current; + }); + const limit = vi.fn(async () => true); + const dispatcher = createKnowledgeAgentDispatcher({ + application: f.app, + resource: agentResource, + ...(limits === undefined ? {} : { limits }), + }); + const common = { + dispatcher, + resource: agentResource, + protectedResourceMetadataUrl: agentMetadataUrl, + allowedOrigins: [agentOrigin], + authenticate, + limit, + }; + const http = createKnowledgeAgentHttp({ ...common, apiUrl: agentApiUrl }); + const mcp = createKnowledgeAgentMcp({ ...common, mcpUrl: agentResource }); + let client: Client | undefined; + const requests: Request[] = []; + const responses: Response[] = []; + async function sdk(handler = mcp) { + if (client !== undefined) return client; + const connected = new Client({ name: "synthetic-kb-agent", version: "1" }); + onTestFinished(() => connected.close()); + const transport = new StreamableHTTPClientTransport( + new URL(agentResource), + { + requestInit: { + headers: { Authorization: "Bearer synthetic-credential" }, + }, + fetch: async (input, init) => { + const request = new Request(input, init); + requests.push(request.clone()); + const response = await handler.handle(request); + if (response === null) throw new Error("MCP request was not routed"); + responses.push(response.clone()); + return response; + }, + }, + ); + await connected.connect(transport); + client = connected; + return connected; + } + async function httpRequest( + envelope: unknown, + init: RequestInit = {}, + url = agentApiUrl, + ) { + const headers = new Headers({ + Authorization: "Bearer synthetic-credential", + "Content-Type": "application/json", + }); + for (const [key, value] of new Headers(init.headers)) + headers.set(key, value); + const response = await http.handle( + new Request(url, { + method: "POST", + body: JSON.stringify(envelope), + ...init, + headers, + }), + ); + if (response === null) throw new Error("HTTP request was not routed"); + return response; + } + async function call( + channel: AgentChannel, + operation: KnowledgeAgentOperation, + input: unknown, + ): Promise { + if (channel === "HTTP") { + const response = await httpRequest({ apiVersion: "1", operation, input }); + const envelope = (await response.json()) as KnowledgeAgentResponse; + expect(response.status).toBe( + "error" in envelope ? envelope.error.status : 200, + ); + return envelope; + } + const result = await ( + await sdk() + ).callTool({ + name: knowledgeAgentToolNames[operation], + arguments: input as KnowledgeAgentInputMap[typeof operation] & + Record, + }); + const content = result.content; + if (!Array.isArray(content) || content.length !== 1) + throw new Error("Expected one complete MCP result"); + const block = content[0] as { type?: string; text?: string }; + if (block.type !== "text" || typeof block.text !== "string") + throw new Error("Expected a text MCP result"); + const envelope = JSON.parse(block.text) as KnowledgeAgentResponse; + expect(result.isError === true).toBe("error" in envelope); + return envelope; + } + return { + ...f, + authority, + authenticate, + limit, + dispatcher, + http, + mcp, + common, + sdk, + requests, + responses, + httpRequest, + call, + makeHttp: (overrides: Partial) => + createKnowledgeAgentHttp({ + ...common, + apiUrl: agentApiUrl, + ...overrides, + }), + }; +} + +export function agentResult( + response: KnowledgeAgentResponse, + operation: Operation, +): KnowledgeAgentResultMap[Operation] { + expect(response).toMatchObject({ apiVersion: "1", operation }); + if ("error" in response) throw new Error(JSON.stringify(response)); + return response.result as KnowledgeAgentResultMap[Operation]; +} + +/** No exception text, receipt, verifier, private source, or evidence is public. */ +export function expectPrivateAgentError(response: unknown, code?: string) { + expect(response).toMatchObject({ + apiVersion: "1", + error: { + ...(code === undefined ? {} : { code }), + status: expect.any(Number), + }, + }); + const encoded = JSON.stringify(response); + for (const secret of [ + "PRIVATE_", + "receipt/", + "staff/verifier", + "staff/workshop", + "trustedRunnerIds", + "trustedAttesterIds", + "stack", + ]) + expect(encoded).not.toContain(secret); +} diff --git a/tests/agent-security.test.ts b/tests/agent-security.test.ts new file mode 100644 index 0000000..317661a --- /dev/null +++ b/tests/agent-security.test.ts @@ -0,0 +1,1000 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { knowledgeLimits } from "@pegma/knowledge-base-core"; +import { + createKnowledgeAgentDispatcher, + createKnowledgeAgentHttp, + createKnowledgeAgentMcp, + defaultKnowledgeAgentLimits, + knowledgeAgentScopes, + knowledgeAgentToolNames, + type KnowledgeAgentIdentity, +} from "@pegma/knowledge-base-mcp"; +import { createMemoryStore } from "@pegma/storage-core"; +import { describe, expect, it, vi } from "vitest"; +import { + access, + admin, + author, + draft, + evidence, +} from "../test/application-fixtures.js"; +import { + agentApiUrl, + agentChannels, + agentFixture, + agentIdentity, + agentMetadataUrl, + agentOrigin, + agentResource, + agentResult, + expectPrivateAgentError, +} from "../test/agent-fixtures.js"; +import { allKnowledgeRows } from "../test/application-stores.js"; + +const read = { + apiVersion: "1", + operation: "getDraft", + input: { articleId: "article/export" }, +}; + +function request( + body: BodyInit | null = JSON.stringify(read), + init: RequestInit = {}, + url = agentApiUrl, +) { + const headers = new Headers({ + Authorization: "Bearer synthetic-credential", + "Content-Type": "application/json", + }); + for (const [key, value] of new Headers(init.headers)) headers.set(key, value); + return new Request(url, { + method: "POST", + body, + duplex: "half", + ...init, + headers, + } as RequestInit); +} + +async function error(response: Response | null, status: number, code?: string) { + expect(response).not.toBeNull(); + expect(response!.status).toBe(status); + expect(response!.headers.get("Cache-Control")).toBe("no-store"); + expectPrivateAgentError(await response!.json(), code); + return response!; +} + +describe("KB agent least-authority security", () => { + it("intersects credential scopes with fresh current permissions for every operation", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + const current = await f.createDraft(); + const requirements = { + collectionId: current.revision.collectionId, + kind: "explanation", + }; + const before = await allKnowledgeRows(f.store); + const cases = [ + { + scopes: [knowledgeAgentScopes.draftRead], + permissions: [knowledgeAgentScopes.draftWrite], + }, + { + scopes: [knowledgeAgentScopes.draftWrite], + permissions: [knowledgeAgentScopes.draftRead], + }, + { scopes: [], permissions: Object.values(knowledgePermissions) }, + { scopes: Object.values(knowledgeAgentScopes), permissions: [] }, + ]; + for (const test of cases) { + f.authority.current = { + ...agentIdentity(), + scopes: test.scopes, + access: { + ...access(author.principalId, test.permissions), + roles: ["knowledge.admin", "knowledge.author"], + entitlements: Object.values(knowledgePermissions), + }, + }; + for (const channel of agentChannels) { + expectPrivateAgentError( + await f.call(channel, "getDraft", { articleId: current.articleId }), + "forbidden", + ); + expectPrivateAgentError( + await f.call(channel, "createDraft", { + ...f.command("scope-denied", 0), + articleId: "article/denied", + collectionId: current.revision.collectionId, + draft: draft(), + }), + "forbidden", + ); + expectPrivateAgentError( + await f.call(channel, "getValidationRequirements", requirements), + "forbidden", + ); + } + } + // Read and management permissions do not imply author requirements. + f.authority.current = { + ...agentIdentity(), + access: admin, + scopes: [ + knowledgeAgentScopes.draftRead, + knowledgePermissions.validationManage, + ], + }; + for (const channel of agentChannels) + expectPrivateAgentError( + await f.call(channel, "getValidationRequirements", requirements), + "forbidden", + ); + for (const scope of [ + knowledgeAgentScopes.draftWrite, + knowledgeAgentScopes.evidenceSubmit, + ]) { + f.authority.current = { + ...agentIdentity(), + scopes: [scope], + access: access(author.principalId, [scope]), + }; + for (const channel of agentChannels) + expect( + agentResult( + await f.call(channel, "getValidationRequirements", requirements), + "getValidationRequirements", + ).checks, + ).toHaveLength(1); + } + expect(await allKnowledgeRows(f.store)).toEqual(before); + }); + + it("passes a detached context containing only the three intersected permissions", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + const current = await f.createDraft(); + const forwarded: AccessContext[] = []; + const dispatcher = createKnowledgeAgentDispatcher({ + resource: agentResource, + application: { + ...f.app, + getDraft: async (context, input) => { + forwarded.push(context); + return f.app.getDraft(context, input); + }, + }, + }); + const identity: KnowledgeAgentIdentity = { + ...agentIdentity(), + access: { + ...admin, + roles: ["admin"], + entitlements: ["all"], + permissions: [ + ...admin.permissions, + ...Array.from( + { length: 100 }, + (_, index) => `unrelated.permission.${index}`, + ), + ], + }, + scopes: [...Object.values(knowledgePermissions), "*"], + }; + agentResult(await dispatcher.dispatch(identity, read), "getDraft"); + expect(forwarded).toEqual([ + { + principalId: admin.principalId, + policyVersion: admin.policyVersion, + roles: [], + entitlements: [], + permissions: Object.values(knowledgeAgentScopes), + }, + ]); + expect(forwarded[0]).not.toBe(identity.access); + expect(current.revision.createdBy).toBe(author.principalId); + f.authority.current = identity; + for (const channel of agentChannels) + agentResult(await f.call(channel, "getDraft", read.input), "getDraft"); + }); + + it("exposes exactly five tools even to an administrator and refuses private or staff operations", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + await f.createDraft(); + f.authority.current = { + ...agentIdentity(), + access: admin, + scopes: [...Object.values(knowledgePermissions), "*"], + }; + const client = await f.sdk(); + expect( + (await client.listTools()).tools.map((tool) => tool.name).sort(), + ).toEqual(Object.values(knowledgeAgentToolNames).sort()); + const before = await allKnowledgeRows(f.store); + for (const operation of [ + "getEvidence", + "getProvenance", + "setProvenance", + "getReview", + "submitForReview", + "rejectReview", + "publishArticle", + "retireArticle", + "revokeEvidence", + "createCollection", + "getCollection", + "updateCollectionPolicy", + "putValidationPolicy", + "getGovernanceConfiguration", + "putGovernanceConfiguration", + "getPublishedArticle", + "searchPublishedArticles", + ]) { + const response = await f.httpRequest({ + apiVersion: "1", + operation, + input: { + articleId: "article/export", + credential: "PRIVATE_SUBMITTED_CREDENTIAL", + }, + }); + await error(response, 400, "invalid_request"); + expectPrivateAgentError( + await f.dispatcher.dispatch(f.authority.current, { + apiVersion: "1", + operation, + input: {}, + }), + "invalid_request", + ); + } + for (const name of [ + "knowledge_v1_publish_article", + "knowledge_v1_get_evidence", + "knowledge_v1_set_provenance", + ]) { + const result = await client.callTool({ + name, + arguments: { + articleId: "article/export", + receipt: "PRIVATE_FAKE_PROOF", + }, + }); + expect(result.isError).toBe(true); + expect(JSON.stringify(result)).not.toMatch( + /PRIVATE_FAKE_PROOF|staff\/workshop/u, + ); + } + expect(await allKnowledgeRows(f.store)).toEqual(before); + }); + + it("re-resolves current authority on both transports and fails closed on revocation and outage", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + await f.createDraft(); + for (const channel of agentChannels) + agentResult(await f.call(channel, "getDraft", read.input), "getDraft"); + const authenticatedBefore = f.authenticate.mock.calls.length; + f.authority.current = { + ...agentIdentity(), + access: access(author.principalId, []), + }; + for (const channel of agentChannels) + expectPrivateAgentError( + await f.call(channel, "getDraft", read.input), + "forbidden", + ); + expect(f.authenticate.mock.calls.length).toBeGreaterThanOrEqual( + authenticatedBefore + 2, + ); + f.authority.current = agentIdentity(); + agentResult(await f.call("MCP", "getDraft", read.input), "getDraft"); + f.authority.unavailable = true; + await error(await f.http.handle(request()), 503, "unavailable"); + await error( + await f.mcp.handle( + request( + JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/list" }), + {}, + agentResource, + ), + ), + 503, + "unavailable", + ); + }); + + it("binds credentials to the exact resource and keeps independently composed stores isolated", async () => { + const a = agentFixture(createMemoryStore()); + const b = agentFixture(createMemoryStore()); + await a.setupCollection(); + await a.createDraft(); + for (const channel of agentChannels) + expectPrivateAgentError( + await b.call(channel, "getDraft", read.input), + "not_found", + ); + a.authority.current = { + ...agentIdentity(), + resource: "https://other.example/agent/mcp", + }; + await error(await a.http.handle(request()), 401, "invalid_token"); + await error( + await a.mcp.handle(request("{}", {}, agentResource)), + 401, + "invalid_token", + ); + expectPrivateAgentError( + await a.dispatcher.dispatch(a.authority.current, read), + "forbidden", + ); + }); + + it("rejects supplied actors, authority and proof fields without trusting a passed string", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + const current = await f.createDraft(); + f.setTime(3_000); + const input = { + ...f.command("forged", current.generation), + articleId: current.articleId, + evidence: evidence(current.revision), + receipt: "PRIVATE_FORGED_RECEIPT", + }; + const before = await allKnowledgeRows(f.store); + const forged = [ + { ...input, access: admin }, + { ...input, actorId: admin.principalId }, + { ...input, scopes: Object.values(knowledgePermissions) }, + { + ...input, + evidence: { + ...input.evidence, + attestation: { + id: "PRIVATE_PROOF", + verifiedBy: "staff/verifier", + verifiedAt: "2026-11-06T20:00:03.000Z", + }, + }, + }, + { + ...input, + evidence: { ...input.evidence, hash: "a".repeat(64), version: 1 }, + }, + ]; + for (const candidate of forged) + for (const channel of agentChannels) + expectPrivateAgentError( + await f.call(channel, "submitEvidence", candidate), + "invalid_request", + ); + expect(f.verify).not.toHaveBeenCalled(); + for (const channel of agentChannels) + expectPrivateAgentError( + await f.call(channel, "submitEvidence", input), + "prerequisite", + ); + expect(await allKnowledgeRows(f.store)).toEqual(before); + }); +}); + +describe("KB agent hostile request and transport boundary", () => { + it("authenticates and admits valid MCP notifications without dispatching domain commands", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + const application = { ...f.app }; + const serviceCalls = [ + vi.spyOn(application, "getDraft"), + vi.spyOn(application, "createDraft"), + vi.spyOn(application, "updateDraft"), + vi.spyOn(application, "getValidationRequirements"), + vi.spyOn(application, "submitEvidence"), + ]; + const dispatcher = createKnowledgeAgentDispatcher({ + application, + resource: agentResource, + }); + const mcp = createKnowledgeAgentMcp({ + ...f.common, + dispatcher, + mcpUrl: agentResource, + }); + const client = await f.sdk(mcp); + const before = await allKnowledgeRows(f.store); + f.authenticate.mockClear(); + f.limit.mockClear(); + f.responses.length = 0; + await client.notification({ + method: "notifications/cancelled", + params: { requestId: 42, reason: "Synthetic operation was cancelled." }, + }); + expect(f.responses).toHaveLength(1); + expect(f.responses[0]!.status).toBe(202); + expect(await f.responses[0]!.text()).toBe(""); + expect(f.authenticate).toHaveBeenCalledTimes(1); + expect(f.limit).toHaveBeenCalledTimes(1); + + const notifications = [ + { + jsonrpc: "2.0", + method: "notifications/synthetic-extension", + params: { requestId: 43 }, + }, + { + jsonrpc: "2.0", + method: "tools/call", + params: { + name: knowledgeAgentToolNames.createDraft, + arguments: { + ...f.command("notification-must-not-create", 0), + articleId: "article/notification-must-not-exist", + collectionId: "collection/workshop", + draft: draft(), + }, + }, + }, + ]; + for (const notification of notifications) { + const admittedBefore = f.limit.mock.calls.length; + const authenticatedBefore = f.authenticate.mock.calls.length; + const response = await mcp.handle( + request( + JSON.stringify(notification), + { headers: { Accept: "application/json, text/event-stream" } }, + agentResource, + ), + ); + expect(response?.status).toBe(202); + expect(await response!.text()).toBe(""); + expect(f.limit).toHaveBeenCalledTimes(admittedBefore + 1); + expect(f.authenticate).toHaveBeenCalledTimes(authenticatedBefore + 1); + } + const malformed = [ + { + jsonrpc: "1.0", + method: "notifications/cancelled", + params: { requestId: 42 }, + }, + { + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { requestId: {} }, + }, + { jsonrpc: "2.0", method: "notifications/cancelled", params: {} }, + ]; + for (const notification of malformed) { + const response = await mcp.handle( + request( + JSON.stringify(notification), + { headers: { Accept: "application/json, text/event-stream" } }, + agentResource, + ), + ); + expect(response?.status).toBe(400); + expect(JSON.stringify(await response!.json())).not.toContain( + "Synthetic operation", + ); + } + for (const service of serviceCalls) expect(service).not.toHaveBeenCalled(); + expect(await allKnowledgeRows(f.store)).toEqual(before); + }); + + it("enforces each reduced graph budget before parsing JSON on HTTP and MCP", async () => { + const cases = [ + { limits: { maxDepth: 1 }, body: { child: { value: 0 } } }, + { limits: { maxNodes: 3 }, body: [0, 1, 2, 3] }, + { limits: { maxArrayLength: 2 }, body: [0, 1, 2] }, + { limits: { maxObjectKeys: 2 }, body: { first: 0, second: 1, third: 2 } }, + ]; + for (const test of cases) { + const f = agentFixture(createMemoryStore(), test.limits); + const dispatch = vi.fn(f.dispatcher.dispatch); + const dispatcher = { ...f.dispatcher, dispatch }; + const handlers = [ + [ + agentApiUrl, + createKnowledgeAgentHttp({ + ...f.common, + dispatcher, + apiUrl: agentApiUrl, + }), + ], + [ + agentResource, + createKnowledgeAgentMcp({ + ...f.common, + dispatcher, + mcpUrl: agentResource, + }), + ], + ] as const; + const source = JSON.stringify(test.body); + for (const [url, handler] of handlers) { + const incoming = request(source, {}, url); + const parse = vi.spyOn(JSON, "parse"); + let response: Response | null; + try { + response = await handler.handle(incoming); + // Filter by the exact caller body so unrelated runtime JSON activity + // cannot satisfy or invalidate the parse-order assertion. + expect( + parse.mock.calls.filter(([input]) => input === source), + ).toHaveLength(0); + } finally { + parse.mockRestore(); + } + await error(response!, 413, "capacity"); + expect(dispatch).not.toHaveBeenCalled(); + } + } + }); + + it("accepts explicit IPv6 loopback configuration for synthetic HTTP and MCP hosts", () => { + const f = agentFixture(createMemoryStore()); + const resource = "http://[::1]:19999/agent/mcp"; + const dispatcher = createKnowledgeAgentDispatcher({ + application: f.app, + resource, + }); + const common = { + ...f.common, + dispatcher, + resource, + protectedResourceMetadataUrl: + "http://[::1]:19999/.well-known/oauth-protected-resource/agent/mcp", + allowedOrigins: ["http://[::1]:19999"], + allowInsecureLoopback: true, + }; + expect(() => + createKnowledgeAgentHttp({ + ...common, + apiUrl: "http://[::1]:19999/agent/v1", + }), + ).not.toThrow(); + expect(() => + createKnowledgeAgentMcp({ ...common, mcpUrl: resource }), + ).not.toThrow(); + }); + + it("rejects a UTF-8 BOM instead of accepting otherwise valid HTTP and MCP messages", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + await f.createDraft(); + const messages = [ + [agentApiUrl, f.http, read], + [ + agentResource, + f.mcp, + { + jsonrpc: "2.0", + id: 73, + method: "tools/call", + params: { + name: knowledgeAgentToolNames.getDraft, + arguments: read.input, + }, + }, + ], + ] as const; + for (const [url, handler, message] of messages) { + const source = JSON.stringify(message); + const headers = { Accept: "application/json, text/event-stream" }; + const accepted = await handler.handle(request(source, { headers }, url)); + expect(accepted?.status).toBe(200); + await accepted!.body?.cancel(); + const bytes = new TextEncoder().encode(`\ufeff${source}`); + await error( + await handler.handle(request(bytes, { headers }, url)), + 400, + "invalid_request", + ); + } + }); + + it("requires host admission configuration and refuses insecure or ambiguous endpoint URLs", () => { + const f = agentFixture(createMemoryStore()); + const options = { ...f.common, apiUrl: agentApiUrl }; + for (const apiUrl of [ + "http://knowledge.example/agent/v1", + `${agentApiUrl}?token=secret`, + `${agentApiUrl}#fragment`, + "https://user:secret@knowledge.example/agent/v1", + ]) + expect(() => createKnowledgeAgentHttp({ ...options, apiUrl })).toThrow( + TypeError, + ); + expect(() => + createKnowledgeAgentHttp({ ...options, limit: undefined! }), + ).toThrow(TypeError); + expect(() => + createKnowledgeAgentHttp({ ...options, authenticate: undefined! }), + ).toThrow(TypeError); + expect(() => + createKnowledgeAgentMcp({ + ...f.common, + mcpUrl: "https://other.example/mcp", + }), + ).toThrow(TypeError); + expect(() => f.makeHttp({ allowedOrigins: [`${agentOrigin}/`] })).toThrow( + TypeError, + ); + expect(() => + f.makeHttp({ + protectedResourceMetadataUrl: "http://metadata.example/resource", + }), + ).toThrow(TypeError); + }); + + it("rejects wrong Host, Origin, endpoint authority, query tokens, and DNS rebinding before authentication", async () => { + const f = agentFixture(createMemoryStore()); + const hostile = [ + request(undefined, { headers: { Host: "attacker.example" } }), + request(undefined, { + headers: { Host: "knowledge.example@attacker.example" }, + }), + request(undefined, { headers: { Origin: "https://attacker.example" } }), + request(undefined, { headers: { Origin: "null" } }), + request(undefined, {}, "https://attacker.example/agent/v1"), + request(undefined, {}, `${agentApiUrl}?access_token=PRIVATE_TOKEN`), + request(undefined, {}, `${agentApiUrl}?unrelated=1`), + ]; + for (const candidate of hostile) { + const response = await f.http.handle(candidate); + expect(response).not.toBeNull(); + expect([400, 403]).toContain(response!.status); + expectPrivateAgentError(await response!.json()); + } + const loopback = f.makeHttp({ + apiUrl: "http://127.0.0.1:19999/agent/v1", + allowInsecureLoopback: true, + }); + await error( + await loopback.handle( + request( + undefined, + { headers: { Host: "rebound.attacker.example:19999" } }, + "http://127.0.0.1:19999/agent/v1", + ), + ), + 400, + "invalid_request", + ); + expect(f.authenticate).not.toHaveBeenCalled(); + expect(f.limit).not.toHaveBeenCalled(); + expect( + await f.http.handle( + request(undefined, {}, "https://knowledge.example/unrelated"), + ), + ).toBeNull(); + }); + + it("accepts only bounded ASCII header bearer credentials and normalizes host rejections", async () => { + const f = agentFixture(createMemoryStore()); + for (const authorization of [ + "", + "Basic c2VjcmV0", + "Bearer", + "Bearer x,y", + "Bearer PRIVATE_\u00e9_TOKEN", + `Bearer ${"a".repeat(8_193)}`, + ]) + await error( + await f.http.handle( + request(undefined, { + headers: { + Authorization: authorization, + Cookie: "session=PRIVATE_COOKIE", + }, + }), + ), + 401, + "invalid_token", + ); + expect(f.authenticate).not.toHaveBeenCalled(); + for (const status of [401, 403, 302, 500]) { + f.authority.rejected = new Response("PRIVATE_AUTHENTICATION_DETAILS", { + status, + headers: { + "Set-Cookie": "PRIVATE_COOKIE", + Location: "https://private.example", + "WWW-Authenticate": "PRIVATE_CHALLENGE", + }, + }); + const response = await error( + await f.http.handle(request()), + status === 401 || status === 403 ? status : 503, + ); + for (const header of ["Set-Cookie", "Location"]) + expect(response.headers.get(header)).toBeNull(); + if (status === 401 || status === 403) { + expect(response.headers.get("WWW-Authenticate")).toContain( + `resource_metadata="${agentMetadataUrl}"`, + ); + expect(response.headers.get("WWW-Authenticate")).not.toContain( + "PRIVATE_CHALLENGE", + ); + } + } + }); + + it("runs the required limiter before authentication and body reads and fails closed", async () => { + const f = agentFixture(createMemoryStore()); + for (const decision of [ + false, + { allowed: false, retryAfterSeconds: 17 }, + "throws", + ] as const) { + let readCount = 0; + const stream = new ReadableStream( + { + pull() { + readCount += 1; + }, + }, + { highWaterMark: 0 }, + ); + const limit = vi.fn(async () => { + if (decision === "throws") throw new Error("PRIVATE_LIMITER_OUTAGE"); + return decision; + }); + const handler = f.makeHttp({ limit }); + const response = await error( + await handler.handle(request(stream)), + decision === "throws" ? 503 : 429, + ); + expect(response.headers.get("Retry-After")).toBe( + typeof decision === "object" ? "17" : null, + ); + expect(limit).toHaveBeenCalledOnce(); + expect(readCount).toBe(0); + expect(f.authenticate).not.toHaveBeenCalled(); + await stream.cancel(); + } + }); + + it("limits actual streaming bytes and chunk count and cancels rejected streams", async () => { + const f = agentFixture(createMemoryStore()); + for (const mode of ["bytes", "chunks"] as const) { + let pulls = 0; + const cancel = vi.fn(); + const stream = new ReadableStream( + { + pull(controller) { + pulls += 1; + controller.enqueue( + new Uint8Array( + mode === "bytes" + ? defaultKnowledgeAgentLimits.maxRequestBytes + 1 + : 0, + ), + ); + }, + cancel, + }, + { highWaterMark: 0 }, + ); + await error(await f.http.handle(request(stream)), 413, "capacity"); + expect(cancel).toHaveBeenCalledOnce(); + expect(pulls).toBeLessThanOrEqual(mode === "bytes" ? 1 : 1_025); + } + const cancel = vi.fn(); + const declared = new ReadableStream( + { cancel }, + { highWaterMark: 0 }, + ); + await error( + await f.http.handle( + request(declared, { + headers: { + "Content-Length": String( + defaultKnowledgeAgentLimits.maxRequestBytes + 1, + ), + }, + }), + ), + 413, + "capacity", + ); + expect(cancel).toHaveBeenCalledOnce(); + }); + + it("rejects invalid UTF-8, dishonest lengths, compressed or non-JSON bodies, and excessive graphs", async () => { + const f = agentFixture(createMemoryStore()); + await error( + await f.http.handle(request(new Uint8Array([0xc3, 0x28]))), + 400, + "invalid_request", + ); + await error( + await f.http.handle( + request("{}", { headers: { "Content-Length": "1" } }), + ), + 400, + "invalid_request", + ); + await error( + await f.http.handle( + request("{}", { headers: { "Content-Length": "-1" } }), + ), + 400, + "invalid_request", + ); + for (const headers of [ + { "Content-Type": "text/plain" }, + { "Content-Type": "application/json; charset=latin1" }, + { "Content-Encoding": "gzip" }, + ]) + await error( + await f.http.handle(request("{}", { headers })), + 415, + "unsupported_media_type", + ); + for (const body of [ + "[".repeat(30) + "0" + "]".repeat(30), + JSON.stringify(Array(2_000).fill(0)), + JSON.stringify({ + ...read, + unexpected: "x".repeat(defaultKnowledgeAgentLimits.maxRequestBytes), + }), + ]) + await error(await f.http.handle(request(body)), 413, "capacity"); + for (const envelope of [ + { ...read, apiVersion: "2" }, + { ...read, input: { ...read.input, access: admin } }, + { ...read, extra: "PRIVATE_UNKNOWN_FIELD" }, + { apiVersion: "1", operation: "PRIVATE_UNKNOWN_OPERATION", input: {} }, + ]) + await error(await f.httpRequest(envelope), 400, "invalid_request"); + }); + + it("rejects accessors and hostile object graphs without running getters or toJSON", async () => { + const f = agentFixture(createMemoryStore()); + const getter = vi.fn(() => "PRIVATE_GETTER"); + const accessor = { ...read }; + Object.defineProperty(accessor, "input", { enumerable: true, get: getter }); + const toJSON = vi.fn(() => read); + const cycle: Record = {}; + cycle.self = cycle; + const sparse = Array(1); + const symbolic = { ...read, [Symbol("PRIVATE_KEY")]: "PRIVATE_VALUE" }; + const inherited = Object.create(read) as unknown; + for (const candidate of [ + accessor, + { ...read, toJSON }, + cycle, + sparse, + symbolic, + inherited, + ]) + expectPrivateAgentError( + await f.dispatcher.dispatch(agentIdentity(), candidate), + "invalid_request", + ); + expect(getter).not.toHaveBeenCalled(); + expect(toJSON).not.toHaveBeenCalled(); + const identity = agentIdentity(); + Object.defineProperty(identity, "scopes", { + enumerable: true, + get: getter, + }); + expectPrivateAgentError( + await f.dispatcher.dispatch(identity, read), + "forbidden", + ); + expect(getter).not.toHaveBeenCalled(); + }); + + it("counts UTF-8 rather than characters and never returns truncated guides", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + const input = { + ...f.command("utf8-limit", 0), + articleId: "article/utf8", + collectionId: "collection/workshop", + draft: draft( + "explanation", + "\u00e9".repeat(knowledgeLimits.contentBytes / 2 + 1), + ), + }; + for (const channel of agentChannels) + expectPrivateAgentError( + await f.call(channel, "createDraft", input), + "invalid_request", + ); + const current = await f.createDraft( + "article/large", + "collection/workshop", + draft("explanation", "x".repeat(8_000)), + ); + const bounded = createKnowledgeAgentDispatcher({ + application: f.app, + resource: agentResource, + limits: { maxResponseBytes: 2_048 }, + }); + expectPrivateAgentError( + await bounded.dispatch(agentIdentity(), { + ...read, + input: { articleId: current.articleId }, + }), + "capacity", + ); + expect( + (await f.app.getDraft(author, { articleId: current.articleId })).revision + .content.text, + ).toHaveLength(8_000); + for (const limits of [ + { maxDepth: 0 }, + { maxRequestBytes: defaultKnowledgeAgentLimits.maxRequestBytes + 1 }, + { maxResponseBytes: 512 }, + { maxNodes: 1, extra: 1 }, + ]) + expect(() => + createKnowledgeAgentDispatcher({ + application: f.app, + resource: agentResource, + limits, + }), + ).toThrow(TypeError); + }); + + it("reserves enough response space for the largest legal acknowledgement before permitting mutations", async () => { + const store = createMemoryStore(); + const f = agentFixture(store, { maxResponseBytes: 2_048 }); + await f.setupCollection(); + const before = await allKnowledgeRows(store); + expect(() => + createKnowledgeAgentDispatcher({ + application: f.app, + resource: agentResource, + limits: { maxResponseBytes: 512 }, + }), + ).toThrow(TypeError); + expect(await allKnowledgeRows(store)).toEqual(before); + const input = { + ...f.command("largest-acknowledgement", 0), + articleId: "\u6587".repeat(200), + collectionId: "collection/workshop", + draft: draft(), + }; + const created = agentResult( + await f.call("HTTP", "createDraft", input), + "createDraft", + ); + expect(created.value.id).toBe(input.articleId); + expect(created.value.generation).toBe(1); + const committed = await allKnowledgeRows(store); + expect( + agentResult(await f.call("MCP", "createDraft", input), "createDraft"), + ).toEqual({ ...created, replayed: true }); + expect(await allKnowledgeRows(store)).toEqual(committed); + }); + + it("serves explicit CORS for accepted origins and omits credentials and caching", async () => { + const f = agentFixture(createMemoryStore()); + await f.setupCollection(); + await f.createDraft(); + for (const origin of [agentOrigin, undefined]) { + const response = await f.httpRequest(read, { + headers: origin === undefined ? {} : { Origin: origin }, + }); + expect(response.status).toBe(200); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe( + origin ?? null, + ); + expect( + response.headers.get("Access-Control-Allow-Credentials"), + ).toBeNull(); + expect(response.headers.get("Set-Cookie")).toBeNull(); + expect(response.headers.get("Cache-Control")).toBe("no-store"); + expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff"); + expect(response.headers.get("Vary")).toContain("Origin"); + } + await error( + await f.http.handle(request(null, { method: "GET" })), + 405, + "method_not_allowed", + ); + }); +}); diff --git a/tests/agent-transports.conformance.test.ts b/tests/agent-transports.conformance.test.ts new file mode 100644 index 0000000..98ccafc --- /dev/null +++ b/tests/agent-transports.conformance.test.ts @@ -0,0 +1,367 @@ +import { knowledgeAgentToolNames } from "@pegma/knowledge-base-mcp"; +import { describe, expect, it } from "vitest"; +import { + admin, + author, + draft, + evidence, +} from "../test/application-fixtures.js"; +import { + agentChannels, + agentFixture, + agentResult, + expectPrivateAgentError, +} from "../test/agent-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { traceStore } from "../test/trace-store.js"; + +for (const [backend, createStore] of storeFactories) { + describe(`KB agent HTTP/MCP public conformance (${backend})`, () => { + for (const channel of agentChannels) { + it(`${channel} authors, checks and submits verified evidence with cross-transport replay`, async () => { + const f = agentFixture(await createStore()); + await f.setupCollection(); + const other = channel === "HTTP" ? "MCP" : "HTTP"; + const create = { + ...f.command("agent-create", 0), + correlationId: "synthetic-agent-request-123", + articleId: "article/agent-export", + collectionId: "collection/workshop", + draft: draft(), + }; + const created = agentResult( + await f.call(channel, "createDraft", create), + "createDraft", + ); + expect(created).toMatchObject({ + replayed: false, + value: { + id: create.articleId, + generation: 1, + articleRevision: 1, + state: "draft", + }, + }); + let current = agentResult( + await f.call(channel, "getDraft", { articleId: create.articleId }), + "getDraft", + ); + expect(current.revision.createdBy).toBe(author.principalId); + expect(current.revision.content).toEqual(create.draft.content); + expect( + agentResult( + await f.call(other, "getDraft", { articleId: create.articleId }), + "getDraft", + ), + ).toEqual(current); + f.setTime(2_000); + const update = { + ...f.command("agent-edit", current.generation), + articleId: current.articleId, + collectionId: current.revision.collectionId, + draft: { ...draft(), title: "Export a fictional workspace safely" }, + }; + const updated = agentResult( + await f.call(channel, "updateDraft", update), + "updateDraft", + ); + expect(updated.value).toMatchObject({ + generation: 2, + articleRevision: 2, + }); + expect(updated.value.contentHash).not.toBe(created.value.contentHash); + expectPrivateAgentError( + await f.call(other, "updateDraft", { + ...update, + ...f.command("stale-edit", 1), + }), + "conflict", + ); + const requirementsInput = { + collectionId: create.collectionId, + kind: "explanation", + }; + const requirements = agentResult( + await f.call(channel, "getValidationRequirements", requirementsInput), + "getValidationRequirements", + ); + expect(requirements).toMatchObject({ + expectedStagingBuildId: "staging-42", + checks: [ + { + id: "explanation-content", + testKind: "content", + maxAgeMilliseconds: 60_000, + }, + ], + }); + expect( + agentResult( + await f.call(other, "getValidationRequirements", requirementsInput), + "getValidationRequirements", + ), + ).toEqual(requirements); + expect(JSON.stringify(requirements)).not.toMatch( + /trustedRunnerIds|trustedAttesterIds|staff\/verifier|runner\/staging/u, + ); + + current = agentResult( + await f.call(channel, "getDraft", { articleId: create.articleId }), + "getDraft", + ); + f.setTime(4_000); + const issued = await f.issueReceipt(current); + const submit = { + ...f.command("agent-evidence", current.generation), + articleId: current.articleId, + evidence: issued.submission, + receipt: issued.receipt, + }; + const submitted = agentResult( + await f.call(channel, "submitEvidence", submit), + "submitEvidence", + ); + expect(submitted.value).toMatchObject({ + generation: 3, + articleRevision: 2, + }); + const committed = await allKnowledgeRows(f.store); + expect( + agentResult( + await f.call(other, "submitEvidence", submit), + "submitEvidence", + ), + ).toEqual({ ...submitted, replayed: true }); + // Correlation is request tracing metadata. It neither changes the + // original semantic command nor permits a second state transition. + const replayedCreate = agentResult( + await f.call(other, "createDraft", { + ...create, + correlationId: "synthetic-retry-request-456", + }), + "createDraft", + ); + expect(replayedCreate).toEqual({ ...created, replayed: true }); + expect(Object.keys(replayedCreate.value).sort()).toEqual([ + "articleRevision", + "contentHash", + "generation", + "id", + "state", + ]); + expectPrivateAgentError( + await f.call(other, "createDraft", { + ...create, + draft: { ...create.draft, title: "PRIVATE_CHANGED_COMMAND" }, + }), + "conflict", + ); + expect(await allKnowledgeRows(f.store)).toEqual(committed); + const articleRows = committed.filter( + (row) => row.resourceId === create.articleId, + ); + expect( + articleRows.filter((row) => row.kind === "revision"), + ).toHaveLength(2); + expect( + articleRows.filter((row) => row.kind === "evidence"), + ).toHaveLength(1); + expect( + articleRows.filter((row) => row.kind === "command"), + ).toHaveLength(3); + expect( + articleRows + .filter((row) => row.kind === "audit") + .map((row) => row.data), + ).toContainEqual( + expect.objectContaining({ + details: expect.objectContaining({ + correlationId: create.correlationId, + }), + }), + ); + + current = await f.app.getDraft(author, { articleId: create.articleId }); + current = await f.setSources(current, [ + { + id: "source/private", + system: "synthetic-support", + resourceId: "PRIVATE_SOURCE_TICKET_7", + version: "2", + }, + ]); + await f.review(current); + const visible = agentResult( + await f.call(other, "getDraft", { articleId: create.articleId }), + "getDraft", + ); + expect(visible.hasPendingReview).toBe(true); + expect(visible.revision.createdBy).toBe(author.principalId); + for (const privateValue of [ + "PRIVATE_SOURCE_TICKET_7", + "PRIVATE_STAFF_EVIDENCE", + "staff/verifier", + issued.receipt, + "attestation", + "reviewerId", + "sourceSnapshot", + ]) + expect(JSON.stringify(visible)).not.toContain(privateValue); + expect(await (await f.sdk()).listTools()).toMatchObject({ + tools: expect.arrayContaining( + Object.values(knowledgeAgentToolNames).map((name) => + expect.objectContaining({ name }), + ), + ), + }); + expect((await (await f.sdk()).listTools()).tools).toHaveLength(5); + for (const response of f.responses) { + expect(response.headers.get("Mcp-Session-Id")).toBeNull(); + expect(response.headers.get("Cache-Control")).toBe("no-store"); + } + }); + } + + it("replays a committed evidence command after the backing store loses its acknowledgement", async () => { + const backing = await createStore(); + const traced = traceStore(backing); + const f = agentFixture(traced.store); + await f.setupCollection(); + const current = await f.createDraft(); + f.setTime(3_000); + const issued = await f.issueReceipt(current); + const input = { + ...f.command("uncertain-evidence", current.generation), + articleId: current.articleId, + evidence: issued.submission, + receipt: issued.receipt, + }; + let lost = false; + traced.intercept(async (transaction, commit) => { + const outcome = await commit(); + if ( + !lost && + transaction.partition.startsWith("article:") && + outcome.committed + ) { + lost = true; + throw new Error("PRIVATE_CONNECTION_LOST_AFTER_COMMIT"); + } + return outcome; + }); + expectPrivateAgentError( + await f.call("HTTP", "submitEvidence", input), + "unavailable", + ); + expect(lost).toBe(true); + traced.intercept(undefined); + const committed = await allKnowledgeRows(backing); + const replay = agentResult( + await f.call("MCP", "submitEvidence", input), + "submitEvidence", + ); + expect(replay).toMatchObject({ + replayed: true, + value: { generation: 2, articleRevision: 1 }, + }); + expect(f.verify).toHaveBeenCalledOnce(); + expect(await allKnowledgeRows(backing)).toEqual(committed); + expect( + (await f.app.getEvidence(admin, { articleId: current.articleId })) + .evidence, + ).toHaveLength(1); + // A replay receipt is an acknowledgement, never restored read authority. + f.authority.current = { ...f.authority.current, scopes: [] }; + expectPrivateAgentError( + await f.call("HTTP", "submitEvidence", input), + "forbidden", + ); + expect(await allKnowledgeRows(backing)).toEqual(committed); + }); + + it("requires independently verified actor, revision, content, runner, build and freshness bindings", async () => { + const f = agentFixture(await createStore()); + await f.setupCollection(); + const current = await f.createDraft(); + f.setTime(3_000); + const submitted = evidence(current.revision); + const defects = [ + { + name: "revision", + code: "conflict", + submission: { ...submitted, articleRevision: 2 }, + }, + { + name: "hash", + code: "prerequisite", + submission: { ...submitted, contentHash: "b".repeat(64) }, + }, + { + name: "build", + code: "prerequisite", + submission: { ...submitted, stagingBuildId: "PRIVATE_WRONG_BUILD" }, + }, + { + name: "runner", + code: "prerequisite", + submission: { ...submitted, runnerId: "runner/PRIVATE_UNTRUSTED" }, + }, + { + name: "predates draft", + code: "prerequisite", + submission: { ...submitted, executedAt: "2026-11-06T19:58:00.000Z" }, + }, + { name: "stale", code: "prerequisite", submission: submitted }, + { name: "unverified", code: "prerequisite", submission: submitted }, + { name: "other actor", code: "prerequisite", submission: submitted }, + ]; + const before = await allKnowledgeRows(f.store); + for (const defect of defects) { + f.setTime(defect.name === "stale" ? 120_000 : 3_000); + const issued = await f.issueReceipt( + current, + defect.submission, + defect.name === "other actor" ? admin : author, + ); + const input = { + ...f.command( + `rejected-evidence-${defect.name.replaceAll(" ", "-")}`, + current.generation, + ), + articleId: current.articleId, + evidence: issued.submission, + receipt: + defect.name === "unverified" + ? "PRIVATE_FORGED_RECEIPT" + : issued.receipt, + }; + for (const channel of agentChannels) + expectPrivateAgentError( + await f.call(channel, "submitEvidence", input), + defect.code, + ); + } + expect(await allKnowledgeRows(f.store)).toEqual(before); + expect( + (await f.app.getEvidence(admin, { articleId: current.articleId })) + .evidence, + ).toEqual([]); + f.setTime(3_000); + const legitimate = await f.issueReceipt(current); + expect( + agentResult( + await f.call("MCP", "submitEvidence", { + ...f.command("bound-evidence", current.generation), + articleId: current.articleId, + evidence: legitimate.submission, + receipt: legitimate.receipt, + }), + "submitEvidence", + ).value.generation, + ).toBe(2); + }); + }); +} diff --git a/tsconfig.json b/tsconfig.json index 08388be..14c3357 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,6 +3,7 @@ "references": [ { "path": "./packages/contracts" }, { "path": "./packages/core" }, - { "path": "./packages/application" } + { "path": "./packages/application" }, + { "path": "./packages/mcp" } ] }