-
-
Notifications
You must be signed in to change notification settings - Fork 21.6k
Expand file tree
/
Copy pathmcp.ts
More file actions
1636 lines (1495 loc) · 56.3 KB
/
Copy pathmcp.ts
File metadata and controls
1636 lines (1495 loc) · 56.3 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { NextApiRequest, NextApiResponse } from "next";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import {
ElicitResultSchema,
ListPromptsRequestSchema,
GetPromptRequestSchema,
type PrimitiveSchemaDefinition,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { db } from "@/lib/db";
import { isValidApiKeyFormat } from "@/lib/api-key";
import { parseSkillFiles, serializeSkillFiles, sanitizeFilename, DEFAULT_SKILL_FILE } from "@/lib/skill-files";
import appConfig from "@/../prompts.config";
import {
mcpGeneralLimiter,
mcpToolCallLimiter,
mcpWriteToolLimiter,
mcpAiToolLimiter,
} from "@/lib/rate-limit";
interface AuthenticatedUser {
id: string;
username: string;
mcpPromptsPublicByDefault: boolean;
}
// In-memory auth cache for warm function instances (5-min TTL)
const authCache = new Map<string, { user: AuthenticatedUser | null; expiry: number }>();
const AUTH_CACHE_TTL = 5 * 60 * 1000;
async function authenticateApiKey(apiKey: string | null): Promise<AuthenticatedUser | null> {
if (!apiKey || !isValidApiKeyFormat(apiKey)) {
return null;
}
const cached = authCache.get(apiKey);
if (cached && Date.now() < cached.expiry) {
return cached.user;
}
const user = await db.user.findUnique({
where: { apiKey },
select: {
id: true,
username: true,
mcpPromptsPublicByDefault: true,
},
});
authCache.set(apiKey, { user, expiry: Date.now() + AUTH_CACHE_TTL });
return user;
}
interface ExtractedVariable {
name: string;
defaultValue?: string;
}
function slugify(text: string): string {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, "")
.replace(/[\s_-]+/g, "-")
.replace(/^-+|-+$/g, "");
}
/**
* Get the prompt name/slug for MCP.
* Priority: slug > slugify(title) > id
*/
function getPromptName(prompt: { id: string; slug?: string | null; title: string }): string {
if (prompt.slug) return prompt.slug;
const titleSlug = slugify(prompt.title);
if (titleSlug) return titleSlug;
return prompt.id;
}
function extractVariables(content: string): ExtractedVariable[] {
// Format: ${variableName} or ${variableName:default}
const regex = /\$\{([a-zA-Z_][a-zA-Z0-9_\s]*?)(?::([^}]*))?\}/g;
const variables: ExtractedVariable[] = [];
const seen = new Set<string>();
let match;
while ((match = regex.exec(content)) !== null) {
const name = match[1].trim();
if (!seen.has(name)) {
seen.add(name);
variables.push({
name,
defaultValue: match[2]?.trim(),
});
}
}
return variables;
}
interface CategoryRow {
id: string;
name: string;
slug: string;
}
/**
* Match a user-supplied category string against known categories.
* Tries, in order: exact slug (case-insensitive), exact name (case-insensitive),
* then slugified-name / slug equality (so "Code Review" and "code_review" both map
* to the "code-review" category). Returns null when nothing matches.
*/
export function findCategoryMatch(categories: CategoryRow[], input: string): CategoryRow | null {
const needle = input.trim().toLowerCase();
if (!needle) return null;
const bySlug = categories.find((c) => c.slug.toLowerCase() === needle);
if (bySlug) return bySlug;
const byName = categories.find((c) => c.name.toLowerCase() === needle);
if (byName) return byName;
const inputSlug = slugify(input);
const bySlugified = categories.find((c) => c.slug === inputSlug || slugify(c.name) === inputSlug);
if (bySlugified) return bySlugified;
return null;
}
/**
* Visibility filter for fetching a single prompt/skill by id: public entries, plus the
* authenticated owner's own private ones. Unauthenticated callers see only public entries.
* Returns a Prisma `where` fragment to spread into the query. Keep get_prompt and get_skill
* in sync — get_prompt previously hard-filtered `isPrivate: false`, hiding owners' own private
* prompts from themselves.
*/
export function buildPromptVisibilityFilter(
authenticatedUser: Pick<AuthenticatedUser, "id"> | null | undefined
) {
return authenticatedUser
? {
OR: [
{ isPrivate: false },
{ isPrivate: true, authorId: authenticatedUser.id },
],
}
: { isPrivate: false };
}
/**
* Resolve a category string (slug or name) to a category id. Returns a human-readable
* warning (instead of silently dropping the value) when nothing matches, so callers can
* surface it rather than creating a prompt with no category and no feedback.
*/
async function resolveCategory(
category: string | undefined
): Promise<{ categoryId: string | null; warning?: string }> {
if (!category) return { categoryId: null };
const categories = await db.category.findMany({ select: { id: true, name: true, slug: true } });
const match = findCategoryMatch(categories, category);
if (match) return { categoryId: match.id };
const available = categories.map((c) => c.slug).sort().join(", ");
return {
categoryId: null,
warning: `Category "${category}" did not match any category and was not assigned. Call list_categories, or pass one of these slugs: ${available || "(none)"}.`,
};
}
export const config = {
api: {
bodyParser: false,
},
};
interface ServerOptions {
categories?: string[];
tags?: string[];
users?: string[];
authenticatedUser?: AuthenticatedUser | null;
}
function createServer(options: ServerOptions = {}) {
const server = new McpServer(
{
name: "prompts-chat",
version: "1.0.0",
},
{
capabilities: {
prompts: { listChanged: false },
tools: { listChanged: false },
},
}
);
const { authenticatedUser } = options;
// Build category/tag filter for prompts
// If authenticated user is present and no specific users filter, include their private prompts
const buildPromptFilter = (includeOwnPrivate: boolean = true): Record<string, unknown> => {
const baseFilter: Record<string, unknown> = {
isUnlisted: false,
deletedAt: null,
};
// Handle visibility: public prompts OR authenticated user's own prompts
if (authenticatedUser && includeOwnPrivate) {
// If users filter includes the authenticated user (or no users filter), include their private prompts
const usersFilter = options.users && options.users.length > 0 ? options.users : null;
const includeAuthUserPrivate = !usersFilter || usersFilter.includes(authenticatedUser.username);
if (includeAuthUserPrivate) {
baseFilter.OR = [
{ isPrivate: false },
{ isPrivate: true, authorId: authenticatedUser.id },
];
} else {
baseFilter.isPrivate = false;
}
} else {
baseFilter.isPrivate = false;
}
if (options.categories && options.categories.length > 0) {
baseFilter.category = {
slug: { in: options.categories },
};
}
if (options.tags && options.tags.length > 0) {
baseFilter.tags = {
some: {
tag: { slug: { in: options.tags } },
},
};
}
if (options.users && options.users.length > 0) {
baseFilter.author = {
username: { in: options.users },
};
}
return baseFilter;
};
const promptFilter = buildPromptFilter();
// Dynamic MCP Prompts - expose database prompts as MCP prompts
server.server.setRequestHandler(ListPromptsRequestSchema, async (request) => {
const cursor = request.params?.cursor;
const page = cursor ? parseInt(cursor, 10) : 1;
const perPage = 20;
const prompts = await db.prompt.findMany({
where: promptFilter,
skip: (page - 1) * perPage,
take: perPage + 1, // fetch one extra to check if there's more
orderBy: { createdAt: "desc" },
select: {
id: true,
slug: true,
title: true,
description: true,
},
});
const hasMore = prompts.length > perPage;
const results = hasMore ? prompts.slice(0, perPage) : prompts;
return {
prompts: results.map((p) => {
return {
name: getPromptName(p),
title: p.title,
description: p.description || undefined,
};
}),
nextCursor: hasMore ? String(page + 1) : undefined,
};
});
server.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
const promptSlug = request.params.name;
const args = request.params.arguments || {};
const promptSelect = { id: true, slug: true, title: true, description: true, content: true };
// Try direct lookup by slug first
let prompt = await db.prompt.findFirst({
where: { ...promptFilter, slug: promptSlug },
select: promptSelect,
});
// Fallback: lookup by id
if (!prompt) {
prompt = await db.prompt.findFirst({
where: { ...promptFilter, id: promptSlug },
select: promptSelect,
});
}
// Fallback: lookup by title for prompts without stored slug
// Uses indexed DB query instead of loading 500 rows into memory
// TODO: Backfill slug column for all existing prompts so this fallback can be removed
if (!prompt) {
const titleGuess = promptSlug.replace(/-/g, " ");
prompt = await db.prompt.findFirst({
where: { ...promptFilter, slug: null, title: { contains: titleGuess, mode: "insensitive" } },
select: promptSelect,
});
}
if (!prompt) {
throw new Error(`Prompt not found: ${promptSlug}`);
}
// Replace variables in content
let filledContent = prompt.content;
const variables = extractVariables(prompt.content);
for (const variable of variables) {
const value = args[variable.name] ?? variable.defaultValue ?? `\${${variable.name}}`;
filledContent = filledContent.replace(
new RegExp(`\\$\\{${variable.name}(?::[^}]*)?\\}`, "g"),
String(value)
);
}
return {
description: prompt.description || prompt.title,
messages: [
{
role: "user" as const,
content: {
type: "text" as const,
text: filledContent,
},
},
],
};
});
server.registerTool(
"search_prompts",
{
title: "Search Prompts",
description:
"Search for AI prompts by keyword. Returns matching prompts with title, description, content, author, category, and tags. Use this to discover prompts for various AI tasks like coding, writing, analysis, and more.",
inputSchema: {
query: z.string().describe("Search query to find relevant prompts"),
limit: z
.number()
.min(1)
.max(50)
.default(10)
.describe("Maximum number of prompts to return (default 10, max 50)"),
type: z
.enum(["TEXT", "STRUCTURED", "IMAGE", "VIDEO", "AUDIO"])
.optional()
.describe("Filter by prompt type"),
category: z.string().optional().describe("Filter by category slug"),
tag: z.string().optional().describe("Filter by tag slug"),
},
},
async ({ query, limit = 10, type, category, tag }) => {
try {
const where: Record<string, unknown> = {
isUnlisted: false,
deletedAt: null,
AND: [
// Search filter
{
OR: [
{ title: { contains: query, mode: "insensitive" } },
{ description: { contains: query, mode: "insensitive" } },
{ content: { contains: query, mode: "insensitive" } },
],
},
// Visibility filter: public OR user's own private prompts
authenticatedUser
? {
OR: [
{ isPrivate: false },
{ isPrivate: true, authorId: authenticatedUser.id },
],
}
: { isPrivate: false },
],
};
if (type) where.type = type;
if (category) where.category = { slug: category };
if (tag) where.tags = { some: { tag: { slug: tag } } };
const prompts = await db.prompt.findMany({
where,
take: Math.min(limit, 50),
orderBy: { createdAt: "desc" },
select: {
id: true,
slug: true,
title: true,
description: true,
content: true,
type: true,
createdAt: true,
author: { select: { username: true, name: true } },
category: { select: { name: true, slug: true } },
tags: { select: { tag: { select: { name: true, slug: true } } } },
_count: { select: { votes: true } },
},
});
const results = prompts.map((p) => ({
id: p.id,
slug: getPromptName(p),
title: p.title,
description: p.description,
contentPreview: p.content.substring(0, 300) + (p.content.length > 300 ? '...' : ''),
type: p.type,
author: p.author.name || p.author.username,
category: p.category?.name || null,
categorySlug: p.category?.slug || null,
tags: p.tags.map((t) => t.tag.name),
votes: p._count.votes,
createdAt: p.createdAt.toISOString(),
}));
return {
content: [
{
type: "text" as const,
text: JSON.stringify({ query, count: results.length, prompts: results }),
},
],
};
} catch (error) {
console.error("MCP search_prompts error:", error);
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Failed to search prompts" }) }],
isError: true,
};
}
}
);
server.registerTool(
"get_prompt",
{
title: "Get Prompt",
description:
"Get a prompt by ID and optionally fill in its variables. If the prompt contains template variables (like {{variable}}), you will be asked to provide values for them.",
inputSchema: {
id: z.string().describe("The ID of the prompt to retrieve"),
fill_variables: z.boolean().default(false).describe(
"If true and the prompt has template variables, triggers interactive variable filling. Default false — returns raw prompt with variable metadata."
),
},
},
async ({ id, fill_variables }, extra) => {
try {
const visibilityFilter = buildPromptVisibilityFilter(authenticatedUser);
const prompt = await db.prompt.findFirst({
where: {
id,
isUnlisted: false,
deletedAt: null,
...visibilityFilter,
},
select: {
id: true,
slug: true,
title: true,
description: true,
content: true,
type: true,
structuredFormat: true,
author: { select: { username: true, name: true } },
category: { select: { name: true, slug: true } },
tags: { select: { tag: { select: { name: true, slug: true } } } },
},
});
if (!prompt) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Prompt not found" }) }],
isError: true,
};
}
const variables = extractVariables(prompt.content);
if (fill_variables && variables.length > 0) {
const properties: Record<string, PrimitiveSchemaDefinition> = {};
const requiredFields: string[] = [];
for (const variable of variables) {
properties[variable.name] = {
type: "string",
title: variable.name,
description: `Value for \${${variable.name}}${variable.defaultValue ? ` (default: ${variable.defaultValue})` : ""}`,
default: variable.defaultValue,
};
// Only require fields without defaults
if (!variable.defaultValue) {
requiredFields.push(variable.name);
}
}
try {
// Add timeout to prevent hanging if client doesn't support elicitation
const timeoutMs = 10000; // 10 seconds
const elicitationPromise = extra.sendRequest(
{
method: "elicitation/create",
params: {
mode: "form",
message: `This prompt requires ${variables.length} variable(s). Please provide values:`,
requestedSchema: {
type: "object",
properties,
required: requiredFields.length > 0 ? requiredFields : undefined,
},
},
},
ElicitResultSchema
);
let timeoutId: NodeJS.Timeout;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error("Elicitation timeout")), timeoutMs);
});
try {
const elicitResult = await Promise.race([elicitationPromise, timeoutPromise]);
clearTimeout(timeoutId!);
if (elicitResult.action === "accept" && elicitResult.content) {
let filledContent = prompt.content;
for (const [key, value] of Object.entries(elicitResult.content)) {
// Skip keys that don't match valid variable name format (ReDoS prevention)
if (!/^[a-zA-Z_][a-zA-Z0-9_\s]*$/.test(key)) {
continue;
}
// Replace ${key} or ${key:default} patterns
filledContent = filledContent.replace(
new RegExp(`\\$\\{${key}(?::[^}]*)?\\}`, "g"),
String(value)
);
}
return {
content: [
{
type: "text" as const,
text: JSON.stringify({
...prompt,
content: filledContent,
originalContent: prompt.content,
variables: elicitResult.content,
author: prompt.author.name || prompt.author.username,
category: prompt.category?.name || null,
tags: prompt.tags.map((t) => t.tag.name),
link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`,
}),
},
],
};
} else {
return {
content: [
{
type: "text" as const,
text: JSON.stringify({
...prompt,
variablesRequired: variables,
message: "User declined to provide variable values. Returning original prompt.",
author: prompt.author.name || prompt.author.username,
category: prompt.category?.name || null,
tags: prompt.tags.map((t) => t.tag.name),
link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`,
}),
},
],
};
}
} catch (e) {
clearTimeout(timeoutId!);
throw e;
}
} catch {
return {
content: [
{
type: "text" as const,
text: JSON.stringify({
...prompt,
variablesRequired: variables,
message: "Elicitation not supported. Variables need to be filled manually.",
author: prompt.author.name || prompt.author.username,
category: prompt.category?.name || null,
tags: prompt.tags.map((t) => t.tag.name),
link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`,
}),
},
],
};
}
} else if (variables.length > 0) {
// Return prompt with variable metadata, no timeout
return {
content: [{ type: "text" as const, text: JSON.stringify({
id: prompt.id,
slug: getPromptName(prompt),
title: prompt.title,
description: prompt.description,
content: prompt.content,
type: prompt.type,
author: prompt.author.name || prompt.author.username,
category: prompt.category?.name || null,
tags: prompt.tags.map((t) => t.tag.name),
variables: variables.map(v => ({ name: v.name, defaultValue: v.defaultValue })),
hint: "This prompt has template variables. Call get_prompt with fill_variables=true to fill them interactively.",
}) }],
};
}
return {
content: [
{
type: "text" as const,
text: JSON.stringify({
...prompt,
author: prompt.author.name || prompt.author.username,
category: prompt.category?.name || null,
tags: prompt.tags.map((t) => t.tag.name),
link: `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`,
}),
},
],
};
} catch (error) {
console.error("MCP get_prompt error:", error);
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Failed to get prompt" }) }],
isError: true,
};
}
}
);
// Save prompt tool - requires authentication
server.registerTool(
"save_prompt",
{
title: "Save Prompt",
description:
"Save a new prompt to your prompts.chat account. Requires API key authentication. Prompts are private by default unless configured otherwise in settings.",
inputSchema: {
title: z.string().min(1).max(200).describe("Title of the prompt"),
content: z.string().min(1).describe("The prompt content. Can include variables like ${variable} or ${variable:default}"),
description: z.string().max(500).optional().describe("Optional description of the prompt"),
tags: z.array(z.string()).max(10).optional().describe("Optional array of tag names (will be created if they don't exist)"),
category: z.string().optional().describe("Optional category slug or name. Call list_categories for valid values; an unrecognized value is ignored (with a warning in the response) rather than failing the save."),
isPrivate: z.boolean().optional().describe("Whether the prompt is private (default: uses your account setting)"),
type: z.enum(["TEXT", "STRUCTURED", "IMAGE", "VIDEO", "AUDIO"]).optional().describe("Prompt type (default: TEXT)"),
structuredFormat: z.enum(["JSON", "YAML"]).optional().describe("Format for structured prompts"),
},
},
async ({ title, content, description, tags, category, isPrivate, type, structuredFormat }) => {
if (!authenticatedUser) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Authentication required. Please provide an API key." }) }],
isError: true,
};
}
try {
// Determine privacy setting
const shouldBePrivate = isPrivate !== undefined ? isPrivate : !authenticatedUser.mcpPromptsPublicByDefault;
// Find or create tags
const tagConnections: { tag: { connect: { id: string } } }[] = [];
if (tags && tags.length > 0) {
for (const tagName of tags) {
const tagSlug = slugify(tagName);
if (!tagSlug) continue;
let tag = await db.tag.findUnique({ where: { slug: tagSlug } });
if (!tag) {
tag = await db.tag.create({
data: {
name: tagName,
slug: tagSlug,
},
});
}
tagConnections.push({ tag: { connect: { id: tag.id } } });
}
}
// Resolve category (accepts slug or name; warns instead of silently dropping)
const { categoryId, warning: categoryWarning } = await resolveCategory(category);
// Create the prompt
const prompt = await db.prompt.create({
data: {
title,
slug: slugify(title),
content,
description: description || null,
isPrivate: shouldBePrivate,
type: type || "TEXT",
structuredFormat: type === "STRUCTURED" ? (structuredFormat || "JSON") : null,
authorId: authenticatedUser.id,
categoryId: categoryId || null,
tags: {
create: tagConnections,
},
},
select: {
id: true,
slug: true,
title: true,
description: true,
content: true,
isPrivate: true,
type: true,
createdAt: true,
tags: { select: { tag: { select: { name: true, slug: true } } } },
category: { select: { name: true, slug: true } },
},
});
return {
content: [
{
type: "text" as const,
text: JSON.stringify({
success: true,
...(categoryWarning ? { warning: categoryWarning } : {}),
prompt: {
...prompt,
tags: prompt.tags.map((t) => t.tag.name),
category: prompt.category?.name || null,
categorySlug: prompt.category?.slug || null,
link: prompt.isPrivate ? null : `https://prompts.chat/prompts/${prompt.id}_${getPromptName(prompt)}`,
},
}),
},
],
};
} catch (error) {
console.error("MCP save_prompt error:", error);
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Failed to save prompt" }) }],
isError: true,
};
}
}
);
// Improve prompt tool - uses AI to enhance prompts
server.registerTool(
"improve_prompt",
{
title: "Improve Prompt",
description:
"Transform a basic prompt into a well-structured, comprehensive prompt using AI. Optionally searches for similar prompts for inspiration. Supports different output types (text, image, video, sound) and formats (text, JSON, YAML).",
inputSchema: {
prompt: z.string().min(1).max(10000).describe("The prompt to improve"),
outputType: z
.enum(["text", "image", "video", "sound"])
.default("text")
.describe("Content type: text, image, video, or sound"),
outputFormat: z
.enum(["text", "structured_json", "structured_yaml"])
.default("text")
.describe("Response format: text, structured_json, or structured_yaml"),
},
},
async ({ prompt, outputType = "text", outputFormat = "text" }) => {
if (!authenticatedUser) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Authentication required. Please provide an API key." }) }],
isError: true,
};
}
try {
const { improvePrompt } = await import("@/lib/ai/improve-prompt");
const result = await improvePrompt({ prompt, outputType, outputFormat });
return {
content: [
{
type: "text" as const,
text: JSON.stringify(result),
},
],
};
} catch (error) {
console.error("MCP improve_prompt error:", error);
const message = error instanceof Error ? error.message : "Failed to improve prompt";
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: message }) }],
isError: true,
};
}
}
);
// Save skill tool - create a new skill with multiple files
server.registerTool(
"save_skill",
{
title: "Save Skill",
description:
"Save a new Agent Skill to your prompts.chat account. Skills are multi-file prompts that can include SKILL.md (required), reference docs, scripts, and configuration files. Requires API key authentication. If the file contents are too long, first save the SKILL.md only, with no other files. Then call add_file_to_skill tool per file.",
inputSchema: {
title: z.string().min(1).max(200).describe("Title of the skill"),
description: z.string().max(500).optional().describe("Description of what the skill does"),
files: z.array(z.object({
filename: z.string().describe("File path (e.g., 'SKILL.md', 'reference.md', 'scripts/helper.py')"),
content: z.string().describe("File content"),
})).min(1).describe("Array of files. Must include SKILL.md as the main skill file."),
tags: z.array(z.string()).max(10).optional().describe("Optional array of tag names"),
category: z.string().optional().describe("Optional category slug or name. Call list_categories for valid values; an unrecognized value is ignored (with a warning in the response) rather than failing the save."),
isPrivate: z.boolean().optional().describe("Whether the skill is private (default: uses your account setting)"),
},
},
async ({ title, description, files, tags, category, isPrivate }) => {
if (!authenticatedUser) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Authentication required. Please provide an API key." }) }],
isError: true,
};
}
try {
// Ensure SKILL.md exists
const hasSkillMd = files.some(f => f.filename === DEFAULT_SKILL_FILE);
if (!hasSkillMd) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "SKILL.md file is required" }) }],
isError: true,
};
}
// Validate all filenames to prevent path traversal
for (const f of files) {
if (f.filename !== DEFAULT_SKILL_FILE && !sanitizeFilename(f.filename)) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: `Invalid filename: '${f.filename}'. Filenames must not contain '..', start/end with '/', or use special characters.` }) }],
isError: true,
};
}
}
// Serialize files to multi-file format
const content = serializeSkillFiles(files.map(f => ({ filename: f.filename, content: f.content })));
// Determine privacy setting
const shouldBePrivate = isPrivate !== undefined ? isPrivate : !authenticatedUser.mcpPromptsPublicByDefault;
// Find or create tags
const tagConnections: { tag: { connect: { id: string } } }[] = [];
if (tags && tags.length > 0) {
for (const tagName of tags) {
const tagSlug = slugify(tagName);
if (!tagSlug) continue;
let tag = await db.tag.findUnique({ where: { slug: tagSlug } });
if (!tag) {
tag = await db.tag.create({
data: { name: tagName, slug: tagSlug },
});
}
tagConnections.push({ tag: { connect: { id: tag.id } } });
}
}
// Resolve category (accepts slug or name; warns instead of silently dropping)
const { categoryId, warning: categoryWarning } = await resolveCategory(category);
// Create the skill
const skill = await db.prompt.create({
data: {
title,
slug: slugify(title),
content,
description: description || null,
isPrivate: shouldBePrivate,
type: "SKILL",
authorId: authenticatedUser.id,
categoryId: categoryId || null,
tags: { create: tagConnections },
},
select: {
id: true,
slug: true,
title: true,
description: true,
isPrivate: true,
createdAt: true,
tags: { select: { tag: { select: { name: true, slug: true } } } },
category: { select: { name: true, slug: true } },
},
});
return {
content: [
{
type: "text" as const,
text: JSON.stringify({
success: true,
...(categoryWarning ? { warning: categoryWarning } : {}),
skill: {
...skill,
files: files.map(f => f.filename),
tags: skill.tags.map((t) => t.tag.name),
category: skill.category?.name || null,
categorySlug: skill.category?.slug || null,
link: skill.isPrivate ? null : `https://prompts.chat/prompts/${skill.id}_${getPromptName(skill)}`,
},
}),
},
],
};
} catch (error) {
console.error("MCP save_skill error:", error);
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Failed to save skill" }) }],
isError: true,
};
}
}
);
// Add file to skill tool
server.registerTool(
"add_file_to_skill",
{
title: "Add File to Skill",
description:
"Add a new file to an existing Agent Skill. Use this to add reference docs, scripts, or configuration files to a skill you own.",
inputSchema: {
skillId: z.string().describe("The ID of the skill to add the file to"),
filename: z.string().describe("File path (e.g., 'reference.md', 'scripts/helper.py', 'config/settings.json')"),
content: z.string().describe("File content"),
},
},
async ({ skillId, filename, content }) => {
if (!authenticatedUser) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Authentication required. Please provide an API key." }) }],
isError: true,
};
}
try {
// Fetch the skill
const skill = await db.prompt.findFirst({
where: {
id: skillId,
type: "SKILL",
authorId: authenticatedUser.id,
deletedAt: null,
},
select: { id: true, content: true, title: true, slug: true },
});
if (!skill) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "Skill not found or you don't have permission to edit it" }) }],
isError: true,
};
}
// Parse existing files
const files = parseSkillFiles(skill.content);
// Check if file already exists
if (files.some(f => f.filename === filename)) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: `File '${filename}' already exists. Use a different filename or update the existing file.` }) }],
isError: true,
};
}
// Cannot add SKILL.md (it always exists)
if (filename === DEFAULT_SKILL_FILE) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "SKILL.md already exists. Edit the skill directly to modify it." }) }],
isError: true,
};
}
// Validate filename to prevent path traversal
if (!sanitizeFilename(filename)) {
return {