@abinnovision/payloadcms-mcpx 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +258 -0
  3. package/dist/api-keys/collection.mjs +58 -0
  4. package/dist/api-keys/fields.mjs +88 -0
  5. package/dist/api-keys/key.mjs +10 -0
  6. package/dist/auth/resolve.mjs +62 -0
  7. package/dist/capabilities.mjs +30 -0
  8. package/dist/endpoint/handler.mjs +84 -0
  9. package/dist/endpoint/result.mjs +59 -0
  10. package/dist/endpoint/server.mjs +52 -0
  11. package/dist/index.d.mts +5 -0
  12. package/dist/index.mjs +4 -0
  13. package/dist/options.mjs +107 -0
  14. package/dist/plugin.d.mts +9 -0
  15. package/dist/plugin.mjs +42 -0
  16. package/dist/schema/describe.mjs +82 -0
  17. package/dist/schema/lexical.mjs +25 -0
  18. package/dist/schema/pointer.mjs +83 -0
  19. package/dist/schema/shape.mjs +147 -0
  20. package/dist/schema/walk.mjs +109 -0
  21. package/dist/tools/create-document.mjs +67 -0
  22. package/dist/tools/describe-schema.mjs +44 -0
  23. package/dist/tools/find-documents.mjs +54 -0
  24. package/dist/tools/get-document.mjs +54 -0
  25. package/dist/tools/index.mjs +23 -0
  26. package/dist/tools/list-capabilities.mjs +49 -0
  27. package/dist/tools/names.mjs +14 -0
  28. package/dist/tools/patch-document.mjs +113 -0
  29. package/dist/tools/shared.mjs +65 -0
  30. package/dist/tools/validate-document.mjs +48 -0
  31. package/dist/types.d.mts +113 -0
  32. package/dist/types.mjs +7 -0
  33. package/dist/version.mjs +6 -0
  34. package/dist/write/draft-guard.d.mts +10 -0
  35. package/dist/write/draft-guard.mjs +70 -0
  36. package/dist/write/patch.mjs +220 -0
  37. package/dist/write/publish-blockers.d.mts +13 -0
  38. package/dist/write/publish-blockers.mjs +72 -0
  39. package/dist/write/transaction.mjs +19 -0
  40. package/package.json +89 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 abi group GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,258 @@
1
+ # @abinnovision/payloadcms-mcpx
2
+
3
+ A Payload CMS plugin that mounts an MCP (Model Context Protocol) server whose
4
+ tool surface stays small and accurate regardless of the size of the
5
+ content model.
6
+
7
+ Instead of generating one tool per collection with the full document schema
8
+ inlined, the plugin types its surface in three layers. The tool signatures are
9
+ small and static: collection slugs, locales and operations as enums, everything
10
+ else scalars. The field shapes are pulled on demand through `describeSchema`,
11
+ one node at a time, stopping at every blocks boundary. And every write is
12
+ resolved server-side against the real config and the real document, so unknown
13
+ fields, misplaced blocks and unusable rich text nodes are refused with the
14
+ valid alternatives listed, never silently dropped.
15
+
16
+ Writes are RFC 6902 patches that always land as drafts; publishing stays a
17
+ human action in the admin panel. Every write returns the publish
18
+ blockers: the validation failures that still prevent a human from publishing
19
+ the draft. Capabilities are declared twice: the plugin config decides what
20
+ can exist, a checkbox on each API key decides what does, and a missing checkbox
21
+ means no (fail-closed).
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ yarn add @abinnovision/payloadcms-mcpx
27
+ ```
28
+
29
+ - Peer dependency: `payload >=3.88.0 <4`.
30
+ - The package is published as ESM only, matching Payload itself.
31
+
32
+ ## Usage
33
+
34
+ ```ts
35
+ import { mcpxPlugin } from "@abinnovision/payloadcms-mcpx";
36
+ import { buildConfig } from "payload";
37
+
38
+ export default buildConfig({
39
+ // ...
40
+ plugins: [
41
+ mcpxPlugin({
42
+ collections: {
43
+ pages: { read: true, write: true },
44
+ posts: { read: true, write: true },
45
+ tags: true, // shorthand for { read: true }
46
+ },
47
+ limits: { maxLimit: 25, maxDepth: 1 },
48
+ }),
49
+ ],
50
+ });
51
+ ```
52
+
53
+ The plugin adds:
54
+
55
+ - a `POST /api/mcpx` endpoint speaking MCP over streamable HTTP (stateless,
56
+ JSON responses; `GET`/`DELETE` answer 405),
57
+ - an `mcpx-api-keys` collection (admin group "MCP") holding the keys and their
58
+ capability checkboxes,
59
+ - a draft guard on every collection, so any write carrying the MCP request
60
+ marker lands as a draft, including writes made by custom tools.
61
+
62
+ ## API keys
63
+
64
+ Keys are created in the admin panel under MCP > API Keys. The plaintext key is
65
+ generated on create, stored encrypted with an HMAC index for lookup, and shown
66
+ to anyone who may read the key document (own keys only, by default). Each key:
67
+
68
+ - is bound to the user who created it and acts as that user: every operation
69
+ runs with `req.user` set to the linked user and `overrideAccess: false`, so
70
+ your collection access control applies unchanged;
71
+ - carries one checkbox per exposed collection and operation, plus one per
72
+ custom tool. All checkboxes default to off. A key can never enable an
73
+ operation the plugin config does not expose, and keys created before a
74
+ capability existed stay without it.
75
+
76
+ Keys authenticate only the MCP endpoint. They are deliberately not a Payload
77
+ auth strategy, so a key can never authenticate the REST or GraphQL API; the
78
+ reverse also holds: an admin session or JWT is ignored by the MCP endpoint.
79
+
80
+ Use `apiKeys.overrideCollection` to widen access (for example, admins manage
81
+ all keys) or add fields.
82
+
83
+ ## Connecting a client
84
+
85
+ The endpoint speaks streamable HTTP with `Authorization: Bearer <key>`:
86
+
87
+ ```bash
88
+ npx @modelcontextprotocol/inspector
89
+ # transport: Streamable HTTP, URL: http://localhost:3000/api/mcpx
90
+ # header: Authorization: Bearer <key>
91
+ ```
92
+
93
+ Claude Code:
94
+
95
+ ```bash
96
+ claude mcp add --transport http payload http://localhost:3000/api/mcpx \
97
+ --header "Authorization: Bearer <key>"
98
+ ```
99
+
100
+ Claude Desktop (no direct HTTP header support) via `mcp-remote`:
101
+
102
+ ```json
103
+ {
104
+ "mcpServers": {
105
+ "payload": {
106
+ "command": "npx",
107
+ "args": [
108
+ "-y",
109
+ "mcp-remote",
110
+ "http://localhost:3000/api/mcpx",
111
+ "--header",
112
+ "Authorization: Bearer <key>"
113
+ ]
114
+ }
115
+ }
116
+ }
117
+ ```
118
+
119
+ ## Tools
120
+
121
+ The surface is fixed at seven tools plus your custom ones. `tools/list`
122
+ reflects the key: write tools disappear for read-only keys, and every
123
+ `collection` enum contains only the slugs the key may touch.
124
+
125
+ | Tool | Purpose | Key arguments |
126
+ | ------------------ | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
127
+ | `listCapabilities` | What this key may do; call first to orient. | none |
128
+ | `describeSchema` | Field shape of one node; `next` lists the drill-down paths. | `collection`, `paths?`, `expand?` |
129
+ | `findDocuments` | Query documents. | `collection`, `where?`, `sort?`, `limit?`, `page?`, `depth?`, `select?`, `locale?`, `draft?` |
130
+ | `getDocument` | Read one document or a subtree of it. | `collection`, `id`, `path?` (JSON pointer), `depth?`, `locale?`, `draft?` |
131
+ | `patchDocument` | Apply RFC 6902 operations to the current draft. | `collection`, `id`, `locale`, `patches`, `expectedUpdatedAt?` |
132
+ | `createDocument` | Create a draft from a minimal seed. | `collection`, `locale`, `data` |
133
+ | `validateDocument` | Publish blockers without writing. | `collection`, `id`, `locale` |
134
+
135
+ Rules the tools enforce and explain in their own descriptions:
136
+
137
+ - `describeSchema` paths are dotted and stop at blocks fields, which list the
138
+ block slugs they accept; every node carries `next`, the ready-to-use paths
139
+ for those blocks (`layout.sections.sectionWrapper`), so pass an entry of
140
+ `next` as a `paths` element to descend. A block is described as it exists at
141
+ that position.
142
+ - Field and collection `admin.description` values are included in
143
+ `describeSchema` and `listCapabilities`, so intent written for the admin
144
+ panel reaches the client. Strings and locale-keyed records pass through;
145
+ functions and components are dropped.
146
+ - Builtin tools reject unknown arguments by name instead of silently ignoring
147
+ them.
148
+ - A schema path becomes a patch pointer by replacing `.` with `/`, adding a
149
+ leading `/`, and replacing each `[]` with a 0-based index.
150
+ - Adding a block requires `blockType` on the value; append with `/-`.
151
+ - Clearing is `replace` with `null`; a list is emptied with `[]` and refuses
152
+ `null`. `remove` is only valid on list elements, because Payload keeps
153
+ fields absent from a write.
154
+ - Nothing in a patch batch is applied unless every operation validates first.
155
+ - Pass the `updatedAt` you read as `expectedUpdatedAt` so a concurrent edit is
156
+ refused instead of overwritten.
157
+ - Fields Payload maintains (`id`, `_status`, `createdAt`, `updatedAt`,
158
+ `deletedAt`) are never listed and never writable; `readOnly` fields are
159
+ listed but refused on write.
160
+
161
+ ## Drafts and publish blockers
162
+
163
+ Draft-only writing is enforced on the Payload operation, not in the tool
164
+ handlers: a `beforeOperation` hook forces `draft: true` and strips `_status`
165
+ from every write carrying the MCP request marker, so custom tools and anything
166
+ else writing through the same request are covered too. A `beforeChange` hook
167
+ refuses any write that would still not land as a draft.
168
+
169
+ Publish blockers are advisory. Payload skips validation on draft saves (unless
170
+ `versions.drafts.validate` is set), so after every write the plugin re-runs
171
+ Payload's own field validation over the saved draft and returns the failures
172
+ as `publishBlockers` with paths and labels. The write stands; the client gets a
173
+ checklist of what remains. Three limits: only the written locale is
174
+ validated; field `beforeChange` hooks run again during the check, so they must
175
+ be pure; and the check runs privileged, so blocker paths and messages may name
176
+ fields the key's user cannot read (values are never included).
177
+ Collections with `versions.drafts.validate: true` refuse invalid drafts
178
+ outright; those failures come back as `validationErrors`.
179
+
180
+ Writes also report `notApplied`: pointers whose value Payload kept unchanged,
181
+ which happens when field-level access denies the update.
182
+
183
+ ## Custom tools
184
+
185
+ ```ts
186
+ import { defineMcpxTool } from "@abinnovision/payloadcms-mcpx";
187
+ import { z } from "zod";
188
+
189
+ const publishQueue = defineMcpxTool({
190
+ name: "queueForReview",
191
+ description: "Marks a page as ready for editorial review.",
192
+ inputSchema: { id: z.string() },
193
+ handler: async ({ args, req }) => {
194
+ // req.user is the key's linked user, req.context.mcpx carries the
195
+ // key id and capabilities. Writes through payload.update({ req })
196
+ // land as drafts like every other MCP write.
197
+ await req.payload.update({
198
+ collection: "pages",
199
+ id: args.id,
200
+ data: { reviewRequested: true },
201
+ overrideAccess: false,
202
+ req,
203
+ });
204
+ return { content: [{ type: "text", text: "queued" }] };
205
+ },
206
+ });
207
+ ```
208
+
209
+ Each custom tool gets its own checkbox on every API key, default off.
210
+
211
+ Custom tool shapes are registered as given, and the MCP SDK wraps them in a
212
+ non-strict object: unknown arguments are stripped before your handler runs.
213
+ Builtin tools reject them instead.
214
+
215
+ ## Options
216
+
217
+ | Option | Default | Description |
218
+ | ------------------------------------ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
219
+ | `collections` | required | Allow-list. `true` means `{ read: true }`. |
220
+ | `collections.<slug>.read` | `true` | Expose `describeSchema`, `findDocuments`, `getDocument`. |
221
+ | `collections.<slug>.write` | `false` | Expose `patchDocument`, `createDocument`, `validateDocument`. Requires `versions.drafts` unless `allowLiveWrites`. |
222
+ | `collections.<slug>.allowLiveWrites` | `false` | Permit writes to a collection without drafts (they land live). |
223
+ | `userCollection` | `config.admin.user` or `users` | Auth collection the keys act as. |
224
+ | `apiKeys.slug` | `mcpx-api-keys` | Slug of the generated key collection. |
225
+ | `apiKeys.overrideCollection` | none | Final override applied to the generated collection. |
226
+ | `endpoint.path` | `/mcpx` | Endpoint path below the API route. |
227
+ | `limits.maxLimit` | `25` | Upper bound for `findDocuments.limit`. |
228
+ | `limits.maxDepth` | `1` | Upper bound for `depth` on reads. |
229
+ | `tools` | `[]` | Custom tools. |
230
+ | `auth.resolve` | none | Replace or wrap the default key resolution. |
231
+ | `serverInfo` | package name and version | Reported to MCP clients. |
232
+
233
+ Misconfiguration (unknown slugs, write on a collection without drafts, upload
234
+ collections exposed for write, tool name collisions) fails at startup with
235
+ `InvalidConfiguration`. Auth collections cannot be exposed at all, read
236
+ included: their documents carry credentials, such as the decrypted Payload API
237
+ key of every user.
238
+
239
+ ## Security notes
240
+
241
+ - Keys are stored encrypted; lookup is by HMAC-SHA256 index derived from
242
+ `payload.secret`, the same scheme Payload uses for its own API keys.
243
+ - The endpoint authenticates with Bearer keys only; admin JWTs and cookies are
244
+ ignored. Keys cannot authenticate REST or GraphQL.
245
+ - Every operation runs under the linked user with `overrideAccess: false`.
246
+ - Not covered in v1: `delete` (no tool exists and none is generated), globals,
247
+ uploads. Custom tools are trusted code and can do what the linked user may.
248
+
249
+ ## Non-goals of v1 / roadmap
250
+
251
+ Globals, deletes, uploads, markdown authoring for rich text, row addressing by
252
+ id instead of index, cross-locale publish blockers, pagination of
253
+ `describeSchema` with `expand`, and a handler-level timeout are all deliberate
254
+ omissions for now.
255
+
256
+ ## License
257
+
258
+ Apache-2.0
@@ -0,0 +1,58 @@
1
+ import { createCapabilityFields, createKeyFields } from "./fields.mjs";
2
+ import { generateApiKey, hashApiKey } from "./key.mjs";
3
+ //#region src/api-keys/collection.ts
4
+ /**
5
+ * Generates the key on create and keeps the lookup index in step with it.
6
+ * Runs after field `beforeValidate` fallbacks, so on update `data.apiKey` is the
7
+ * decrypted plaintext of the stored key.
8
+ */ const keyBeforeChange = ({ data, operation, req }) => {
9
+ if (operation === "create" && typeof data["apiKey"] !== "string") data["apiKey"] = generateApiKey();
10
+ if (typeof data["apiKey"] === "string") data["apiKeyIndex"] = hashApiKey(req.payload.secret, data["apiKey"]);
11
+ return data;
12
+ };
13
+ /**
14
+ * The collection holding MCP API keys. It is not an auth collection on
15
+ * purpose: keys must only ever authenticate the MCP endpoint, never the REST
16
+ * or GraphQL API.
17
+ */ const createApiKeysCollection = (options) => {
18
+ const { userCollection } = options;
19
+ const isUser = ({ req }) => Boolean(req.user && req.user.collection === userCollection);
20
+ const ownKeysOnly = ({ req }) => isUser({ req }) && req.user ? { user: { equals: req.user.id } } : false;
21
+ return {
22
+ slug: options.apiKeysSlug,
23
+ labels: {
24
+ singular: "API Key",
25
+ plural: "API Keys"
26
+ },
27
+ admin: {
28
+ group: "MCP",
29
+ useAsTitle: "label",
30
+ description: "Keys for MCP clients. Each key acts as its user and may only do what its capabilities allow."
31
+ },
32
+ access: {
33
+ create: isUser,
34
+ read: ownKeysOnly,
35
+ update: ownKeysOnly,
36
+ delete: ownKeysOnly
37
+ },
38
+ hooks: { beforeChange: [keyBeforeChange] },
39
+ fields: [
40
+ {
41
+ name: "user",
42
+ type: "relationship",
43
+ relationTo: userCollection,
44
+ required: true,
45
+ access: {
46
+ create: () => false,
47
+ update: () => false
48
+ },
49
+ defaultValue: ({ req }) => isUser({ req }) ? req.user?.id : void 0,
50
+ admin: { description: "The user this key acts as." }
51
+ },
52
+ ...createKeyFields(),
53
+ ...createCapabilityFields(options)
54
+ ]
55
+ };
56
+ };
57
+ //#endregion
58
+ export { createApiKeysCollection, keyBeforeChange };
@@ -0,0 +1,88 @@
1
+ import { CAPABILITIES_FIELD } from "../capabilities.mjs";
2
+ //#region src/api-keys/fields.ts
3
+ const encryptKey = ({ req, value }) => typeof value === "string" ? req.payload.encrypt(value) : value;
4
+ const decryptKey = ({ req, value }) => {
5
+ if (typeof value !== "string") return value;
6
+ try {
7
+ return req.payload.decrypt(value);
8
+ } catch {
9
+ return;
10
+ }
11
+ };
12
+ const checkbox = (name, description) => ({
13
+ name,
14
+ type: "checkbox",
15
+ defaultValue: false,
16
+ admin: { description }
17
+ });
18
+ /**
19
+ * Fields every key carries. Key generation and the HMAC index live in the
20
+ * collection-level `beforeChange` hook (see `collection.ts`), because sibling
21
+ * field hooks run in parallel and cannot depend on each other's values.
22
+ */ const createKeyFields = () => [
23
+ {
24
+ name: "label",
25
+ type: "text",
26
+ required: true,
27
+ admin: { description: "What this key is used for." }
28
+ },
29
+ {
30
+ name: "enabled",
31
+ type: "checkbox",
32
+ defaultValue: true,
33
+ admin: { description: "Disabled keys are refused without revoking them." }
34
+ },
35
+ {
36
+ name: "apiKey",
37
+ type: "text",
38
+ access: {
39
+ create: () => false,
40
+ update: () => false
41
+ },
42
+ admin: {
43
+ readOnly: true,
44
+ description: "Generated when the key is created. Send it as `Authorization: Bearer <key>`."
45
+ },
46
+ hooks: {
47
+ beforeChange: [encryptKey],
48
+ afterRead: [decryptKey]
49
+ }
50
+ },
51
+ {
52
+ name: "apiKeyIndex",
53
+ type: "text",
54
+ hidden: true,
55
+ index: true
56
+ }
57
+ ];
58
+ /**
59
+ * One checkbox per exposed operation, grouped per collection and per custom
60
+ * tool. Only operations the plugin config exposes get a checkbox, so a key can
61
+ * never enable more than the config allows. Everything defaults to off.
62
+ */ const createCapabilityFields = (options) => {
63
+ const collectionGroups = options.collections.map((collection) => ({
64
+ name: collection.fieldName,
65
+ type: "group",
66
+ label: collection.slug,
67
+ fields: [...collection.read ? [checkbox("read", "Describe, find and read documents.")] : [], ...collection.write ? [checkbox("write", "Create, patch and validate drafts.")] : []]
68
+ }));
69
+ const toolCheckboxes = options.tools.map((tool) => checkbox(tool.name, tool.description));
70
+ const groups = [...collectionGroups.length > 0 ? [{
71
+ name: "collections",
72
+ type: "group",
73
+ fields: collectionGroups
74
+ }] : [], ...toolCheckboxes.length > 0 ? [{
75
+ name: "tools",
76
+ type: "group",
77
+ fields: toolCheckboxes
78
+ }] : []];
79
+ if (groups.length === 0) return [];
80
+ return [{
81
+ name: CAPABILITIES_FIELD,
82
+ type: "group",
83
+ admin: { description: "What this key may do. Unchecked means refused, whatever the plugin config allows." },
84
+ fields: groups
85
+ }];
86
+ };
87
+ //#endregion
88
+ export { createCapabilityFields, createKeyFields };
@@ -0,0 +1,10 @@
1
+ import crypto from "node:crypto";
2
+ //#region src/api-keys/key.ts
3
+ /**
4
+ * A fresh API key: 32 random bytes, base64url so it is safe in headers.
5
+ */ const generateApiKey = () => crypto.randomBytes(32).toString("base64url");
6
+ /**
7
+ * Lookup index of a key, the same HMAC Payload core uses for `apiKeyIndex`.
8
+ */ const hashApiKey = (secret, key) => crypto.createHmac("sha256", secret).update(key).digest("hex");
9
+ //#endregion
10
+ export { generateApiKey, hashApiKey };
@@ -0,0 +1,62 @@
1
+ import { hashApiKey } from "../api-keys/key.mjs";
2
+ //#region src/auth/resolve.ts
3
+ const BEARER = /^Bearer\s+(\S+)\s*$/i;
4
+ /**
5
+ * The bearer token of an `Authorization` header, or `null`.
6
+ */ const parseBearer = (headers) => {
7
+ const header = headers.get("authorization");
8
+ if (!header) return null;
9
+ return BEARER.exec(header.trim())?.[1] ?? null;
10
+ };
11
+ const relationId = (value) => {
12
+ if (typeof value === "string" || typeof value === "number") return value;
13
+ if (typeof value === "object" && value !== null && "id" in value) return value.id;
14
+ };
15
+ /**
16
+ * Resolves the bearer key of a request to the user it acts as.
17
+ *
18
+ * The key is looked up by its HMAC index, the same way Payload resolves its own
19
+ * API keys. A missing, unknown, disabled or orphaned key yields `null`; nothing
20
+ * here throws, so the handler alone decides how a refusal looks.
21
+ */ const resolveApiKeyAuth = async (req, options) => {
22
+ const key = parseBearer(req.headers);
23
+ if (key === null) return null;
24
+ const { payload } = req;
25
+ const { docs } = await payload.find({
26
+ collection: options.apiKeysSlug,
27
+ where: { apiKeyIndex: { equals: hashApiKey(payload.secret, key) } },
28
+ limit: 1,
29
+ pagination: false,
30
+ depth: 0,
31
+ overrideAccess: true,
32
+ select: {
33
+ enabled: true,
34
+ user: true,
35
+ capabilities: true
36
+ }
37
+ });
38
+ const keyDoc = docs[0];
39
+ const userId = relationId(keyDoc?.user);
40
+ if (!keyDoc || keyDoc.enabled !== true || userId === void 0) return null;
41
+ const userCollection = payload.collections[options.userCollection];
42
+ const user = await payload.findByID({
43
+ collection: options.userCollection,
44
+ id: userId,
45
+ depth: userCollection?.config.auth.depth ?? 0,
46
+ overrideAccess: true,
47
+ disableErrors: true
48
+ });
49
+ const lockUntil = typeof user?.["lockUntil"] === "string" ? Date.parse(user["lockUntil"]) : NaN;
50
+ if (!user || user["_verified"] === false || lockUntil > Date.now()) return null;
51
+ return {
52
+ user: {
53
+ ...user,
54
+ collection: options.userCollection,
55
+ _strategy: "mcpx-api-key"
56
+ },
57
+ apiKeyId: keyDoc.id,
58
+ capabilities: keyDoc.capabilities
59
+ };
60
+ };
61
+ //#endregion
62
+ export { parseBearer, resolveApiKeyAuth };