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

direct-client.ts

212 lines6.4 KB

1import { parseWithStandardSchema } from '@tanstack/ai'
2import type { InferToolInput, InferToolOutput } from '@tanstack/ai'
3import { createServerToolContext } from './server/context'
4import { optionsOfServer } from './server/registry'
5import type { MCPServer } from './server/create-server'
6​
7type Named = { name: string }
8​
9type ToolNames<TTools extends ReadonlyArray<Named>> = TTools[number]['name']
10​
11type ToolByName<
12 TTools extends ReadonlyArray<Named>,
13 TName extends string,
14> = Extract<TTools[number], { name: TName }>
15​
16type ResourceUris<TResources extends ReadonlyArray<{ uri?: string }>> = Extract<
17 TResources[number],
18 { uri: string }
19>['uri']
20​
21type ResourceByUri<
22 TResources extends ReadonlyArray<{ uri?: string }>,
23 TUri extends string,
24> = Extract<TResources[number], { uri: TUri }>
25​
26type PromptNames<TPrompts extends ReadonlyArray<Named>> =
27 TPrompts[number]['name']
28​
29type PromptByName<
30 TPrompts extends ReadonlyArray<Named>,
31 TName extends string,
32> = Extract<TPrompts[number], { name: TName }>
33​
34type ResourceContents<TResource> = TResource extends {
35 read: () => infer TResult
37 ? Awaited<TResult>
38 : never
39​
40type PromptArgs<TPrompt> = TPrompt extends {
41 render: (input: infer TArgs) => unknown
43 ? TArgs
44 : never
45​
46type PromptMessages<TPrompt> = TPrompt extends {
47 render: (input: never) => infer TResult
49 ? Awaited<TResult>
50 : never
51​
52/**
53 * The client types of a `createMCPServer` server, for a client that
54 * connects over a transport.
55 *
56 * Pass `typeof server` to `createMCPClient` with a `transport`.
57 * Import the server with `import type`, so its code stays out of the client.
58 *
59 * @example
60 * ```ts
61 * import type { server } from './mcp-server'
62 *
63 * const client = await createMCPClient<typeof server>({
64 * transport: { type: 'http', url: 'https://mcp.example.com/mcp' },
65 * })
66 * await client.callTool('get_weather', { city: 'Paris' })
67 * ```
68 */
69export type DescriptorFromServer<TServer extends MCPServer> = {
70 tools: {
71 [TTool in TServer['tools'][number] as TTool['name']]: {
72 input: InferToolInput<TTool>
73 output: InferToolOutput<TTool>
74 }
75 }
76 resources: {
77 [TResource in Extract<
78 TServer['resources'][number],
79 { uri: string }
80 > as TResource['uri']]: {
81 uri: TResource['uri']
82 data: ResourceContents<TResource>
83 }
84 }
85 prompts: {
86 [TPrompt in TServer['prompts'][number] as TPrompt['name']]: {
87 args: PromptArgs<TPrompt>
88 messages: PromptMessages<TPrompt>
89 }
90 }
91 capabilities: Record<string, unknown>
93​
94// The same context shape that a spec 2026 call on the server gets.
95function directToolContext(server: object, signal: AbortSignal | undefined) {
96 return {
97 context: createServerToolContext({
98 era: '2026',
99 sample: optionsOfServer(server)?.sample,
100 }),
101 abortSignal: signal ?? new AbortController().signal,
102 emitCustomEvent() {},
103 }
105​
106type DirectToolContext = ReturnType<typeof directToolContext>
107​
108type ListedTool = {
109 name: string
110 inputSchema?: unknown
111 execute?: (input: never, context?: DirectToolContext) => unknown
113​
114type ListedResource = {
115 uri?: string
116 read: () => unknown
118​
119type ListedPrompt = {
120 name: string
121 render: (input: never) => unknown
123​
124/**
125 * Calls the tools, resources, and prompts on one TanStack MCP server.
126 *
127 * `server` is the object from `createMCPServer`.
128 * The tool names, resource URIs, and prompt arguments stay typed.
129 * This client does not open a network connection.
130 * `callTool` checks `args` with the tool input schema, like the HTTP server.
131 * The tool gets the spec 2026 context: `ctx.context.requestInput` throws
132 * `ToolInputRequiredError`, and `ctx.context.sample` uses the server
133 * `sample` option.
134 *
135 * @param server - The server object to call
136 *
137 * @example
138 * ```ts
139 * const client = directMCPClient(server)
140 * await client.callTool('get_weather', { city: 'Paris' })
141 * ```
142 */
143export function directMCPClient<const TServer extends MCPServer>(
144 server: TServer,
145) {
146 const tools = server.tools as ReadonlyArray<ListedTool>
147 const resources = server.resources as ReadonlyArray<ListedResource>
148 const prompts = server.prompts as ReadonlyArray<ListedPrompt>
149​
150 return {
151 server,
152​
153 async callTool<const TName extends ToolNames<TServer['tools']>>(
154 name: TName,
155 args: InferToolInput<ToolByName<TServer['tools'], TName>>,
156 options?: { signal?: AbortSignal },
157 ) {
158 const tool = tools.find((item) => item.name === name)
159 if (tool === undefined || tool.execute === undefined) {
160 throw new Error(`The MCP server has no tool ${name}.`)
161 }
162 const execute = tool.execute as (
163 input: InferToolInput<ToolByName<TServer['tools'], TName>>,
164 context?: DirectToolContext,
165 ) =>
166 | InferToolOutput<ToolByName<TServer['tools'], TName>>
167 | Promise<InferToolOutput<ToolByName<TServer['tools'], TName>>>
168 // A schema that is not a Standard Schema passes `args` through.
169 const input = parseWithStandardSchema<
170 InferToolInput<ToolByName<TServer['tools'], TName>>
171 >(tool.inputSchema, args)
172 return execute(input, directToolContext(server, options?.signal))
173 },
174​
175 async readResource<const TUri extends ResourceUris<TServer['resources']>>(
176 uri: TUri,
177 ) {
178 const resource = resources.find((item) => item.uri === uri)
179 if (resource === undefined) {
180 throw new Error(`The MCP server has no resource ${uri}.`)
181 }
182 const read = resource.read as () =>
183 | ResourceContents<ResourceByUri<TServer['resources'], TUri>>
184 | Promise<ResourceContents<ResourceByUri<TServer['resources'], TUri>>>
185 return read()
186 },
187​
188 async getPrompt<const TName extends PromptNames<TServer['prompts']>>(
189 name: TName,
190 args: PromptArgs<PromptByName<TServer['prompts'], TName>>,
191 ) {
192 const prompt = prompts.find((item) => item.name === name)
193 if (prompt === undefined) {
194 throw new Error(`The MCP server has no prompt ${name}.`)
195 }
196 const render = prompt.render as (
197 input: PromptArgs<PromptByName<TServer['prompts'], TName>>,
198 ) =>
199 | PromptMessages<PromptByName<TServer['prompts'], TName>>
200 | Promise<PromptMessages<PromptByName<TServer['prompts'], TName>>>
201 return render(args)
202 },
203 }
205​
206export type DirectMCPClient<TServer extends MCPServer> = ReturnType<
207 typeof directMCPClient<TServer>
209​
210export type DirectClientOptions<TServer extends MCPServer = MCPServer> = {
211 server: TServer