๐Ÿ“ฆ payloadcms / payload

๐Ÿ“„ config.ts ยท 347 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'
import { type MCPAccessSettings, mcpPlugin } from '@payloadcms/plugin-mcp'
import path from 'path'
import { fileURLToPath } from 'url'
import { z } from 'zod'

import { buildConfigWithDefaults } from '../buildConfigWithDefaults.js'
import { Media } from './collections/Media.js'
import { ModifiedPrompts } from './collections/ModifiedPrompts.js'
import { Posts } from './collections/Posts.js'
import { Products } from './collections/Products.js'
import { ReturnedResources } from './collections/ReturnedResources.js'
import { Rolls } from './collections/Rolls.js'
import { Users } from './collections/Users.js'
import { SiteSettings } from './globals/SiteSettings.js'
import { seed } from './seed/index.js'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

export default buildConfigWithDefaults({
  admin: {
    importMap: {
      baseDir: path.resolve(dirname),
    },
  },
  collections: [Users, Media, Posts, Products, Rolls, ModifiedPrompts, ReturnedResources],
  localization: {
    defaultLocale: 'en',
    fallback: true,
    locales: [
      {
        code: 'en',
        label: 'English',
      },
      {
        code: 'es',
        label: 'Spanish',
      },
      {
        code: 'fr',
        label: 'French',
      },
    ],
  },
  globals: [SiteSettings],
  onInit: seed,
  plugins: [
    mcpPlugin({
      /**
       * Override the authentication method.
       * This allows you to use a custom authentication method instead of the default API key authentication.
       * @param req - The request object.
       * @returns The MCP access settings.
       */
      // overrideAuth: (req) => {
      //   const { payload } = req

      //   payload.logger.info('[Override MCP auth]:')

      //   return {
      //     posts: {
      //       find: true,
      //     },
      //     products: {
      //       find: true,
      //       update: true,
      //     },
      //     'payload-mcp-tool': {
      //       diceRoll: true,
      //     },
      //     'payload-mcp-prompt': {
      //       echo: true,
      //     },
      //     'payload-mcp-resource': {
      //       data: true,
      //       dataByID: true,
      //     },
      //   } as MCPAccessSettings
      // },
      overrideApiKeyCollection: (collection) => {
        collection.fields.push({
          name: 'override',
          type: 'text',
          admin: {
            description: 'This field added by overrideApiKeyCollection',
          },
          defaultValue: 'This field added by overrideApiKeyCollection',
        })
        return collection
      },
      collections: {
        [Products.slug]: {
          enabled: true,
        },
        posts: {
          enabled: {
            find: true,
            create: true,
            update: true,
            delete: true,
          },
          description: 'This is a Payload collection with Post documents.',
          overrideResponse: (response, doc, req) => {
            req.payload.logger.info('[Override MCP response for Posts]:')
            response.content.push({
              type: 'text',
              text: `Override MCP response for Posts!`,
            })
            return response
          },
        },
        media: {
          enabled: {
            find: true,
            create: false,
            update: true,
            delete: false,
          },
          description: 'This is a Payload collection with Media documents.',
        },
      },
      globals: {
        'site-settings': {
          enabled: {
            find: true,
            update: true,
          },
          description: 'Site-wide configuration settings.',
        },
      },
      mcp: {
        handlerOptions: {
          verboseLogs: true,
          maxDuration: 60,
        },
        serverOptions: {
          serverInfo: {
            name: 'My Custom MCP Server',
            version: '1.0.0',
          },
        },
        tools: [
          {
            name: 'diceRoll',
            description: 'Rolls a virtual dice with a specified number of sides',
            handler: async (args: Record<string, unknown>, req) => {
              const sides = (args.sides as number) || 6
              const result = Math.floor(Math.random() * sides) + 1
              const payload = req.payload

              payload.logger.info(
                `Dice Roll MCP Tool rolled a ${args.sides} sided die and got a ${result}`,
              )

              await payload.create({
                collection: 'rolls',
                data: {
                  sides,
                  result,
                  user: req.user?.id,
                },
                req,
                overrideAccess: false,
                user: req.user,
                draft: true,
              })

              return Promise.resolve({
                content: [
                  {
                    type: 'text' as const,
                    text: `# Dice Roll Result\n\n**Sides:** ${sides}\n**Result:** ${result}\n\n๐ŸŽฒ You rolled a **${result}** on a ${sides}-sided die!`,
                  },
                ],
              })
            },
            parameters: z.object({
              sides: z
                .number()
                .int()
                .min(2)
                .max(1000)
                .optional()
                .default(6)
                .describe('Number of sides on the dice (default: 6)'),
            }).shape,
          },
        ],
        prompts: [
          {
            name: 'echo',
            argsSchema: { message: z.string() },
            description: 'Creates a prompt to process a message',
            title: 'Echo Prompt',
            handler: async ({ message }, req) => {
              const { payload } = req

              payload.logger.info(`Echo Prompt was sent: ${message}`)

              const modifiedPrompt = `This prompt was sent: ${message}`

              await payload.create({
                collection: 'modified-prompts',
                data: {
                  original: message as string,
                  modified: modifiedPrompt,
                  user: req.user?.id,
                },
                req,
                overrideAccess: false,
                user: req.user,
                draft: true,
              })

              return {
                messages: [
                  {
                    content: {
                      type: 'text',
                      text: modifiedPrompt,
                    },
                    role: 'user',
                  },
                  {
                    content: {
                      type: 'text',
                      text: `This prompt was sent by userId: ${req.user?.id}`,
                    },
                    role: 'assistant',
                  },
                ],
              }
            },
          },
        ],
        resources: [
          // Resource with a static URI
          {
            name: 'data',
            description: 'Data is a resource that contains special data.',
            handler: async (uri, req) => {
              const payload = req.payload

              payload.logger.info(`Data resource was requested`)

              const text = 'My special data.'
              await payload.create({
                collection: 'returned-resources',
                data: {
                  uri: uri.href,
                  content: text,
                  user: req.user?.id,
                },
                req,
                overrideAccess: false,
                user: req.user,
                draft: true,
              })

              return {
                contents: [
                  {
                    uri: uri.href,
                    text,
                  },
                  {
                    uri: uri.href,
                    text: `This was requested by user: ${req.user?.id}`,
                  },
                ],
              }
            },
            mimeType: 'text/plain',
            title: 'Data',
            uri: 'data://app',
          },
          // Resource with a template
          {
            name: 'dataByID',
            description: 'Data is a resource that contains special data.',
            handler: async (uri, { id }, req) => {
              const payload = req.payload

              payload.logger.info(`Data by ID resource was requested`)

              const text = `My special data for ID: ${id}`
              await payload.create({
                collection: 'returned-resources',
                data: {
                  uri: uri.href,
                  content: text,
                  user: req.user?.id,
                },
                req,
                overrideAccess: false,
                user: req.user,
                draft: true,
              })

              return {
                contents: [
                  {
                    uri: uri.href,
                    text,
                  },
                  {
                    uri: uri.href,
                    text: `This was requested by user: ${req.user?.id}`,
                  },
                ],
              }
            },
            mimeType: 'text/plain',
            title: 'Data By ID',
            uri: new ResourceTemplate('data://app/{id}', { list: undefined }),
          },
        ],
      },

      // Experimental MCP tools
      experimental: {
        tools: {
          collections: {
            collectionsDirPath: 'test/plugin-mcp/collections',
            enabled: true,
          },
          config: {
            configFilePath: path.resolve(dirname, 'test/plugin-mcp/config.ts'),
            enabled: true,
          },
          jobs: {
            enabled: true,
            jobsDirPath: 'dev/jobs',
          },
          auth: {
            enabled: true,
          },
        },
      },
    }),
  ],
  typescript: {
    outputFile: path.resolve(dirname, 'payload-types.ts'),
  },
})