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

harness-plugin.ts

778 lines26.0 KB

1import { defineCommand, definePlugin } from '@tanstack/ai-harness'
2import { connectTransport } from './client'
3import type { ElicitResult } from '@modelcontextprotocol/client'
4import type { AnyTool, JSONSchema, Logger } from '@tanstack/ai'
5import type {
6 AnyCommand,
7 PluginPrompt,
8 PluginResources,
9 PluginSessionApi,
10 PluginSetupContext,
11 RunContext,
12 TurnInfo,
13} from '@tanstack/ai-harness'
14import type { MCPClient, OnElicit } from './client'
15import type { McpConnectorOptions } from './connector'
16import type { AskInput } from './tools'
17import type { MCPClientOptions } from './types'
18import type { HttpTransportConfig, StdioTransportConfig } from './transport'
19​
20/** One server of {@link mcp}, keyed by its name. */
21export type McpServerConfig = (
22 | StdioTransportConfig
23 | (HttpTransportConfig & {
24 /**
25 * Sign in with OAuth, like `mcpConnector`. This adds `/connect <name>`
26 * and `/disconnect <name>`. The tools of the server come after the
27 * sign-in, and the tools that are not read-only ask for approval.
28 * `headers` and `authProvider` do not apply then.
29 */
30 oauth?: boolean
31 })
32) & {
33 /**
34 * The time in milliseconds that this server can take to connect, to send
35 * its tool list, or to answer a tool call. Default: the MCP SDK default,
36 * 60,000.
37 */
38 timeoutMs?: number
39 /**
40 * Give the tools of this server to code mode: the `codeMode()` plugin of
41 * `@tanstack/ai-code-mode` takes them out of the tool list and lets the
42 * model call them from `execute_typescript`. Without that plugin, nothing
43 * changes.
44 */
45 codeMode?: boolean
46 /**
47 * Ask the user for approval before a tool of this server runs. `true` asks
48 * for every tool. A function gets the MCP tool definition and returns
49 * `true` to ask. Default: no approval, and for `oauth: true` every tool
50 * that the server does not mark `readOnlyHint`.
51 */
52 needsApproval?: boolean | McpConnectorOptions['needsApproval']
53 /**
54 * The name the model sees for each tool of this server. It gets the MCP
55 * tool definition. Default: `<server>_<tool>`.
56 */
57 toolName?: MCPClientOptions['toolName']
59​
60/**
61 * The status of one server. UIs read the list from
62 * `snapshot().plugins['tanstack/mcp'].servers`. A server is `reconnecting`
63 * after its connection closed, until a new connection is open.
64 */
65export type McpServerStatus = {
66 name: string
67 /** How many tools the server gives the model. */
68 toolCount: number
69} & (
70 | { status: 'connecting' | 'connected' | 'reconnecting' }
71 | { status: 'failed'; error: string }
73​
74/**
75 * A harness plugin that connects MCP servers and gives the model their
76 * tools, named `<server>_<tool>`.
77 *
78 * - Each server connects on its own. A server that fails does not stop the
79 * others: it gets the status `failed` with the error.
80 * - The servers connect in the background. The first turn waits for them.
81 * - `/mcp` lists the servers and their status. UIs read the same list from
82 * the plugin state.
83 * - A `stdio` server runs as one child process (Node only) for every
84 * session of the harness on the host that uses this `mcp()` object. It
85 * stops when the last of those sessions closes, or at `host.close()`.
86 * Create the plugin once, outside the `plugins` factory: a factory that
87 * calls `mcp()` for each session starts a process for each session. The
88 * other servers connect for each session.
89 * - An `http` server with `oauth: true` signs in through `/connect <name>`.
90 * - When the connection of a server closes, the server is `reconnecting`.
91 * The plugin connects again after 0.5 s, 1 s, 2 s, and so on (at most
92 * 30 s), until it is connected or its session or host closes. The wait
93 * starts again at 0.5 s only after a connection stayed open for 30 s, so a
94 * server that crashes right after it connects waits longer each time. The
95 * next turn gets the tools of the new connection. A server that fails its
96 * first connect is `failed`, and connects again the same way.
97 * - A spec 2025 server that asks for input (`elicitation/create`) does not
98 * name the tool call that asks. The user of the call is asked only when
99 * all the calls of that server that run now belong to one run. Else the
100 * request is declined, so a question never goes to another user.
101 * - When a server sends `tools/list_changed`, the next turn lists its tools
102 * again.
103 * - When two servers give a tool with the same name, the model gets the
104 * tool of the server that comes first in `servers`. The plugin warns once,
105 * to the host logger (`createHarnessHost({ logger })`). With
106 * `onDuplicateTool: 'error'`, the later server fails instead.
107 *
108 * @param options.servers - The servers, keyed by name. The name is the tool
109 * prefix.
110 * @param options.onDuplicateTool - What happens when a server gives a tool
111 * name that a server earlier in `servers` gives too. `'warn'` (default):
112 * the model does not get that one tool, and the plugin warns once.
113 * `'error'`: the later server gets the status `failed` with an error that
114 * names both servers and the tool, and the model gets none of its tools.
115 * The other servers keep working.
116 *
117 * @example
118 * ```ts
119 * import { mcp } from '@tanstack/ai-mcp/harness'
120 *
121 * // Once, so the sessions share the stdio process.
122 * const tools = mcp({
123 * servers: {
124 * files: { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '.'] },
125 * docs: { type: 'http', url: 'https://mcp.example.com/mcp', timeoutMs: 10_000 },
126 * notion: { type: 'http', url: 'https://mcp.notion.com/mcp', oauth: true },
127 * },
128 * })
129 *
130 * plugins: () => [tools]
131 * ```
132 */
133export function mcp(options: {
134 servers: Readonly<Record<string, McpServerConfig>>
135 onDuplicateTool?: 'warn' | 'error'
136}) {
137 const servers = Object.entries(options.servers)
138 return definePlugin({
139 name: 'tanstack/mcp',
140 // The stdio servers connect once for the host. The rest is per session.
141 lifetime: 'host',
142 setup: (host) => {
143 // The tool calls of a shared server that run now, newest last.
144 const calling: Array<Caller> = []
145 // A spec 2025 request of a shared server goes to the run that calls,
146 // only when one run calls. Else it is declined (see `elicitFor`).
147 const askCaller = elicitFor(calling)
148 const shared = new Map<string, SharedServer>()
149 for (const [name, server] of servers) {
150 if (server.type !== 'stdio') continue
151 shared.set(name, openServer(host.resources, name, server, askCaller))
152 }
153 // The tool name clashes that were warned about, for all sessions.
154 const warned = new Set<string>()
155 const onDuplicate = options.onDuplicateTool ?? 'warn'
156 return {
157 session: (ctx) =>
158 sessionPart(ctx, servers, shared, calling, warned, onDuplicate),
159 }
160 },
161 })
163​
164/** The part of {@link mcp} that each session sets up. */
165async function sessionPart(
166 ctx: PluginSetupContext,
167 servers: ReadonlyArray<[string, McpServerConfig]>,
168 shared: ReadonlyMap<string, SharedServer>,
169 calling: Array<Caller>,
170 warned: Set<string>,
171 onDuplicate: 'warn' | 'error',
172) {
173 const statuses = new Map<string, McpServerStatus>()
174 for (const [name] of servers) {
175 statuses.set(name, { name, status: 'connecting', toolCount: 0 })
176 }
177 const state = ctx.state({ servers: [...statuses.values()] })
178 const setStatus = async (status: McpServerStatus) => {
179 const old = JSON.stringify(statuses.get(status.name))
180 statuses.set(status.name, status)
181 if (old === JSON.stringify(status)) return
182 await state.update(() => ({ servers: [...statuses.values()] }))
183 }
184 // State from an earlier run of this session is out of date.
185 await state.update(() => ({ servers: [...statuses.values()] }))
186​
187 /**
188 * Connect one server in the background. Returns the tools of the server
189 * for each turn. A stdio server is the shared one of the host. Never
190 * rejects.
191 */
192 const connect = (name: string, server: McpServerConfig) => {
193 const sharedServer = shared.get(name)
194 // The tool calls of this server for this session that run now.
195 const own: Array<Caller> = []
196 const opened =
197 sharedServer ?? openServer(ctx.resources, name, server, elicitFor(own))
198 // After the session closed, the state store can be gone. `/mcp`
199 // reads `statuses`, which is set first.
200 const opening = opened.then(async (link) => {
201 if (link instanceof Error) {
202 await setStatus({
203 name,
204 status: 'failed',
205 error: link.message,
206 toolCount: 0,
207 }).catch(() => undefined)
208 return undefined
209 }
210 const update = () => setStatus(link.status()).catch(() => undefined)
211 link.watch(() => void update(), ctx.resources.signal)
212 await update()
213 return link
214 })
215 return async (_turn: TurnInfo) => {
216 const link = await opening
217 if (!link) return []
218 const tools = trackCaller(
219 await link.tools(),
220 ctx.session,
221 sharedServer ? calling : own,
222 )
223 return askForInput(tools, ctx.session)
224 }
225 }
226​
227 const commands: Record<string, AnyCommand> = {
228 mcp: defineCommand({
229 description: 'Show the MCP servers and their status',
230 run: () => [...statuses.values()].map(statusLine).join('\n'),
231 }),
232 }
233 const prompts: Array<PluginPrompt> = []
234 // One tool list for each server, in the order of `servers`.
235 const lists = await Promise.all(
236 servers.map(async (entry) => {
237 const [name, server] = entry
238 const isOAuth = server.type === 'http' && server.oauth === true
239 if (!isOAuth) return { name, list: connect(name, server) }
240 // Loaded here: the connector needs node:crypto and node:http.
241 const { mcpConnector } = await import('./connector')
242 const connector = await mcpConnector({
243 id: name,
244 label: name,
245 url: server.url,
246 toolName: server.toolName,
247 needsApproval: approvalOf(server),
248 requestOptions: requestOptionsOf(server),
249 ...(server.fetch ? { fetch: server.fetch } : {}),
250 }).setup(ctx)
251 Object.assign(commands, connector.commands)
252 prompts.push(...connector.prompts)
253 // The sign-in belongs to the sender of the turn, so the status is
254 // the one of the last turn.
255 const list = async (turn: TurnInfo) => {
256 try {
257 const tools = await connector.discoverTools(turn)
258 const signedIn =
259 tools.length > 0 || (await turn.run.credentials.get(name)) !== null
260 await setStatus(
261 signedIn
262 ? { name, status: 'connected', toolCount: tools.length }
263 : {
264 name,
265 status: 'failed',
266 error: `Not signed in. Run /connect ${name}.`,
267 toolCount: 0,
268 },
269 )
270 return forCodeMode(server, tools)
271 } catch (error) {
272 // One server that fails must not hide the tools of the others.
273 await setStatus({
274 name,
275 status: 'failed',
276 error: errorText(error),
277 toolCount: 0,
278 })
279 return []
280 }
281 }
282 return { name, list }
283 }),
284 )
285​
286 return {
287 commands,
288 prompts,
289 discoverTools: async (turn: TurnInfo) => {
290 const found = await Promise.all(
291 lists.map(async ({ name, list }) => ({
292 name,
293 tools: await list(turn),
294 })),
295 )
296 return onDuplicate === 'error'
297 ? failOnDuplicate(found, setStatus)
298 : keepFirstTools(found, warned, ctx.logger)
299 },
300 }
302​
303/** A server that the sessions of a host share: its connection, or its error. */
304type SharedServer = ReturnType<typeof openServer>
305​
306/**
307 * Connect one server in `resources`. It never rejects: an error that stops
308 * the setup itself resolves to that error.
309 *
310 * When the first connect fails, the status is `failed` with the error, and
311 * the server connects again with backoff. When the connection closes later,
312 * the status is `reconnecting`, with the same backoff. Both go on until a
313 * connection is open or `resources` is disposed. After
314 * `tools/list_changed`, the next `tools()` lists the tools again.
315 */
316function openServer(
317 resources: PluginResources,
318 name: string,
319 server: McpServerConfig,
320 onElicit: OnElicit,
321) {
322 const { signal } = resources
323 const watchers = new Set<() => void>()
324 let status: McpServerStatus = { name, status: 'connecting', toolCount: 0 }
325 let client: MCPClient | undefined
326 let tools: ReadonlyArray<AnyTool> = []
327 // Set by tools/list_changed. The next `tools()` lists the tools again.
328 let stale = false
329 let listing: Promise<void> | undefined
330 // The backoff goes on across drops, so a server that crashes right after
331 // it connects waits longer each time. It resets only after a connection
332 // stayed open for `stableMs`.
333 let attempt = 0
334 let openedAt = 0
335​
336 const setStatus = (next: McpServerStatus) => {
337 status = next
338 for (const watcher of watchers) watcher()
339 }
340​
341 /** One connection with its tool list. Throws when the server fails. */
342 const open = async () => {
343 // Loaded here: the stdio transport needs node:child_process.
344 const transport =
345 server.type === 'stdio'
346 ? (await import('./stdio')).stdioTransport(server)
347 : server
348 const next = await connectTransport(
349 {
350 transport,
351 prefix: name,
352 toolName: server.toolName,
353 needsApproval: approvalOf(server),
354 requestOptions: requestOptionsOf(server),
355 clientOptions: harnessClientOptions,
356 onClose: () => dropped(),
357 onToolListChanged: () => {
358 stale = true
359 },
360 },
361 onElicit,
362 )
363 let listed: ReadonlyArray<AnyTool>
364 try {
365 listed = forCodeMode(server, await next.tools())
366 } catch (error) {
367 // Connected, but no tool list: the server failed.
368 await next.close().catch(() => undefined)
369 throw error
370 }
371 // Disposed while this connect ran: nothing uses the connection.
372 if (signal.aborted) {
373 await next.close().catch(() => undefined)
374 throw signal.reason
375 }
376 client = next
377 tools = listed
378 stale = false
379 openedAt = Date.now()
380 setStatus({ name, status: 'connected', toolCount: listed.length })
381 }
382​
383 /** The connection closed, and this plugin did not close it. */
384 const dropped = () => {
385 if (status.status !== 'connected' || signal.aborted) return
386 client = undefined
387 tools = []
388 if (Date.now() - openedAt >= stableMs) attempt = 0
389 setStatus({ name, status: 'reconnecting', toolCount: 0 })
390 void reconnect()
391 }
392​
393 const reconnect = async () => {
394 for (;;) {
395 await delay(backoffMs(attempt++), signal)
396 if (signal.aborted) return
397 const isOpen = await open().then(
398 () => true,
399 () => false,
400 )
401 if (isOpen) return
402 }
403 }
404​
405 /** List the tools of `current` again. On a failure, the old list stays. */
406 const relist = async (current: MCPClient) => {
407 stale = false
408 const listed = await current.tools().then(
409 (found) => forCodeMode(server, found),
410 () => undefined,
411 )
412 // The connection closed while it listed.
413 if (client !== current) return
414 if (listed === undefined) {
415 stale = true
416 return
417 }
418 tools = listed
419 setStatus({ name, status: 'connected', toolCount: listed.length })
420 }
421​
422 const link = {
423 status: () => status,
424 /** The tools of the open connection. Never rejects. */
425 tools: async () => {
426 if (stale && client) {
427 listing ??= relist(client).finally(() => {
428 listing = undefined
429 })
430 await listing
431 }
432 return tools
433 },
434 /** Calls `watcher` after each status change, until `until` aborts. */
435 watch: (watcher: () => void, until: AbortSignal) => {
436 if (until.aborted) return
437 watchers.add(watcher)
438 until.addEventListener('abort', () => watchers.delete(watcher), {
439 once: true,
440 })
441 },
442 }
443​
444 return resources
445 .acquire(
446 async () => {
447 try {
448 await open()
449 } catch (error) {
450 if (signal.aborted) throw error
451 // A server that is not up yet (a slow `npx`, a short outage) gets
452 // its tools at a later turn.
453 setStatus({
454 name,
455 status: 'failed',
456 error: errorText(error),
457 toolCount: 0,
458 })
459 void reconnect()
460 }
461 return link
462 },
463 () => client?.close(),
464 )
465 .catch((error: unknown) => new Error(errorText(error)))
467​
468/** How long a connection stays open before the backoff starts again at 0.5 s. */
469const stableMs = 30_000
470​
471/**
472 * The wait before reconnect `attempt` (0 is the first): 0.5 s, 1 s, 2 s,
473 * and so on, at most 30 s. A random part of up to half the wait keeps the
474 * sessions of many hosts from connecting at the same moment.
475 */
476function backoffMs(attempt: number) {
477 const full = Math.min(500 * 2 ** attempt, 30_000)
478 return full / 2 + Math.random() * (full / 2)
480​
481/** Resolves after `ms`, or at once when `signal` aborts. */
482function delay(ms: number, signal: AbortSignal) {
483 return new Promise<void>((resolve) => {
484 // An aborted signal never fires `abort` again.
485 if (signal.aborted) return resolve()
486 const done = () => {
487 clearTimeout(timer)
488 signal.removeEventListener('abort', done)
489 resolve()
490 }
491 const timer = setTimeout(done, ms)
492 signal.addEventListener('abort', done, { once: true })
493 })
495​
496/** The `needsApproval` of a server for the client and the connector. */
497function approvalOf(server: McpServerConfig) {
498 const { needsApproval } = server
499 if (typeof needsApproval !== 'boolean') return needsApproval
500 return () => needsApproval
502​
503/**
504 * The tools of all servers, in server order. A tool whose name an earlier
505 * server already gives is dropped. Each pair of servers warns once, to
506 * `logger`.
507 */
508function keepFirstTools(
509 found: ReadonlyArray<{ name: string; tools: ReadonlyArray<AnyTool> }>,
510 warned: Set<string>,
511 logger: Logger,
512) {
513 const owners = new Map<string, string>()
514 const kept: Array<AnyTool> = []
515 for (const { name, tools } of found) {
516 for (const tool of tools) {
517 const owner = owners.get(tool.name)
518 if (owner === undefined) {
519 owners.set(tool.name, name)
520 kept.push(tool)
521 continue
522 }
523 const pair = JSON.stringify([owner, name])
524 if (warned.has(pair)) continue
525 warned.add(pair)
526 logger.warn(
527 `[@tanstack/ai-mcp] The MCP servers ${JSON.stringify(owner)} and ${JSON.stringify(name)} both give the tool ${JSON.stringify(tool.name)}. The model gets the tool of ${JSON.stringify(owner)}. Set toolName on one of the servers to rename its tools.`,
528 )
529 }
530 }
531 return kept
533​
534/**
535 * The tools of all servers, in server order. A server that gives a tool name
536 * of an earlier server gets the status `failed`, and none of its tools.
537 */
538async function failOnDuplicate(
539 found: ReadonlyArray<{ name: string; tools: ReadonlyArray<AnyTool> }>,
540 setStatus: (status: McpServerStatus) => Promise<void>,
541) {
542 const owners = new Map<string, string>()
543 const kept: Array<AnyTool> = []
544 for (const { name, tools } of found) {
545 const clash = tools.find((tool) => owners.has(tool.name))
546 if (clash) {
547 const owner = owners.get(clash.name)
548 await setStatus({
549 name,
550 status: 'failed',
551 error: `The MCP servers ${JSON.stringify(owner)} and ${JSON.stringify(name)} both give the tool ${JSON.stringify(clash.name)}. Set toolName on one of the servers to rename its tools.`,
552 toolCount: 0,
553 })
554 continue
555 }
556 for (const tool of tools) owners.set(tool.name, name)
557 kept.push(...tools)
558 }
559 return kept
561​
562/** A tool call that runs now: its session, and the run that calls. */
563export interface Caller {
564 session: PluginSessionApi
565 run?: RunContext
567​
568/**
569 * Puts each call of `tools` in `calling` while it runs, with its session
570 * and its run, so a spec 2025 elicitation can find the run that calls.
571 */
572export function trackCaller(
573 tools: ReadonlyArray<AnyTool>,
574 session: PluginSessionApi,
575 calling: Array<Caller>,
576) {
577 return tools.map((tool): AnyTool => {
578 const execute = tool.execute
579 if (!execute) return tool
580 return {
581 ...tool,
582 execute: async (args, context) => {
583 const run = runOf(context)
584 const caller: Caller = { session, ...(run ? { run } : {}) }
585 calling.push(caller)
586 try {
587 return await execute(args, context)
588 } finally {
589 calling.splice(calling.lastIndexOf(caller), 1)
590 }
591 },
592 }
593 })
595​
596/**
597 * The harness asks the user for form and URL elicitations, so its clients
598 * declare both. `chat()` clients keep the default: form only.
599 */
600export const harnessClientOptions = {
601 capabilities: { elicitation: { form: {}, url: {} } },
603​
604/**
605 * Ask the session user when an MCP tool asks for input (a form or a URL
606 * elicitation). The tool call waits for the answer, then sends it to the
607 * server. On spec 2026, a tool call can ask up to 5 times. The answer is the
608 * form content, or an MCP result such as `{ action: 'decline' }` or
609 * `{ action: 'cancel' }`.
610 */
611export function askForInput(
612 tools: ReadonlyArray<AnyTool>,
613 session: PluginSessionApi,
614) {
615 return tools.map((tool): AnyTool => {
616 const execute = tool.execute
617 if (!execute) return tool
618 return {
619 ...tool,
620 execute: (args, context) => {
621 // The question is a wait of the run of this call.
622 const run = runOf(context)
623 const askInput: AskInput = async (request) => ({
624 status: 'resolved',
625 payload: await ask(session, request, run),
626 })
627 return execute(args, {
628 ...(isRecord(context) ? context : {}),
629 askInput,
630 })
631 },
632 }
633 })
635​
636/**
637 * Answers the `elicitation/create` requests of a spec 2025 server. The
638 * request does not name the tool call that it belongs to. So it asks only
639 * when the calls of `calling` all belong to one run of one session, as a
640 * live wait of that run. With no call, or with calls of more than one run
641 * (two users or tenants can share a server), it declines: a question must
642 * never go to the user of another run.
643 */
644export function elicitFor(calling: ReadonlyArray<Caller>): OnElicit {
645 return async (params) => {
646 const [caller] = calling
647 if (!caller) return { action: 'decline' }
648 const isOneRun = calling.every(
649 (other) =>
650 other.session === caller.session &&
651 other.run !== undefined &&
652 other.run.runId === caller.run?.runId,
653 )
654 if (!isOneRun) return { action: 'decline' }
655 return elicitResult(await ask(caller.session, params, caller.run))
656 }
658​
659/**
660 * Asks the session user for one MCP elicitation request body, as a live
661 * wait of `run`, by the name `mcp-elicitation`. With no run, it declines:
662 * only a run can wait for the user.
663 */
664async function ask(
665 session: PluginSessionApi,
666 request: unknown,
667 run: RunContext | undefined,
668) {
669 if (!run) return { action: 'decline' }
670 const body = isRecord(request) ? request : {}
671 const url =
672 body.mode === 'url' && typeof body.url === 'string' ? body.url : undefined
673 const answer = await session.ask({
674 message:
675 typeof body.message === 'string'
676 ? body.message
677 : 'The MCP server asks for input.',
678 schema: isJsonSchema(body.requestedSchema)
679 ? body.requestedSchema
680 : undefined,
681 ...(url ? { url } : {}),
682 live: { name: 'mcp-elicitation', run },
683 })
684 // A URL request has no content: the answer only says "done".
685 return url !== undefined && !(isRecord(answer) && 'action' in answer)
686 ? { action: 'accept' }
687 : answer
689​
690/** Maps an answer to the MCP result: decline, cancel, or accept. */
691function elicitResult(answer: unknown): ElicitResult {
692 if (
693 isRecord(answer) &&
694 (answer.action === 'decline' || answer.action === 'cancel')
695 ) {
696 return { action: answer.action }
697 }
698 const content =
699 isRecord(answer) && answer.action === 'accept' ? answer.content : answer
700 return isElicitContent(content)
701 ? { action: 'accept', content }
702 : { action: 'accept' }
704​
705// ponytail: the SDK checks the result against the schema of the request.
706function isElicitContent(
707 value: unknown,
708): value is NonNullable<ElicitResult['content']> {
709 return isRecord(value)
711​
712function isRecord(value: unknown): value is Record<string, unknown> {
713 return typeof value === 'object' && value !== null
715​
716/** The run of a harness tool call, from its context: `ctx.context.run`. */
717function runOf(context: unknown): RunContext | undefined {
718 const run =
719 isRecord(context) && isRecord(context.context)
720 ? context.context.run
721 : undefined
722 return isRunContext(run) ? run : undefined
724​
725// ponytail: the harness sets `ctx.context.run`. A run id and a signal tell
726// it apart from other context values.
727function isRunContext(value: unknown): value is RunContext {
728 return (
729 isRecord(value) &&
730 typeof value.runId === 'string' &&
731 value.signal instanceof AbortSignal
732 )
734​
735// ponytail: the server owns the schema. The session passes it on as is.
736function isJsonSchema(value: unknown): value is JSONSchema {
737 return isRecord(value)
739​
740/** The SDK request options for `timeoutMs`. */
741function requestOptionsOf(server: McpServerConfig) {
742 return server.timeoutMs === undefined
743 ? undefined
744 : { timeout: server.timeoutMs }
746​
747/** Marks the tools of a `codeMode: true` server for the `codeMode()` plugin. */
748function forCodeMode(server: McpServerConfig, tools: ReadonlyArray<AnyTool>) {
749 if (server.codeMode !== true) return tools
750 return tools.map((tool) => ({
751 ...tool,
752 metadata: { ...tool.metadata, codeMode: true },
753 }))
755​
756function statusLine(server: McpServerStatus) {
757 switch (server.status) {
758 case 'connecting':
759 return `${server.name}: connecting`
760 case 'reconnecting':
761 return `${server.name}: reconnecting`
762 case 'connected': {
763 const unit = server.toolCount === 1 ? 'tool' : 'tools'
764 return `${server.name}: connected (${server.toolCount} ${unit})`
765 }
766 case 'failed':
767 return `${server.name}: failed: ${server.error}`
768 }
770​
771/** The error text for the status. A connect error keeps its reason in `cause`. */
772function errorText(error: unknown) {
773 if (!(error instanceof Error)) return String(error)
774 const { cause } = error
775 return cause instanceof Error
776 ? `${error.message}: ${cause.message}`
777 : error.message