Open History to see the last commit
1type PromptMessage = {
2 role: string
3 content: string
4}
5
6type PromptArgsSchema<TArgs> = {
7 parse: (input: unknown) => TArgs
8}
9
10/**
11 * Builds a resource definition for the MCP server.
12 *
13 * `config` takes `name`, `mimeType`, and `uri` or `uriTemplate`.
14 * If `uri` and `uriTemplate` are both missing, this function throws a TypeError.
15 * Call `.read` with a function that returns the resource contents.
16 *
17 * @param config - The resource `name`, `mimeType`, and `uri` or `uriTemplate`.
18 * @throws {TypeError} When `uri` and `uriTemplate` are both missing.
19 *
20 * @example
21 * ```ts
22 * const readme = resourceDefinition({
23 * uri: 'file:///readme.md',
24 * name: 'readme',
25 * mimeType: 'text/markdown',
26 * }).read(async () => ({ text: '# Hello' }))
27 * ```
28 */
29export function resourceDefinition<
30 const TConfig extends {
31 name: string
32 mimeType: string
33 uri?: string
34 uriTemplate?: string
35 },
36>(config: TConfig) {
37 const hasUri = config.uri !== undefined
38 const hasUriTemplate = config.uriTemplate !== undefined
39 if (!hasUri && !hasUriTemplate) {
40 throw new TypeError(
41 'This resource has no uri and no uriTemplate. Pass a uri or a uriTemplate.',
42 )
43 }
44
45 return {
46 ...config,
47 read<TContents>(readContents: () => TContents | Promise<TContents>) {
48 return {
49 ...config,
50 read: readContents,
51 }
52 },
53 }
54}
55
56/**
57 * Builds a prompt definition for the MCP server.
58 *
59 * `config` takes `name`, `description`, and `argsSchema`.
60 * `argsSchema.parse` runs before the render function receives the arguments.
61 * Call `.render` with a function that returns an array of messages.
62 * Each message has `role` and `content`.
63 *
64 * @param config - The prompt `name`, `description`, and `argsSchema`.
65 *
66 * @example
67 * ```ts
68 * const summarize = promptDefinition({
69 * name: 'summarize',
70 * description: 'Summarize a topic',
71 * argsSchema: z.object({ topic: z.string() }),
72 * }).render(async (args) => [{ role: 'user', content: args.topic }])
73 * ```
74 */
75export function promptDefinition<const TName extends string, TArgs>(config: {
76 name: TName
77 description: string
78 argsSchema: PromptArgsSchema<TArgs>
79}) {
80 const definition = {
81 name: config.name,
82 description: config.description,
83 argsSchema: config.argsSchema,
84 }
85
86 return {
87 ...definition,
88 render(
89 renderPrompt: (
90 args: TArgs,
91 ) => ReadonlyArray<PromptMessage> | Promise<ReadonlyArray<PromptMessage>>,
92 ) {
93 return {
94 ...definition,
95 async render(input: TArgs) {
96 const args = config.argsSchema.parse(input)
97 return renderPrompt(args)
98 },
99 }
100 },
101 }
102}