Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

definitions.ts

187 lines5.5 KB

1import type {
2 AuthInfo,
3 ListResourcesResult,
4 Variables,
5} from '@modelcontextprotocol/server'
6​
7/**
8 * What a resource `read` and `list` receive. `context` holds the values
9 * from `handle(request, { context })` and the verified `authInfo`.
10 */
11export type MCPResourceContext = {
12 context: Record<string, unknown> & { authInfo?: AuthInfo }
14​
15/** Lists the concrete resources of a template for `resources/list`. */
16export type MCPResourceList = (
17 ctx: MCPResourceContext,
18) => ListResourcesResult | Promise<ListResourcesResult>
19​
20/** Reads one resource. `variables` is `{}` for a resource with `uri`. */
21export type MCPResourceRead<TContents = unknown> = (
22 uri: URL,
23 variables: Variables,
24 ctx: MCPResourceContext,
25) => TContents | Promise<TContents>
26​
27type PromptMessage = {
28 role: string
29 content: string
31​
32type PromptArgsSchema<TArgs> = {
33 parse: (input: unknown) => TArgs
35​
36/**
37 * The `variables` that `read` gets: the result of `argsSchema.parse` when the
38 * resource has an `argsSchema`, else the template variables as matched.
39 */
40type ResourceArgsOf<TConfig> = TConfig extends {
41 argsSchema: PromptArgsSchema<infer TArgs>
43 ? TArgs
44 : Variables
45​
46/**
47 * Builds a resource definition for the MCP server.
48 *
49 * `config` takes `name`, `mimeType`, and one of `uri` or `uriTemplate`.
50 * If `uri` and `uriTemplate` are both missing, this function throws a TypeError.
51 * Only a template can take `list(ctx)`. It returns the concrete resources
52 * for `resources/list`.
53 * Call `.read` with a function that returns the resource contents.
54 * It gets the requested `uri`, the template `variables`, and `ctx`.
55 * `ctx.context` holds the values from `handle(request, { context })` and
56 * the verified `authInfo`. A tool gets the same values on its `ctx.context`.
57 *
58 * A template can also take `argsSchema`. Its `parse` runs on the variables
59 * before `read` gets them. A body `{ text | blob, mimeType }` sets the MIME
60 * type of that answer, for a template whose files have different types.
61 *
62 * @param config - The resource `name`, `mimeType`, `uri` or `uriTemplate`, `list`, and `argsSchema`.
63 * @throws {TypeError} When `uri` and `uriTemplate` are both missing.
64 *
65 * @example
66 * ```ts
67 * const readme = resourceDefinition({
68 * uri: 'file:///readme.md',
69 * name: 'readme',
70 * mimeType: 'text/markdown',
71 * }).read(async () => ({ text: '# Hello' }))
72 *
73 * const summary = resourceDefinition({
74 * uriTemplate: 'myapp://items/{itemId}/summary',
75 * name: 'item-summary',
76 * mimeType: 'text/plain',
77 * }).read(async (_uri, { itemId }) => ({ text: `Summary of ${String(itemId)}` }))
78 *
79 * const user = resourceDefinition({
80 * uriTemplate: 'users://{id}',
81 * name: 'user',
82 * mimeType: 'application/json',
83 * argsSchema: z.object({ id: z.string() }),
84 * }).read(async (_uri, { id }) => ({ text: JSON.stringify(await loadUser(id)) }))
85 * ```
86 */
87export function resourceDefinition<
88 const TConfig extends
89 | {
90 name: string
91 mimeType: string
92 uri: string
93 uriTemplate?: never
94 list?: never
95 argsSchema?: never
96 }
97 | {
98 name: string
99 mimeType: string
100 uriTemplate: string
101 uri?: never
102 list?: MCPResourceList
103 argsSchema?: PromptArgsSchema<unknown>
104 },
105>(config: TConfig) {
106 const hasUri = config.uri !== undefined
107 const hasUriTemplate = config.uriTemplate !== undefined
108 if (!hasUri && !hasUriTemplate) {
109 throw new TypeError(
110 'This resource has no uri and no uriTemplate. Pass a uri or a uriTemplate.',
111 )
112 }
113​
114 return {
115 ...config,
116 read<TContents>(
117 readContents: (
118 uri: URL,
119 variables: ResourceArgsOf<TConfig>,
120 ctx: MCPResourceContext,
121 ) => TContents | Promise<TContents>,
122 ) {
123 return {
124 ...config,
125 read: (uri: URL, variables: Variables, ctx: MCPResourceContext) =>
126 readContents(
127 uri,
128 // Without `argsSchema`, `read` gets the variables as matched.
129 // `ResourceArgsOf` picks the same branch from the config type,
130 // which TypeScript cannot follow through the runtime check.
131 (config.argsSchema
132 ? config.argsSchema.parse(variables)
133 : variables) as ResourceArgsOf<TConfig>,
134 ctx,
135 ),
136 }
137 },
138 }
140​
141/**
142 * Builds a prompt definition for the MCP server.
143 *
144 * `config` takes `name`, `description`, and `argsSchema`.
145 * `argsSchema.parse` runs before the render function receives the arguments.
146 * Call `.render` with a function that returns an array of messages.
147 * Each message has `role` and `content`.
148 *
149 * @param config - The prompt `name`, `description`, and `argsSchema`.
150 *
151 * @example
152 * ```ts
153 * const summarize = promptDefinition({
154 * name: 'summarize',
155 * description: 'Summarize a topic',
156 * argsSchema: z.object({ topic: z.string() }),
157 * }).render(async (args) => [{ role: 'user', content: args.topic }])
158 * ```
159 */
160export function promptDefinition<const TName extends string, TArgs>(config: {
161 name: TName
162 description: string
163 argsSchema: PromptArgsSchema<TArgs>
164}) {
165 const definition = {
166 name: config.name,
167 description: config.description,
168 argsSchema: config.argsSchema,
169 }
170​
171 return {
172 ...definition,
173 render(
174 renderPrompt: (
175 args: TArgs,
176 ) => ReadonlyArray<PromptMessage> | Promise<ReadonlyArray<PromptMessage>>,
177 ) {
178 return {
179 ...definition,
180 async render(input: TArgs) {
181 const args = config.argsSchema.parse(input)
182 return renderPrompt(args)
183 },
184 }
185 },
186 }