@payloadcms/plugin-mcp 4.0.0-canary.1 → 4.0.0-canary.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.
- package/dist/collection/getAccessField.d.ts.map +1 -1
- package/dist/collection/getAccessField.js +24 -9
- package/dist/collection/getAccessField.js.map +1 -1
- package/dist/collection/index.d.ts.map +1 -1
- package/dist/collection/index.js +71 -26
- package/dist/collection/index.js.map +1 -1
- package/dist/components/APIKeyField/index.client.d.ts +9 -0
- package/dist/components/APIKeyField/index.client.d.ts.map +1 -0
- package/dist/components/APIKeyField/index.client.js +85 -0
- package/dist/components/APIKeyField/index.client.js.map +1 -0
- package/dist/components/APIKeyField/index.css +105 -0
- package/dist/components/APIKeysEmptyState/index.client.d.ts +4 -0
- package/dist/components/APIKeysEmptyState/index.client.d.ts.map +1 -0
- package/dist/components/APIKeysEmptyState/index.client.js +21 -0
- package/dist/components/APIKeysEmptyState/index.client.js.map +1 -0
- package/dist/components/AccessField/index.client.d.ts.map +1 -1
- package/dist/components/AccessField/index.client.js +139 -197
- package/dist/components/AccessField/index.client.js.map +1 -1
- package/dist/components/AccessField/index.css +50 -44
- package/dist/components/SettingsMenu/index.client.d.ts +8 -0
- package/dist/components/SettingsMenu/index.client.d.ts.map +1 -0
- package/dist/components/SettingsMenu/index.client.js +24 -0
- package/dist/components/SettingsMenu/index.client.js.map +1 -0
- package/dist/endpoint/access.js +16 -0
- package/dist/endpoint/access.js.map +1 -1
- package/dist/exports/client.d.ts +3 -0
- package/dist/exports/client.d.ts.map +1 -1
- package/dist/exports/client.js +3 -0
- package/dist/exports/client.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +51 -3
- package/dist/index.js.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.js +2 -0
- package/dist/mcp/buildMcpServer.js.map +1 -1
- package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/authTools.js +44 -6
- package/dist/mcp/builtin/collections/authTools.js.map +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +10 -19
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.js +7 -0
- package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findTool.js +41 -22
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +7 -0
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +12 -21
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
- package/dist/mcp/builtin/getConfigInfoTool.js +7 -0
- package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findTool.js +15 -20
- package/dist/mcp/builtin/globals/findTool.js.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +7 -0
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +10 -19
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/builtinTools.d.ts +2 -10
- package/dist/mcp/builtinTools.d.ts.map +1 -1
- package/dist/mcp/builtinTools.js +2 -10
- package/dist/mcp/builtinTools.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +24 -10
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/translations/index.d.ts +11 -0
- package/dist/translations/index.d.ts.map +1 -0
- package/dist/translations/index.js +92 -0
- package/dist/translations/index.js.map +1 -0
- package/dist/translations/languages/ar.d.ts +31 -0
- package/dist/translations/languages/ar.d.ts.map +1 -0
- package/dist/translations/languages/ar.js +34 -0
- package/dist/translations/languages/ar.js.map +1 -0
- package/dist/translations/languages/az.d.ts +31 -0
- package/dist/translations/languages/az.d.ts.map +1 -0
- package/dist/translations/languages/az.js +34 -0
- package/dist/translations/languages/az.js.map +1 -0
- package/dist/translations/languages/bg.d.ts +31 -0
- package/dist/translations/languages/bg.d.ts.map +1 -0
- package/dist/translations/languages/bg.js +34 -0
- package/dist/translations/languages/bg.js.map +1 -0
- package/dist/translations/languages/bnBd.d.ts +31 -0
- package/dist/translations/languages/bnBd.d.ts.map +1 -0
- package/dist/translations/languages/bnBd.js +34 -0
- package/dist/translations/languages/bnBd.js.map +1 -0
- package/dist/translations/languages/bnIn.d.ts +31 -0
- package/dist/translations/languages/bnIn.d.ts.map +1 -0
- package/dist/translations/languages/bnIn.js +34 -0
- package/dist/translations/languages/bnIn.js.map +1 -0
- package/dist/translations/languages/ca.d.ts +31 -0
- package/dist/translations/languages/ca.d.ts.map +1 -0
- package/dist/translations/languages/ca.js +34 -0
- package/dist/translations/languages/ca.js.map +1 -0
- package/dist/translations/languages/cs.d.ts +31 -0
- package/dist/translations/languages/cs.d.ts.map +1 -0
- package/dist/translations/languages/cs.js +34 -0
- package/dist/translations/languages/cs.js.map +1 -0
- package/dist/translations/languages/da.d.ts +31 -0
- package/dist/translations/languages/da.d.ts.map +1 -0
- package/dist/translations/languages/da.js +34 -0
- package/dist/translations/languages/da.js.map +1 -0
- package/dist/translations/languages/de.d.ts +31 -0
- package/dist/translations/languages/de.d.ts.map +1 -0
- package/dist/translations/languages/de.js +34 -0
- package/dist/translations/languages/de.js.map +1 -0
- package/dist/translations/languages/en.d.ts +31 -0
- package/dist/translations/languages/en.d.ts.map +1 -0
- package/dist/translations/languages/en.js +34 -0
- package/dist/translations/languages/en.js.map +1 -0
- package/dist/translations/languages/es.d.ts +31 -0
- package/dist/translations/languages/es.d.ts.map +1 -0
- package/dist/translations/languages/es.js +34 -0
- package/dist/translations/languages/es.js.map +1 -0
- package/dist/translations/languages/et.d.ts +31 -0
- package/dist/translations/languages/et.d.ts.map +1 -0
- package/dist/translations/languages/et.js +34 -0
- package/dist/translations/languages/et.js.map +1 -0
- package/dist/translations/languages/fa.d.ts +31 -0
- package/dist/translations/languages/fa.d.ts.map +1 -0
- package/dist/translations/languages/fa.js +34 -0
- package/dist/translations/languages/fa.js.map +1 -0
- package/dist/translations/languages/fr.d.ts +31 -0
- package/dist/translations/languages/fr.d.ts.map +1 -0
- package/dist/translations/languages/fr.js +34 -0
- package/dist/translations/languages/fr.js.map +1 -0
- package/dist/translations/languages/he.d.ts +31 -0
- package/dist/translations/languages/he.d.ts.map +1 -0
- package/dist/translations/languages/he.js +34 -0
- package/dist/translations/languages/he.js.map +1 -0
- package/dist/translations/languages/hr.d.ts +31 -0
- package/dist/translations/languages/hr.d.ts.map +1 -0
- package/dist/translations/languages/hr.js +34 -0
- package/dist/translations/languages/hr.js.map +1 -0
- package/dist/translations/languages/hu.d.ts +31 -0
- package/dist/translations/languages/hu.d.ts.map +1 -0
- package/dist/translations/languages/hu.js +34 -0
- package/dist/translations/languages/hu.js.map +1 -0
- package/dist/translations/languages/hy.d.ts +31 -0
- package/dist/translations/languages/hy.d.ts.map +1 -0
- package/dist/translations/languages/hy.js +34 -0
- package/dist/translations/languages/hy.js.map +1 -0
- package/dist/translations/languages/id.d.ts +31 -0
- package/dist/translations/languages/id.d.ts.map +1 -0
- package/dist/translations/languages/id.js +34 -0
- package/dist/translations/languages/id.js.map +1 -0
- package/dist/translations/languages/is.d.ts +31 -0
- package/dist/translations/languages/is.d.ts.map +1 -0
- package/dist/translations/languages/is.js +34 -0
- package/dist/translations/languages/is.js.map +1 -0
- package/dist/translations/languages/it.d.ts +31 -0
- package/dist/translations/languages/it.d.ts.map +1 -0
- package/dist/translations/languages/it.js +34 -0
- package/dist/translations/languages/it.js.map +1 -0
- package/dist/translations/languages/ja.d.ts +31 -0
- package/dist/translations/languages/ja.d.ts.map +1 -0
- package/dist/translations/languages/ja.js +34 -0
- package/dist/translations/languages/ja.js.map +1 -0
- package/dist/translations/languages/ko.d.ts +31 -0
- package/dist/translations/languages/ko.d.ts.map +1 -0
- package/dist/translations/languages/ko.js +34 -0
- package/dist/translations/languages/ko.js.map +1 -0
- package/dist/translations/languages/lt.d.ts +31 -0
- package/dist/translations/languages/lt.d.ts.map +1 -0
- package/dist/translations/languages/lt.js +34 -0
- package/dist/translations/languages/lt.js.map +1 -0
- package/dist/translations/languages/lv.d.ts +31 -0
- package/dist/translations/languages/lv.d.ts.map +1 -0
- package/dist/translations/languages/lv.js +34 -0
- package/dist/translations/languages/lv.js.map +1 -0
- package/dist/translations/languages/my.d.ts +31 -0
- package/dist/translations/languages/my.d.ts.map +1 -0
- package/dist/translations/languages/my.js +34 -0
- package/dist/translations/languages/my.js.map +1 -0
- package/dist/translations/languages/nb.d.ts +31 -0
- package/dist/translations/languages/nb.d.ts.map +1 -0
- package/dist/translations/languages/nb.js +34 -0
- package/dist/translations/languages/nb.js.map +1 -0
- package/dist/translations/languages/nl.d.ts +31 -0
- package/dist/translations/languages/nl.d.ts.map +1 -0
- package/dist/translations/languages/nl.js +34 -0
- package/dist/translations/languages/nl.js.map +1 -0
- package/dist/translations/languages/pl.d.ts +31 -0
- package/dist/translations/languages/pl.d.ts.map +1 -0
- package/dist/translations/languages/pl.js +34 -0
- package/dist/translations/languages/pl.js.map +1 -0
- package/dist/translations/languages/pt.d.ts +31 -0
- package/dist/translations/languages/pt.d.ts.map +1 -0
- package/dist/translations/languages/pt.js +34 -0
- package/dist/translations/languages/pt.js.map +1 -0
- package/dist/translations/languages/ro.d.ts +31 -0
- package/dist/translations/languages/ro.d.ts.map +1 -0
- package/dist/translations/languages/ro.js +34 -0
- package/dist/translations/languages/ro.js.map +1 -0
- package/dist/translations/languages/rs.d.ts +31 -0
- package/dist/translations/languages/rs.d.ts.map +1 -0
- package/dist/translations/languages/rs.js +34 -0
- package/dist/translations/languages/rs.js.map +1 -0
- package/dist/translations/languages/rsLatin.d.ts +31 -0
- package/dist/translations/languages/rsLatin.d.ts.map +1 -0
- package/dist/translations/languages/rsLatin.js +34 -0
- package/dist/translations/languages/rsLatin.js.map +1 -0
- package/dist/translations/languages/ru.d.ts +31 -0
- package/dist/translations/languages/ru.d.ts.map +1 -0
- package/dist/translations/languages/ru.js +34 -0
- package/dist/translations/languages/ru.js.map +1 -0
- package/dist/translations/languages/sk.d.ts +31 -0
- package/dist/translations/languages/sk.d.ts.map +1 -0
- package/dist/translations/languages/sk.js +34 -0
- package/dist/translations/languages/sk.js.map +1 -0
- package/dist/translations/languages/sl.d.ts +31 -0
- package/dist/translations/languages/sl.d.ts.map +1 -0
- package/dist/translations/languages/sl.js +34 -0
- package/dist/translations/languages/sl.js.map +1 -0
- package/dist/translations/languages/sv.d.ts +31 -0
- package/dist/translations/languages/sv.d.ts.map +1 -0
- package/dist/translations/languages/sv.js +34 -0
- package/dist/translations/languages/sv.js.map +1 -0
- package/dist/translations/languages/ta.d.ts +31 -0
- package/dist/translations/languages/ta.d.ts.map +1 -0
- package/dist/translations/languages/ta.js +34 -0
- package/dist/translations/languages/ta.js.map +1 -0
- package/dist/translations/languages/th.d.ts +31 -0
- package/dist/translations/languages/th.d.ts.map +1 -0
- package/dist/translations/languages/th.js +34 -0
- package/dist/translations/languages/th.js.map +1 -0
- package/dist/translations/languages/tr.d.ts +31 -0
- package/dist/translations/languages/tr.d.ts.map +1 -0
- package/dist/translations/languages/tr.js +34 -0
- package/dist/translations/languages/tr.js.map +1 -0
- package/dist/translations/languages/uk.d.ts +31 -0
- package/dist/translations/languages/uk.d.ts.map +1 -0
- package/dist/translations/languages/uk.js +34 -0
- package/dist/translations/languages/uk.js.map +1 -0
- package/dist/translations/languages/vi.d.ts +31 -0
- package/dist/translations/languages/vi.d.ts.map +1 -0
- package/dist/translations/languages/vi.js +34 -0
- package/dist/translations/languages/vi.js.map +1 -0
- package/dist/translations/languages/zh.d.ts +31 -0
- package/dist/translations/languages/zh.d.ts.map +1 -0
- package/dist/translations/languages/zh.js +34 -0
- package/dist/translations/languages/zh.js.map +1 -0
- package/dist/translations/languages/zhTw.d.ts +31 -0
- package/dist/translations/languages/zhTw.d.ts.map +1 -0
- package/dist/translations/languages/zhTw.js +34 -0
- package/dist/translations/languages/zhTw.js.map +1 -0
- package/dist/translations/types.d.ts +32 -0
- package/dist/translations/types.d.ts.map +1 -0
- package/dist/translations/types.js +3 -0
- package/dist/translations/types.js.map +1 -0
- package/dist/types.d.ts +13 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -6
- package/src/collection/getAccessField.ts +33 -13
- package/src/collection/index.ts +63 -22
- package/src/components/APIKeyField/index.client.tsx +68 -0
- package/src/components/APIKeyField/index.css +105 -0
- package/src/components/APIKeysEmptyState/index.client.tsx +33 -0
- package/src/components/AccessField/index.client.tsx +160 -211
- package/src/components/AccessField/index.css +50 -44
- package/src/components/SettingsMenu/index.client.tsx +30 -0
- package/src/endpoint/access.ts +12 -0
- package/src/exports/client.ts +3 -0
- package/src/index.ts +52 -3
- package/src/mcp/buildMcpServer.ts +2 -0
- package/src/mcp/builtin/collections/authTools.ts +45 -9
- package/src/mcp/builtin/collections/createTool.ts +10 -13
- package/src/mcp/builtin/collections/deleteTool.ts +7 -0
- package/src/mcp/builtin/collections/findTool.ts +53 -16
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +7 -0
- package/src/mcp/builtin/collections/updateTool.ts +11 -14
- package/src/mcp/builtin/getConfigInfoTool.ts +7 -0
- package/src/mcp/builtin/globals/findTool.ts +22 -16
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +7 -0
- package/src/mcp/builtin/globals/updateTool.ts +11 -14
- package/src/mcp/builtinTools.ts +9 -12
- package/src/mcp/sanitizeMCPConfig.ts +15 -11
- package/src/translations/index.ts +105 -0
- package/src/translations/languages/ar.ts +38 -0
- package/src/translations/languages/az.ts +38 -0
- package/src/translations/languages/bg.ts +39 -0
- package/src/translations/languages/bnBd.ts +39 -0
- package/src/translations/languages/bnIn.ts +39 -0
- package/src/translations/languages/ca.ts +39 -0
- package/src/translations/languages/cs.ts +39 -0
- package/src/translations/languages/da.ts +38 -0
- package/src/translations/languages/de.ts +39 -0
- package/src/translations/languages/en.ts +39 -0
- package/src/translations/languages/es.ts +39 -0
- package/src/translations/languages/et.ts +38 -0
- package/src/translations/languages/fa.ts +39 -0
- package/src/translations/languages/fr.ts +39 -0
- package/src/translations/languages/he.ts +37 -0
- package/src/translations/languages/hr.ts +39 -0
- package/src/translations/languages/hu.ts +39 -0
- package/src/translations/languages/hy.ts +39 -0
- package/src/translations/languages/id.ts +39 -0
- package/src/translations/languages/is.ts +39 -0
- package/src/translations/languages/it.ts +39 -0
- package/src/translations/languages/ja.ts +39 -0
- package/src/translations/languages/ko.ts +39 -0
- package/src/translations/languages/lt.ts +39 -0
- package/src/translations/languages/lv.ts +38 -0
- package/src/translations/languages/my.ts +39 -0
- package/src/translations/languages/nb.ts +39 -0
- package/src/translations/languages/nl.ts +39 -0
- package/src/translations/languages/pl.ts +38 -0
- package/src/translations/languages/pt.ts +39 -0
- package/src/translations/languages/ro.ts +39 -0
- package/src/translations/languages/rs.ts +38 -0
- package/src/translations/languages/rsLatin.ts +38 -0
- package/src/translations/languages/ru.ts +39 -0
- package/src/translations/languages/sk.ts +39 -0
- package/src/translations/languages/sl.ts +38 -0
- package/src/translations/languages/sv.ts +39 -0
- package/src/translations/languages/ta.ts +39 -0
- package/src/translations/languages/th.ts +38 -0
- package/src/translations/languages/tr.ts +38 -0
- package/src/translations/languages/uk.ts +39 -0
- package/src/translations/languages/vi.ts +39 -0
- package/src/translations/languages/zh.ts +36 -0
- package/src/translations/languages/zhTw.ts +36 -0
- package/src/translations/types.ts +34 -0
- package/src/types.ts +13 -5
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { PopupList, useConfig, useTranslation } from '@payloadcms/ui';
|
|
4
|
+
import { formatAdminURL } from 'payload/shared';
|
|
5
|
+
import React from 'react';
|
|
6
|
+
/**
|
|
7
|
+
* Entry in the user menu's Settings sub-popup linking to the API keys
|
|
8
|
+
* collection. The collection is excluded from the main nav
|
|
9
|
+
* (`admin.group: false`) and managed from here instead.
|
|
10
|
+
*/ export const MCPSettingsMenu = ()=>{
|
|
11
|
+
const { config } = useConfig();
|
|
12
|
+
const { t } = useTranslation();
|
|
13
|
+
return /*#__PURE__*/ _jsx(PopupList.MenuItem, {
|
|
14
|
+
children: /*#__PURE__*/ _jsx(PopupList.Button, {
|
|
15
|
+
href: formatAdminURL({
|
|
16
|
+
adminRoute: config.routes.admin,
|
|
17
|
+
path: '/collections/payload-mcp-api-keys'
|
|
18
|
+
}),
|
|
19
|
+
children: t('plugin-mcp:manageAPIKeys')
|
|
20
|
+
})
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=index.client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/components/SettingsMenu/index.client.tsx"],"sourcesContent":["'use client'\n\nimport { PopupList, useConfig, useTranslation } from '@payloadcms/ui'\nimport { formatAdminURL } from 'payload/shared'\nimport React from 'react'\n\nimport type { PluginMCPTranslationKeys, PluginMCPTranslations } from '../../translations/index.js'\n\n/**\n * Entry in the user menu's Settings sub-popup linking to the API keys\n * collection. The collection is excluded from the main nav\n * (`admin.group: false`) and managed from here instead.\n */\nexport const MCPSettingsMenu: React.FC = () => {\n const { config } = useConfig()\n const { t } = useTranslation<PluginMCPTranslations, PluginMCPTranslationKeys>()\n\n return (\n <PopupList.MenuItem>\n <PopupList.Button\n href={formatAdminURL({\n adminRoute: config.routes.admin,\n path: '/collections/payload-mcp-api-keys',\n })}\n >\n {t('plugin-mcp:manageAPIKeys')}\n </PopupList.Button>\n </PopupList.MenuItem>\n )\n}\n"],"names":["PopupList","useConfig","useTranslation","formatAdminURL","React","MCPSettingsMenu","config","t","MenuItem","Button","href","adminRoute","routes","admin","path"],"mappings":"AAAA;;AAEA,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,iBAAgB;AACrE,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,OAAOC,WAAW,QAAO;AAIzB;;;;CAIC,GACD,OAAO,MAAMC,kBAA4B;IACvC,MAAM,EAAEC,MAAM,EAAE,GAAGL;IACnB,MAAM,EAAEM,CAAC,EAAE,GAAGL;IAEd,qBACE,KAACF,UAAUQ,QAAQ;kBACjB,cAAA,KAACR,UAAUS,MAAM;YACfC,MAAMP,eAAe;gBACnBQ,YAAYL,OAAOM,MAAM,CAACC,KAAK;gBAC/BC,MAAM;YACR;sBAECP,EAAE;;;AAIX,EAAC"}
|
package/dist/endpoint/access.js
CHANGED
|
@@ -93,6 +93,22 @@ const getAPIKeyDoc = async ({ logger, overrideApiKey, pluginConfig, req })=>{
|
|
|
93
93
|
if (!user) {
|
|
94
94
|
throw new UnauthorizedError();
|
|
95
95
|
}
|
|
96
|
+
try {
|
|
97
|
+
await req.payload.db.updateOne({
|
|
98
|
+
id: doc.id,
|
|
99
|
+
collection: 'payload-mcp-api-keys',
|
|
100
|
+
data: {
|
|
101
|
+
lastUsed: new Date().toISOString()
|
|
102
|
+
},
|
|
103
|
+
req,
|
|
104
|
+
returning: false
|
|
105
|
+
});
|
|
106
|
+
} catch (err) {
|
|
107
|
+
logger.warn({
|
|
108
|
+
err,
|
|
109
|
+
msg: 'Failed to update MCP API key last-used timestamp'
|
|
110
|
+
});
|
|
111
|
+
}
|
|
96
112
|
return {
|
|
97
113
|
...doc,
|
|
98
114
|
user: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/endpoint/access.ts"],"sourcesContent":["import type { DefaultDocumentIDType, PayloadRequest, TypedUser } from 'payload'\n\nimport crypto from 'crypto'\nimport { UnauthorizedError } from 'payload'\n\nimport type { AuthorizedMCP, MCPAPIKeysDoc } from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\n\n/**\n * Resolves the API key (or dev-mode session) and returns the items the caller\n * may use. Denied items are dropped from the array.\n */\nexport const getAuthorizedMCP: (args: { req: PayloadRequest }) => Promise<AuthorizedMCP> = async ({\n req,\n}) => {\n const logger = getLogger({ payload: req.payload })\n const pluginConfig = getPluginConfig({ config: req.payload.config })\n\n const authHeader = req.headers.get('Authorization')\n const hasBearerToken = authHeader?.startsWith('Bearer ')\n\n const buildAuthorized = (apiKeyDoc: MCPAPIKeysDoc): AuthorizedMCP => ({\n items: pluginConfig.items.filter((item) => {\n switch (item.type) {\n case 'collectionTool':\n return apiKeyDoc.access.collections?.[item.collectionSlug]?.[item.configKey] !== false\n case 'globalTool':\n return apiKeyDoc.access.globals?.[item.globalSlug]?.[item.configKey] !== false\n case 'prompt':\n return apiKeyDoc.access.prompts?.[item.configKey] !== false\n case 'resource':\n return apiKeyDoc.access.resources?.[item.configKey] !== false\n case 'tool':\n return apiKeyDoc.access.tools?.[item.configKey] !== false\n }\n }),\n overrideAccess:\n typeof apiKeyDoc.overrideAccess === 'boolean' ? apiKeyDoc.overrideAccess : false,\n user: apiKeyDoc.user,\n })\n\n if (pluginConfig.overrideAuth) {\n return await pluginConfig.overrideAuth({\n getAPIKeyDoc: (overrideApiKey) => getAPIKeyDoc({ logger, overrideApiKey, pluginConfig, req }),\n getAuthorizedMCP: ({ apiKeyDoc }) => buildAuthorized(apiKeyDoc),\n pluginConfig,\n req,\n })\n }\n\n if (process.env.NODE_ENV === 'development' && !hasBearerToken) {\n logger.info('Dev mode: skipping API key check, using session user')\n return buildAuthorized({\n id: -1,\n access: {},\n overrideAccess: true,\n user: req.user ?? null,\n })\n }\n\n return buildAuthorized(await getAPIKeyDoc({ logger, pluginConfig, req }))\n}\n\nconst getAPIKeyDoc = async ({\n logger,\n overrideApiKey,\n pluginConfig,\n req,\n}: {\n logger: ReturnType<typeof getLogger>\n overrideApiKey?: string\n pluginConfig: ReturnType<typeof getPluginConfig>\n req: PayloadRequest\n}): Promise<MCPAPIKeysDoc> => {\n const authHeader = req.headers.get('Authorization')\n const hasBearerToken = authHeader?.startsWith('Bearer ')\n\n const apiKey =\n overrideApiKey ?? (hasBearerToken ? authHeader?.replace('Bearer ', '').trim() || null : null)\n\n if (!apiKey) {\n throw new UnauthorizedError()\n }\n\n const sha256APIKeyIndex = crypto\n .createHmac('sha256', req.payload.secret)\n .update(apiKey)\n .digest('hex')\n\n const doc = await req.payload.db.findOne<MCPAPIKeysDoc>({\n collection: 'payload-mcp-api-keys',\n req,\n where: {\n apiKeyIndex: { equals: sha256APIKeyIndex },\n },\n })\n\n if (!doc || !doc.user) {\n throw new UnauthorizedError()\n }\n\n logger.info('API Key is valid')\n\n const userRef = doc.user\n const userID =\n typeof userRef === 'object' && userRef !== null && 'id' in userRef\n ? userRef.id\n : (userRef as unknown as DefaultDocumentIDType)\n\n const user = (await req.payload.findByID({\n id: userID,\n collection: pluginConfig.userCollection,\n depth: 0,\n disableErrors: true,\n req,\n })) as null | TypedUser\n\n if (!user) {\n throw new UnauthorizedError()\n }\n\n return {\n ...doc,\n user: {\n ...user,\n _strategy: 'mcp-api-key' as const,\n collection: pluginConfig.userCollection,\n },\n }\n}\n"],"names":["crypto","UnauthorizedError","getLogger","getPluginConfig","getAuthorizedMCP","req","logger","payload","pluginConfig","config","authHeader","headers","get","hasBearerToken","startsWith","buildAuthorized","apiKeyDoc","items","filter","item","type","access","collections","collectionSlug","configKey","globals","globalSlug","prompts","resources","tools","overrideAccess","user","overrideAuth","getAPIKeyDoc","overrideApiKey","process","env","NODE_ENV","info","id","apiKey","replace","trim","sha256APIKeyIndex","createHmac","secret","update","digest","doc","db","findOne","collection","where","apiKeyIndex","equals","userRef","userID","findByID","userCollection","depth","disableErrors","_strategy"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAC3B,SAASC,iBAAiB,QAAQ,UAAS;AAI3C,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,eAAe,QAAQ,8BAA6B;AAE7D;;;CAGC,GACD,OAAO,MAAMC,mBAA8E,OAAO,EAChGC,GAAG,EACJ;IACC,MAAMC,SAASJ,UAAU;QAAEK,SAASF,IAAIE,OAAO;IAAC;IAChD,MAAMC,eAAeL,gBAAgB;QAAEM,QAAQJ,IAAIE,OAAO,CAACE,MAAM;IAAC;IAElE,MAAMC,aAAaL,IAAIM,OAAO,CAACC,GAAG,CAAC;IACnC,MAAMC,iBAAiBH,YAAYI,WAAW;IAE9C,MAAMC,kBAAkB,CAACC,YAA6C,CAAA;YACpEC,OAAOT,aAAaS,KAAK,CAACC,MAAM,CAAC,CAACC;gBAChC,OAAQA,KAAKC,IAAI;oBACf,KAAK;wBACH,OAAOJ,UAAUK,MAAM,CAACC,WAAW,EAAE,CAACH,KAAKI,cAAc,CAAC,EAAE,CAACJ,KAAKK,SAAS,CAAC,KAAK;oBACnF,KAAK;wBACH,OAAOR,UAAUK,MAAM,CAACI,OAAO,EAAE,CAACN,KAAKO,UAAU,CAAC,EAAE,CAACP,KAAKK,SAAS,CAAC,KAAK;oBAC3E,KAAK;wBACH,OAAOR,UAAUK,MAAM,CAACM,OAAO,EAAE,CAACR,KAAKK,SAAS,CAAC,KAAK;oBACxD,KAAK;wBACH,OAAOR,UAAUK,MAAM,CAACO,SAAS,EAAE,CAACT,KAAKK,SAAS,CAAC,KAAK;oBAC1D,KAAK;wBACH,OAAOR,UAAUK,MAAM,CAACQ,KAAK,EAAE,CAACV,KAAKK,SAAS,CAAC,KAAK;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QX;YAAkB;QAC3C;IACF;IAEA,IAAI,CAACK,OAAO,CAACA,IAAIjB,IAAI,EAAE;QACrB,MAAM,IAAI9B;IACZ;IAEAK,OAAOgC,IAAI,CAAC;IAEZ,MAAMiB,UAAUP,IAAIjB,IAAI;IACxB,MAAMyB,SACJ,OAAOD,YAAY,YAAYA,YAAY,QAAQ,QAAQA,UACvDA,QAAQhB,EAAE,GACTgB;IAEP,MAAMxB,OAAQ,MAAM1B,IAAIE,OAAO,CAACkD,QAAQ,CAAC;QACvClB,IAAIiB;QACJL,YAAY3C,aAAakD,cAAc;QACvCC,OAAO;QACPC,eAAe;QACfvD;IACF;IAEA,IAAI,CAAC0B,MAAM;QACT,MAAM,IAAI9B;IACZ;IAEA,OAAO;QACL,
|
|
1
|
+
{"version":3,"sources":["../../src/endpoint/access.ts"],"sourcesContent":["import type { DefaultDocumentIDType, PayloadRequest, TypedUser } from 'payload'\n\nimport crypto from 'crypto'\nimport { UnauthorizedError } from 'payload'\n\nimport type { AuthorizedMCP, MCPAPIKeysDoc } from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\n\n/**\n * Resolves the API key (or dev-mode session) and returns the items the caller\n * may use. Denied items are dropped from the array.\n */\nexport const getAuthorizedMCP: (args: { req: PayloadRequest }) => Promise<AuthorizedMCP> = async ({\n req,\n}) => {\n const logger = getLogger({ payload: req.payload })\n const pluginConfig = getPluginConfig({ config: req.payload.config })\n\n const authHeader = req.headers.get('Authorization')\n const hasBearerToken = authHeader?.startsWith('Bearer ')\n\n const buildAuthorized = (apiKeyDoc: MCPAPIKeysDoc): AuthorizedMCP => ({\n items: pluginConfig.items.filter((item) => {\n switch (item.type) {\n case 'collectionTool':\n return apiKeyDoc.access.collections?.[item.collectionSlug]?.[item.configKey] !== false\n case 'globalTool':\n return apiKeyDoc.access.globals?.[item.globalSlug]?.[item.configKey] !== false\n case 'prompt':\n return apiKeyDoc.access.prompts?.[item.configKey] !== false\n case 'resource':\n return apiKeyDoc.access.resources?.[item.configKey] !== false\n case 'tool':\n return apiKeyDoc.access.tools?.[item.configKey] !== false\n }\n }),\n overrideAccess:\n typeof apiKeyDoc.overrideAccess === 'boolean' ? apiKeyDoc.overrideAccess : false,\n user: apiKeyDoc.user,\n })\n\n if (pluginConfig.overrideAuth) {\n return await pluginConfig.overrideAuth({\n getAPIKeyDoc: (overrideApiKey) => getAPIKeyDoc({ logger, overrideApiKey, pluginConfig, req }),\n getAuthorizedMCP: ({ apiKeyDoc }) => buildAuthorized(apiKeyDoc),\n pluginConfig,\n req,\n })\n }\n\n if (process.env.NODE_ENV === 'development' && !hasBearerToken) {\n logger.info('Dev mode: skipping API key check, using session user')\n return buildAuthorized({\n id: -1,\n access: {},\n overrideAccess: true,\n user: req.user ?? null,\n })\n }\n\n return buildAuthorized(await getAPIKeyDoc({ logger, pluginConfig, req }))\n}\n\nconst getAPIKeyDoc = async ({\n logger,\n overrideApiKey,\n pluginConfig,\n req,\n}: {\n logger: ReturnType<typeof getLogger>\n overrideApiKey?: string\n pluginConfig: ReturnType<typeof getPluginConfig>\n req: PayloadRequest\n}): Promise<MCPAPIKeysDoc> => {\n const authHeader = req.headers.get('Authorization')\n const hasBearerToken = authHeader?.startsWith('Bearer ')\n\n const apiKey =\n overrideApiKey ?? (hasBearerToken ? authHeader?.replace('Bearer ', '').trim() || null : null)\n\n if (!apiKey) {\n throw new UnauthorizedError()\n }\n\n const sha256APIKeyIndex = crypto\n .createHmac('sha256', req.payload.secret)\n .update(apiKey)\n .digest('hex')\n\n const doc = await req.payload.db.findOne<MCPAPIKeysDoc>({\n collection: 'payload-mcp-api-keys',\n req,\n where: {\n apiKeyIndex: { equals: sha256APIKeyIndex },\n },\n })\n\n if (!doc || !doc.user) {\n throw new UnauthorizedError()\n }\n\n logger.info('API Key is valid')\n\n const userRef = doc.user\n const userID =\n typeof userRef === 'object' && userRef !== null && 'id' in userRef\n ? userRef.id\n : (userRef as unknown as DefaultDocumentIDType)\n\n const user = (await req.payload.findByID({\n id: userID,\n collection: pluginConfig.userCollection,\n depth: 0,\n disableErrors: true,\n req,\n })) as null | TypedUser\n\n if (!user) {\n throw new UnauthorizedError()\n }\n\n try {\n await req.payload.db.updateOne({\n id: doc.id,\n collection: 'payload-mcp-api-keys',\n data: { lastUsed: new Date().toISOString() },\n req,\n returning: false,\n })\n } catch (err) {\n logger.warn({ err, msg: 'Failed to update MCP API key last-used timestamp' })\n }\n\n return {\n ...doc,\n user: {\n ...user,\n _strategy: 'mcp-api-key' as const,\n collection: pluginConfig.userCollection,\n },\n }\n}\n"],"names":["crypto","UnauthorizedError","getLogger","getPluginConfig","getAuthorizedMCP","req","logger","payload","pluginConfig","config","authHeader","headers","get","hasBearerToken","startsWith","buildAuthorized","apiKeyDoc","items","filter","item","type","access","collections","collectionSlug","configKey","globals","globalSlug","prompts","resources","tools","overrideAccess","user","overrideAuth","getAPIKeyDoc","overrideApiKey","process","env","NODE_ENV","info","id","apiKey","replace","trim","sha256APIKeyIndex","createHmac","secret","update","digest","doc","db","findOne","collection","where","apiKeyIndex","equals","userRef","userID","findByID","userCollection","depth","disableErrors","updateOne","data","lastUsed","Date","toISOString","returning","err","warn","msg","_strategy"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAC3B,SAASC,iBAAiB,QAAQ,UAAS;AAI3C,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,eAAe,QAAQ,8BAA6B;AAE7D;;;CAGC,GACD,OAAO,MAAMC,mBAA8E,OAAO,EAChGC,GAAG,EACJ;IACC,MAAMC,SAASJ,UAAU;QAAEK,SAASF,IAAIE,OAAO;IAAC;IAChD,MAAMC,eAAeL,gBAAgB;QAAEM,QAAQJ,IAAIE,OAAO,CAACE,MAAM;IAAC;IAElE,MAAMC,aAAaL,IAAIM,OAAO,CAACC,GAAG,CAAC;IACnC,MAAMC,iBAAiBH,YAAYI,WAAW;IAE9C,MAAMC,kBAAkB,CAACC,YAA6C,CAAA;YACpE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ACF,EAAE,OAAOC,KAAK;QACZ7D,OAAO8D,IAAI,CAAC;YAAED;YAAKE,KAAK;QAAmD;IAC7E;IAEA,OAAO;QACL,GAAGrB,GAAG;QACNjB,MAAM;YACJ,GAAGA,IAAI;YACPuC,WAAW;YACXnB,YAAY3C,aAAakD,cAAc;QACzC;IACF;AACF"}
|
package/dist/exports/client.d.ts
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
1
|
export { AccessField } from '../components/AccessField/index.client.js';
|
|
2
|
+
export { APIKeyField } from '../components/APIKeyField/index.client.js';
|
|
3
|
+
export { APIKeysEmptyState } from '../components/APIKeysEmptyState/index.client.js';
|
|
4
|
+
export { MCPSettingsMenu } from '../components/SettingsMenu/index.client.js';
|
|
2
5
|
//# sourceMappingURL=client.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/exports/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAA"}
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/exports/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAA;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAA;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iDAAiD,CAAA;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAA"}
|
package/dist/exports/client.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
export { AccessField } from '../components/AccessField/index.client.js';
|
|
3
|
+
export { APIKeyField } from '../components/APIKeyField/index.client.js';
|
|
4
|
+
export { APIKeysEmptyState } from '../components/APIKeysEmptyState/index.client.js';
|
|
5
|
+
export { MCPSettingsMenu } from '../components/SettingsMenu/index.client.js';
|
|
3
6
|
|
|
4
7
|
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { AccessField } from '../components/AccessField/index.client.js'\n"],"names":["AccessField"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,4CAA2C"}
|
|
1
|
+
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { AccessField } from '../components/AccessField/index.client.js'\nexport { APIKeyField } from '../components/APIKeyField/index.client.js'\nexport { APIKeysEmptyState } from '../components/APIKeysEmptyState/index.client.js'\nexport { MCPSettingsMenu } from '../components/SettingsMenu/index.client.js'\n"],"names":["AccessField","APIKeyField","APIKeysEmptyState","MCPSettingsMenu"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,4CAA2C;AACvE,SAASC,WAAW,QAAQ,4CAA2C;AACvE,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,eAAe,QAAQ,6CAA4C"}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAO1F,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,cAAc;QAC7B,UAAU,EAAE,SAAS,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,CAAA;KACjD;IACD,UAAU,iBAAiB;QACzB,uFAAuF;QACvF,wBAAwB,EAAE,eAAe,CAAA;KAC1C;CACF;AAED,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,CAAA;AAExE,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAElG,eAAO,MAAM,SAAS,wDAqFpB,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -2,14 +2,14 @@ import { defaultUserCollection, definePlugin } from 'payload';
|
|
|
2
2
|
import { getAPIKeysCollection } from './collection/index.js';
|
|
3
3
|
import { mcpEndpoint } from './endpoint/index.js';
|
|
4
4
|
import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js';
|
|
5
|
+
import { translations } from './translations/index.js';
|
|
5
6
|
export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
|
|
6
7
|
export const mcpPlugin = definePlugin({
|
|
7
8
|
slug: '@payloadcms/plugin-mcp',
|
|
8
9
|
order: 10,
|
|
9
10
|
plugin: ({ config, plugins, ...rawConfig })=>{
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
// Pre-seed the default user collection to prevent that.
|
|
11
|
+
// If a project has no auth collection yet, add the default users collection
|
|
12
|
+
// so the relationship target and default `userCollection` exist.
|
|
13
13
|
if (!config.admin?.user) {
|
|
14
14
|
const firstCollectionWithAuth = (config.collections ?? []).find(({ auth })=>Boolean(auth));
|
|
15
15
|
if (!firstCollectionWithAuth) {
|
|
@@ -31,6 +31,27 @@ export const mcpPlugin = definePlugin({
|
|
|
31
31
|
(config.collections ??= []).push(getAPIKeysCollection({
|
|
32
32
|
pluginConfig
|
|
33
33
|
}));
|
|
34
|
+
if (!config.i18n) {
|
|
35
|
+
config.i18n = {};
|
|
36
|
+
}
|
|
37
|
+
if (!config.i18n.translations) {
|
|
38
|
+
config.i18n.translations = {};
|
|
39
|
+
}
|
|
40
|
+
const supportedLanguageKeys = config.i18n.supportedLanguages ? Object.keys(config.i18n.supportedLanguages) : [
|
|
41
|
+
'en'
|
|
42
|
+
];
|
|
43
|
+
for (const lang of supportedLanguageKeys){
|
|
44
|
+
const pluginEntry = translations[lang];
|
|
45
|
+
if (!pluginEntry) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const typedLocale = lang;
|
|
49
|
+
const existing = config.i18n.translations[typedLocale] ?? {};
|
|
50
|
+
config.i18n.translations[typedLocale] = {
|
|
51
|
+
...existing,
|
|
52
|
+
'plugin-mcp': pluginEntry.translations['plugin-mcp']
|
|
53
|
+
};
|
|
54
|
+
}
|
|
34
55
|
// Keep the API-keys collection registered even when disabled, so DB schema
|
|
35
56
|
// and generated types don't drift between enabled/disabled environments.
|
|
36
57
|
if (pluginConfig.disabled) {
|
|
@@ -38,6 +59,21 @@ export const mcpPlugin = definePlugin({
|
|
|
38
59
|
}
|
|
39
60
|
return {
|
|
40
61
|
...config,
|
|
62
|
+
admin: {
|
|
63
|
+
...config.admin,
|
|
64
|
+
components: {
|
|
65
|
+
...config.admin?.components,
|
|
66
|
+
userMenuSettingsItems: [
|
|
67
|
+
...config.admin?.components?.userMenuSettingsItems ?? [],
|
|
68
|
+
{
|
|
69
|
+
group: 'MCP',
|
|
70
|
+
items: [
|
|
71
|
+
'@payloadcms/plugin-mcp/client#MCPSettingsMenu'
|
|
72
|
+
]
|
|
73
|
+
}
|
|
74
|
+
]
|
|
75
|
+
}
|
|
76
|
+
},
|
|
41
77
|
endpoints: [
|
|
42
78
|
...config.endpoints ?? [],
|
|
43
79
|
// Payload prefixes /api, so the full path is /api/mcp.
|
|
@@ -45,6 +81,18 @@ export const mcpPlugin = definePlugin({
|
|
|
45
81
|
handler: mcpEndpoint,
|
|
46
82
|
method: 'post',
|
|
47
83
|
path: '/mcp'
|
|
84
|
+
},
|
|
85
|
+
// Streamable HTTP's optional server=>client GET stream. We don't offer
|
|
86
|
+
// one, so answer 405 per spec-— clients then skip it cleanly
|
|
87
|
+
{
|
|
88
|
+
handler: ()=>new Response(null, {
|
|
89
|
+
headers: {
|
|
90
|
+
Allow: 'POST'
|
|
91
|
+
},
|
|
92
|
+
status: 405
|
|
93
|
+
}),
|
|
94
|
+
method: 'get',
|
|
95
|
+
path: '/mcp'
|
|
48
96
|
}
|
|
49
97
|
]
|
|
50
98
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { defaultUserCollection, definePlugin } from 'payload'\n\nimport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'\n\nimport { getAPIKeysCollection } from './collection/index.js'\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\n\ndeclare module 'payload' {\n export interface PayloadRequest {\n payloadAPI: 'GraphQL' | 'local' | 'MCP' | 'REST'\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n}\n\nexport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, plugins, ...rawConfig }) => {\n //
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { AcceptedLanguages } from '@payloadcms/translations'\n\nimport { defaultUserCollection, definePlugin } from 'payload'\n\nimport type { PluginDefaultTranslationsObject } from './translations/types.js'\nimport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'\n\nimport { getAPIKeysCollection } from './collection/index.js'\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\nimport { translations } from './translations/index.js'\n\ndeclare module 'payload' {\n export interface PayloadRequest {\n payloadAPI: 'GraphQL' | 'local' | 'MCP' | 'REST'\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n}\n\nexport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, plugins, ...rawConfig }) => {\n // If a project has no auth collection yet, add the default users collection\n // so the relationship target and default `userCollection` exist.\n if (!config.admin?.user) {\n const firstCollectionWithAuth = (config.collections ?? []).find(({ auth }) => Boolean(auth))\n if (!firstCollectionWithAuth) {\n ;(config.collections ??= []).push(defaultUserCollection)\n }\n }\n\n const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: rawConfig })\n\n // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.\n const registered = plugins['@payloadcms/plugin-mcp']\n if (registered) {\n // @ts-expect-error\n registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options\n }\n\n ;(config.collections ??= []).push(getAPIKeysCollection({ pluginConfig }))\n\n if (!config.i18n) {\n config.i18n = {}\n }\n\n if (!config.i18n.translations) {\n config.i18n.translations = {}\n }\n\n const supportedLanguageKeys = config.i18n.supportedLanguages\n ? Object.keys(config.i18n.supportedLanguages)\n : ['en']\n\n for (const lang of supportedLanguageKeys) {\n const pluginEntry = translations[lang as keyof typeof translations]\n if (!pluginEntry) {\n continue\n }\n\n const typedLocale = lang as AcceptedLanguages\n const existing = (config.i18n.translations[typedLocale] ?? {}) as Record<string, unknown>\n config.i18n.translations[typedLocale] = {\n ...existing,\n 'plugin-mcp': pluginEntry.translations['plugin-mcp'],\n } as PluginDefaultTranslationsObject\n }\n\n // Keep the API-keys collection registered even when disabled, so DB schema\n // and generated types don't drift between enabled/disabled environments.\n if (pluginConfig.disabled) {\n return config\n }\n\n return {\n ...config,\n admin: {\n ...config.admin,\n components: {\n ...config.admin?.components,\n userMenuSettingsItems: [\n ...(config.admin?.components?.userMenuSettingsItems ?? []),\n {\n group: 'MCP',\n items: ['@payloadcms/plugin-mcp/client#MCPSettingsMenu'],\n },\n ],\n },\n },\n endpoints: [\n ...(config.endpoints ?? []),\n // Payload prefixes /api, so the full path is /api/mcp.\n { handler: mcpEndpoint, method: 'post', path: '/mcp' },\n // Streamable HTTP's optional server=>client GET stream. We don't offer\n // one, so answer 405 per spec-— clients then skip it cleanly\n {\n handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),\n method: 'get',\n path: '/mcp',\n },\n ],\n }\n },\n})\n"],"names":["defaultUserCollection","definePlugin","getAPIKeysCollection","mcpEndpoint","sanitizeMCPConfig","translations","defineCollectionTool","defineGlobalTool","definePrompt","defineTool","mcpPlugin","slug","order","plugin","config","plugins","rawConfig","admin","user","firstCollectionWithAuth","collections","find","auth","Boolean","push","pluginConfig","registered","sanitizedOptions","i18n","supportedLanguageKeys","supportedLanguages","Object","keys","lang","pluginEntry","typedLocale","existing","disabled","components","userMenuSettingsItems","group","items","endpoints","handler","method","path","Response","headers","Allow","status"],"mappings":"AAEA,SAASA,qBAAqB,EAAEC,YAAY,QAAQ,UAAS;AAK7D,SAASC,oBAAoB,QAAQ,wBAAuB;AAC5D,SAASC,WAAW,QAAQ,sBAAqB;AACjD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,YAAY,QAAQ,0BAAyB;AActD,SAASC,oBAAoB,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,UAAU,QAAQ,kBAAiB;AAElG,OAAO,MAAMC,YAAYT,aAA8B;IACrDU,MAAM;IACNC,OAAO;IACPC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,OAAO,EAAE,GAAGC,WAAW;QACxC,4EAA4E;QAC5E,iEAAiE;QACjE,IAAI,CAACF,OAAOG,KAAK,EAAEC,MAAM;YACvB,MAAMC,0BAA0B,AAACL,CAAAA,OAAOM,WAAW,IAAI,EAAE,AAAD,EAAGC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAE,GAAKC,QAAQD;YACtF,IAAI,CAACH,yBAAyB;;gBAC1BL,CAAAA,OAAOM,WAAW,KAAK,EAAE,AAAD,EAAGI,IAAI,CAACxB;YACpC;QAC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AAO;gCAAC;6BAAgD;wBAC1D;qBACD;gBACH;YACF;YACAC,WAAW;mBACL5B,OAAO4B,SAAS,IAAI,EAAE;gBAC1B,uDAAuD;gBACvD;oBAAEC,SAASxC;oBAAayC,QAAQ;oBAAQC,MAAM;gBAAO;gBACrD,uEAAuE;gBACvE,6DAA6D;gBAC7D;oBACEF,SAAS,IAAM,IAAIG,SAAS,MAAM;4BAAEC,SAAS;gCAAEC,OAAO;4BAAO;4BAAGC,QAAQ;wBAAI;oBAC5EL,QAAQ;oBACRC,MAAM;gBACR;aACD;QACH;IACF;AACF,GAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAC5E,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,SAAS,CAAA;AAGvD,OAAO,KAAK,EACV,aAAa,EAMb,wBAAwB,EAEzB,MAAM,aAAa,CAAA;AAKpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,uCAI5B;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,
|
|
1
|
+
{"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAC5E,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,SAAS,CAAA;AAGvD,OAAO,KAAK,EACV,aAAa,EAMb,wBAAwB,EAEzB,MAAM,aAAa,CAAA;AAKpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,uCAI5B;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,SAyLH,CAAA"}
|
|
@@ -94,6 +94,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
|
|
|
94
94
|
input: item.tool.input
|
|
95
95
|
});
|
|
96
96
|
server.registerTool(item.mcpName, {
|
|
97
|
+
annotations: item.tool.annotations,
|
|
97
98
|
description: item.tool.description,
|
|
98
99
|
inputSchema: toStandardSchema(inputSchema)
|
|
99
100
|
}, async (input, ctx)=>callEntityTool({
|
|
@@ -147,6 +148,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
|
|
|
147
148
|
{
|
|
148
149
|
const tool = item.tool;
|
|
149
150
|
server.registerTool(item.mcpName, {
|
|
151
|
+
annotations: tool.annotations,
|
|
150
152
|
description: tool.description,
|
|
151
153
|
inputSchema: tool.input ? toStandardSchema(tool.input) : undefined
|
|
152
154
|
}, async (input, ctx)=>finalizeToolResponse(await tool.handler({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, type PayloadRequest } from 'payload'\nimport { z } from 'zod'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/**\n * Transport-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The caller is responsible for picking a transport\n * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and\n * calling `server.connect(transport)`.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = (\n response: MCPToolResponse,\n overrideResponse?: MCPResponseOverride,\n ): MCPToolResponse => {\n const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `collectionSlug` / `globalSlug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput[slugKey] as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = { authorizedMCP, input: toolInput, req, serverContext }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })\n : match.tool.handler({ ...handlerArgs, globalSlug: slug }))\n\n return finalizeToolResponse(response, match.tool.overrideResponse)\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({\n name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',\n input: item.tool.input,\n })\n\n server.registerTool(\n item.mcpName,\n {\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({\n name,\n input,\n}: {\n input?: ToolInputSchema\n name: 'collectionSlug' | 'globalSlug'\n}): ToolInputSchema => {\n const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'\n const slugSchema = z.string().describe(description)\n\n if (!input) {\n return z.object({ [name]: slugSchema })\n }\n\n if (input instanceof z.ZodObject) {\n return input.extend({ [name]: slugSchema })\n }\n\n const schema = input as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...schema,\n type: 'object',\n properties: {\n ...schema.properties,\n [name]: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set([name, ...(schema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","z","getLogger","toStandardSchema","buildMcpServer","authorizedMCP","pluginConfig","req","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","response","overrideResponse","overridden","doc","_doc","rest","callEntityTool","input","item","serverContext","entity","type","slugKey","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","describe","object","ZodObject","extend","schema","properties","required","Array","from"],"mapp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AAU;YACpB,CAAClE,KAAK,EAAE;gBACNkB,MAAM;gBACNwB;YACF;QACF;QACAyB,UAAUC,MAAMC,IAAI,CAAC,IAAIjC,IAAI;YAACpC;eAAUiE,OAAOE,QAAQ,IAAI,EAAE;SAAE;IACjE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, type PayloadRequest } from 'payload'\nimport { z } from 'zod'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/**\n * Transport-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The caller is responsible for picking a transport\n * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and\n * calling `server.connect(transport)`.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = (\n response: MCPToolResponse,\n overrideResponse?: MCPResponseOverride,\n ): MCPToolResponse => {\n const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `collectionSlug` / `globalSlug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const slugKey = item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput[slugKey] as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires ${slugKey}. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = { authorizedMCP, input: toolInput, req, serverContext }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, collectionSlug: slug })\n : match.tool.handler({ ...handlerArgs, globalSlug: slug }))\n\n return finalizeToolResponse(response, match.tool.overrideResponse)\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({\n name: item.type === 'collectionTool' ? 'collectionSlug' : 'globalSlug',\n input: item.tool.input,\n })\n\n server.registerTool(\n item.mcpName,\n {\n annotations: item.tool.annotations,\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({\n name,\n input,\n}: {\n input?: ToolInputSchema\n name: 'collectionSlug' | 'globalSlug'\n}): ToolInputSchema => {\n const description = name === 'collectionSlug' ? 'The collection slug' : 'The global slug'\n const slugSchema = z.string().describe(description)\n\n if (!input) {\n return z.object({ [name]: slugSchema })\n }\n\n if (input instanceof z.ZodObject) {\n return input.extend({ [name]: slugSchema })\n }\n\n const schema = input as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...schema,\n type: 'object',\n properties: {\n ...schema.properties,\n [name]: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set([name, ...(schema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","z","getLogger","toStandardSchema","buildMcpServer","authorizedMCP","pluginConfig","req","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","response","overrideResponse","overridden","doc","_doc","rest","callEntityTool","input","item","serverContext","entity","type","slugKey","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","annotations","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","describe","object","ZodObject","extend","schema","properties","required","Array","from"],"mappings":"AAAA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,QAA6B,UAAS;AACvD,SAASC,CAAC,QAAQ,MAAK;AAavB,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACC,MAAMC,gBAAgBF,aAAaG,GAAG,EAAED,iBAAiB,CAAC;IAC1D,MAAME,SAAS,IAAIX,UACjB;QAAEY,MAAM;QAAsBC,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K,GAAGtB,iBAAiByC,KAAKnB,KAAK,IAAImC;wBAC3D,GACA,OAAOnC,OAAgB8B,MACrBtC,qBACE,MAAM2B,KAAKC,OAAO,CAAC;gCACjBxC;gCACAoB,OAAQA,SAAS,CAAC;gCAClBlB;gCACAoB,eAAe4B;4BACjB,IACAX,KAAKzB,gBAAgB;wBAG3BJ,OAAOyC,IAAI,CAAC,CAAC,QAAQ,EAAE9B,KAAKS,OAAO,CAAC,YAAY,CAAC;wBACjD;oBACF;YACF;QACF;IACF,EAAE,OAAOkC,OAAO;QACd,MAAM,IAAIrE,SAAS,CAAC,gCAAgC,EAAEsE,OAAOD,QAAQ,EAAE;IACzE;IAEA,OAAO3D;AACT,EAAC;AAED,MAAMyC,gBAAgB,CAAC,EACrBxC,IAAI,EACJc,KAAK,EAIN;IACC,MAAM6B,cAAc3C,SAAS,mBAAmB,wBAAwB;IACxE,MAAM4D,aAAatE,EAAEuE,MAAM,GAAGC,QAAQ,CAACnB;IAEvC,IAAI,CAAC7B,OAAO;QACV,OAAOxB,EAAEyE,MAAM,CAAC;YAAE,CAAC/D,KAAK,EAAE4D;QAAW;IACvC;IAEA,IAAI9C,iBAAiBxB,EAAE0E,SAAS,EAAE;QAChC,OAAOlD,MAAMmD,MAAM,CAAC;YAAE,CAACjE,KAAK,EAAE4D;QAAW;IAC3C;IAEA,MAAMM,SAASpD;IAKf,OAAO;QACL,GAAGoD,MAAM;QACThD,MAAM;QACNiD,YAAY;YACV,GAAGD,OAAOC,UAAU;YACpB,CAACnE,KAAK,EAAE;gBACNkB,MAAM;gBACNyB;YACF;QACF;QACAyB,UAAUC,MAAMC,IAAI,CAAC,IAAIlC,IAAI;YAACpC;eAAUkE,OAAOE,QAAQ,IAAI,EAAE;SAAE;IACjE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authTools.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"names":[],"mappings":"AAiCA,eAAO,MAAM,kBAAkB,
|
|
1
|
+
{"version":3,"file":"authTools.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"names":[],"mappings":"AAiCA,eAAO,MAAM,kBAAkB,4CAqC7B,CAAA;AAEF,eAAO,MAAM,4BAA4B,4CAuCvC,CAAA;AAEF,eAAO,MAAM,mBAAmB,4CAiD9B,CAAA;AAEF,eAAO,MAAM,2BAA2B,4CAmCtC,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAgC/B,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAiC/B,CAAA"}
|
|
@@ -22,9 +22,16 @@ const wrapError = (name)=>({ collectionSlug, message })=>{
|
|
|
22
22
|
};
|
|
23
23
|
};
|
|
24
24
|
export const authCollectionTool = defineCollectionTool({
|
|
25
|
+
annotations: {
|
|
26
|
+
destructiveHint: false,
|
|
27
|
+
idempotentHint: true,
|
|
28
|
+
openWorldHint: false,
|
|
29
|
+
readOnlyHint: true,
|
|
30
|
+
title: 'Check Auth Status'
|
|
31
|
+
},
|
|
25
32
|
description: 'Checks authentication status for the current user.',
|
|
26
33
|
input: z.object({
|
|
27
|
-
headers: z.string().describe('Optional
|
|
34
|
+
headers: z.record(z.string(), z.string()).describe('Optional custom headers to send with the authentication request').optional()
|
|
28
35
|
})
|
|
29
36
|
}).handler(async ({ collectionSlug, input, req })=>{
|
|
30
37
|
const logger = getLogger({
|
|
@@ -33,11 +40,7 @@ export const authCollectionTool = defineCollectionTool({
|
|
|
33
40
|
try {
|
|
34
41
|
let authHeaders = new Headers();
|
|
35
42
|
if (input.headers) {
|
|
36
|
-
|
|
37
|
-
authHeaders = new Headers(JSON.parse(input.headers));
|
|
38
|
-
} catch {
|
|
39
|
-
logger.warn(`Invalid headers JSON for auth: ${input.headers}, using empty headers`);
|
|
40
|
-
}
|
|
43
|
+
authHeaders = new Headers(input.headers);
|
|
41
44
|
}
|
|
42
45
|
const result = await req.payload.auth({
|
|
43
46
|
headers: authHeaders
|
|
@@ -61,6 +64,13 @@ export const authCollectionTool = defineCollectionTool({
|
|
|
61
64
|
}
|
|
62
65
|
});
|
|
63
66
|
export const forgotPasswordCollectionTool = defineCollectionTool({
|
|
67
|
+
annotations: {
|
|
68
|
+
destructiveHint: false,
|
|
69
|
+
idempotentHint: false,
|
|
70
|
+
openWorldHint: true,
|
|
71
|
+
readOnlyHint: false,
|
|
72
|
+
title: 'Forgot Password'
|
|
73
|
+
},
|
|
64
74
|
description: 'Sends a password reset email to a user.',
|
|
65
75
|
input: z.object({
|
|
66
76
|
disableEmail: z.boolean().describe('Whether to disable sending the email (for testing)').optional().default(false),
|
|
@@ -99,6 +109,13 @@ export const forgotPasswordCollectionTool = defineCollectionTool({
|
|
|
99
109
|
}
|
|
100
110
|
});
|
|
101
111
|
export const loginCollectionTool = defineCollectionTool({
|
|
112
|
+
annotations: {
|
|
113
|
+
destructiveHint: false,
|
|
114
|
+
idempotentHint: false,
|
|
115
|
+
openWorldHint: false,
|
|
116
|
+
readOnlyHint: false,
|
|
117
|
+
title: 'User Login'
|
|
118
|
+
},
|
|
102
119
|
description: 'Authenticates a user with email and password.',
|
|
103
120
|
input: z.object({
|
|
104
121
|
depth: z.number().int().min(0).max(10).describe('Depth of population for relationships').optional().default(0),
|
|
@@ -139,6 +156,13 @@ export const loginCollectionTool = defineCollectionTool({
|
|
|
139
156
|
}
|
|
140
157
|
});
|
|
141
158
|
export const resetPasswordCollectionTool = defineCollectionTool({
|
|
159
|
+
annotations: {
|
|
160
|
+
destructiveHint: false,
|
|
161
|
+
idempotentHint: false,
|
|
162
|
+
openWorldHint: false,
|
|
163
|
+
readOnlyHint: false,
|
|
164
|
+
title: 'Reset Password'
|
|
165
|
+
},
|
|
142
166
|
description: 'Resets a user password with a reset token.',
|
|
143
167
|
input: z.object({
|
|
144
168
|
password: z.string().describe('The new password for the user'),
|
|
@@ -176,6 +200,13 @@ export const resetPasswordCollectionTool = defineCollectionTool({
|
|
|
176
200
|
}
|
|
177
201
|
});
|
|
178
202
|
export const unlockCollectionTool = defineCollectionTool({
|
|
203
|
+
annotations: {
|
|
204
|
+
destructiveHint: false,
|
|
205
|
+
idempotentHint: true,
|
|
206
|
+
openWorldHint: false,
|
|
207
|
+
readOnlyHint: false,
|
|
208
|
+
title: 'Unlock Account'
|
|
209
|
+
},
|
|
179
210
|
description: 'Unlocks a user account that has been locked due to failed login attempts.',
|
|
180
211
|
input: z.object({
|
|
181
212
|
email: emailSchema
|
|
@@ -213,6 +244,13 @@ export const unlockCollectionTool = defineCollectionTool({
|
|
|
213
244
|
}
|
|
214
245
|
});
|
|
215
246
|
export const verifyCollectionTool = defineCollectionTool({
|
|
247
|
+
annotations: {
|
|
248
|
+
destructiveHint: false,
|
|
249
|
+
idempotentHint: false,
|
|
250
|
+
openWorldHint: false,
|
|
251
|
+
readOnlyHint: false,
|
|
252
|
+
title: 'Email Verification'
|
|
253
|
+
},
|
|
216
254
|
description: 'Verifies a user email with a verification token.',
|
|
217
255
|
input: z.object({
|
|
218
256
|
token: z.string().describe('The verification token sent to the user email')
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.string().email().describe('The user email address')\n\nconst wrapError =\n (name: string) =>\n ({ collectionSlug, message }: { collectionSlug: string; message: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n description: 'Checks authentication status for the current user.',\n input: z.object({\n headers: z\n .string()\n .describe(\n 'Optional JSON string containing custom headers to send with the authentication request',\n )\n .optional(),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n try {\n authHeaders = new Headers(JSON.parse(input.headers) as Record<string, string>)\n } catch {\n logger.warn(`Invalid headers JSON for auth: ${input.headers}, using empty headers`)\n }\n }\n const result = await req.payload.auth({ headers: authHeaders })\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in auth tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('auth')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n description: 'Sends a password reset email to a user.',\n input: z.object({\n disableEmail: z\n .boolean()\n .describe('Whether to disable sending the email (for testing)')\n .optional()\n .default(false),\n email: emailSchema,\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.forgotPassword({\n collection: collectionSlug,\n data: { email: input.email },\n disableEmail: input.disableEmail,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Forgot Password Email Sent\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in forgotPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n description: 'Authenticates a user with email and password.',\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('Depth of population for relationships')\n .optional()\n .default(0),\n email: emailSchema,\n password: z.string().describe('The user password'),\n showHiddenFields: z\n .boolean()\n .describe('Whether to show hidden fields in the response')\n .optional()\n .default(false),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: collectionSlug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n showHiddenFields: input.showHiddenFields,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in login tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('login')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n description: 'Resets a user password with a reset token.',\n input: z.object({\n password: z.string().describe('The new password for the user'),\n token: z.string().describe('The password reset token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: collectionSlug,\n data: { password: input.password, token: input.token },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in resetPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('resetPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: z.object({ email: emailSchema }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: collectionSlug,\n data: { email: input.email },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in unlock tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('unlock')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n description: 'Verifies a user email with a verification token.',\n input: z.object({\n token: z.string().describe('The verification token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: collectionSlug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${collectionSlug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in verify tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('verify')({ collectionSlug, message: errorMessage })\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","emailSchema","string","email","describe","wrapError","name","collectionSlug","message","content","type","text","authCollectionTool","description","input","object","headers","optional","handler","req","logger","payload","authHeaders","Headers","JSON","parse","warn","result","auth","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","disableEmail","boolean","default","forgotPassword","collection","data","loginCollectionTool","depth","number","int","min","max","password","showHiddenFields","login","resetPasswordCollectionTool","token","resetPassword","overrideAccess","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1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.string().email().describe('The user email address')\n\nconst wrapError =\n (name: string) =>\n ({ collectionSlug, message }: { collectionSlug: string; message: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${collectionSlug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Check Auth Status',\n },\n description: 'Checks authentication status for the current user.',\n input: z.object({\n headers: z\n .record(z.string(), z.string())\n .describe('Optional custom headers to send with the authentication request')\n .optional(),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n authHeaders = new Headers(input.headers)\n }\n const result = await req.payload.auth({ headers: authHeaders })\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in auth tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('auth')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Forgot Password',\n },\n description: 'Sends a password reset email to a user.',\n input: z.object({\n disableEmail: z\n .boolean()\n .describe('Whether to disable sending the email (for testing)')\n .optional()\n .default(false),\n email: emailSchema,\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.forgotPassword({\n collection: collectionSlug,\n data: { email: input.email },\n disableEmail: input.disableEmail,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Forgot Password Email Sent\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in forgotPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'User Login',\n },\n description: 'Authenticates a user with email and password.',\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('Depth of population for relationships')\n .optional()\n .default(0),\n email: emailSchema,\n password: z.string().describe('The user password'),\n showHiddenFields: z\n .boolean()\n .describe('Whether to show hidden fields in the response')\n .optional()\n .default(false),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: collectionSlug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n showHiddenFields: input.showHiddenFields,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in login tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('login')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Reset Password',\n },\n description: 'Resets a user password with a reset token.',\n input: z.object({\n password: z.string().describe('The new password for the user'),\n token: z.string().describe('The password reset token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: collectionSlug,\n data: { password: input.password, token: input.token },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${collectionSlug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in resetPassword tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('resetPassword')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Unlock Account',\n },\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: z.object({ email: emailSchema }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: collectionSlug,\n data: { email: input.email },\n overrideAccess: true,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${collectionSlug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in unlock tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('unlock')({ collectionSlug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Email Verification',\n },\n description: 'Verifies a user email with a verification token.',\n input: z.object({\n token: z.string().describe('The verification token sent to the user email'),\n }),\n}).handler(async ({ collectionSlug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: collectionSlug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${collectionSlug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in verify tool on ${collectionSlug}: ${errorMessage}`)\n return wrapError('verify')({ collectionSlug, message: errorMessage })\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","emailSchema","string","email","describe","wrapError","name","collectionSlug","message","content","type","text","authCollectionTool","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","headers","record","optional","handler","req","logger","payload","authHeaders","Headers","result","auth","JSON","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","disableEmail","boolean","default","forgotPassword","collection","data","loginCollectionTool","depth","number","int","min","max","password","showHiddenFields","login","resetPasswordCollectionTool","token","resetPassword","overrideAccess","unlockCollectionTool","unlock","verifyCollectionTool","verifyEmail"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD;;;;;;;;;CASC,GAED,MAAMC,cAAcH,EAAEI,MAAM,GAAGC,KAAK,GAAGC,QAAQ,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OK,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAM5B,OAAO,GAAG;QAC9DmB,OAAOS,KAAK,CAAC,CAAC,wBAAwB,EAAE7B,eAAe,EAAE,EAAE8B,cAAc;QACzE,OAAOhC,UAAU,UAAU;YAAEE;YAAgBC,SAAS6B;QAAa;IACrE;AACF,GAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,kBAAkB,
|
|
1
|
+
{"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,kBAAkB,4CA0F7B,CAAA"}
|
|
@@ -8,6 +8,13 @@ import { validateCollectionData } from '../validateEntityData.js';
|
|
|
8
8
|
import { formatCollectionError } from './formatCollectionError.js';
|
|
9
9
|
const DEFAULT_DESCRIPTION = 'Create a document in any collection by passing the collection slug and data.';
|
|
10
10
|
export const createDocumentTool = defineCollectionTool({
|
|
11
|
+
annotations: {
|
|
12
|
+
destructiveHint: false,
|
|
13
|
+
idempotentHint: false,
|
|
14
|
+
openWorldHint: false,
|
|
15
|
+
readOnlyHint: false,
|
|
16
|
+
title: 'Create Document'
|
|
17
|
+
},
|
|
11
18
|
description: DEFAULT_DESCRIPTION,
|
|
12
19
|
input: z.object({
|
|
13
20
|
data: z.record(z.string(), z.unknown()).describe('The document fields to create'),
|
|
@@ -15,7 +22,7 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
15
22
|
draft: z.boolean().describe('Whether to create the document as a draft').optional().default(false),
|
|
16
23
|
fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
|
|
17
24
|
locale: z.string().describe('Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
|
|
18
|
-
select: z.string().describe(
|
|
25
|
+
select: z.record(z.string(), z.unknown()).describe('Optional: define exactly which fields you\'d like to return, e.g., {"title": true}').optional()
|
|
19
26
|
})
|
|
20
27
|
}).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
|
|
21
28
|
const payload = req.payload;
|
|
@@ -36,22 +43,6 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
36
43
|
return validationError;
|
|
37
44
|
}
|
|
38
45
|
const parsedData = transformPointDataToPayload(inputData);
|
|
39
|
-
let selectClause;
|
|
40
|
-
if (select) {
|
|
41
|
-
try {
|
|
42
|
-
selectClause = JSON.parse(select);
|
|
43
|
-
} catch {
|
|
44
|
-
logger.warn(`Invalid select clause JSON: ${select}`);
|
|
45
|
-
return {
|
|
46
|
-
content: [
|
|
47
|
-
{
|
|
48
|
-
type: 'text',
|
|
49
|
-
text: 'Error: Invalid JSON in select clause'
|
|
50
|
-
}
|
|
51
|
-
]
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
46
|
const result = await payload.create({
|
|
56
47
|
collection: collectionSlug,
|
|
57
48
|
data: parsedData,
|
|
@@ -65,8 +56,8 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
65
56
|
...fallbackLocale ? {
|
|
66
57
|
fallbackLocale
|
|
67
58
|
} : {},
|
|
68
|
-
...
|
|
69
|
-
select:
|
|
59
|
+
...select ? {
|
|
60
|
+
select: select
|
|
70
61
|
} : {}
|
|
71
62
|
});
|
|
72
63
|
logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`);
|