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

direct-client.ts

233 lines7.2 KB

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