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

transport.ts

84 lines2.4 KB

1import {
2 SSEClientTransport,
3 StreamableHTTPClientTransport,
4} from '@modelcontextprotocol/client'
5import type {
6 OAuthClientProvider,
7 Transport,
8} from '@modelcontextprotocol/client'
9​
10export interface HttpTransportConfig {
11 type: 'http'
12 url: string
13 headers?: Record<string, string>
14 fetch?: typeof fetch
15 authProvider?: OAuthClientProvider
17​
18export interface SseTransportConfig {
19 type: 'sse'
20 url: string
21 headers?: Record<string, string>
22 fetch?: typeof fetch
23 authProvider?: OAuthClientProvider
25​
26/** stdio is declared here for typing but constructed only via `@tanstack/ai-mcp/stdio`. */
27export interface StdioTransportConfig {
28 type: 'stdio'
29 command: string
30 args?: Array<string>
31 env?: Record<string, string>
32 cwd?: string
34​
35export type TransportConfig =
36 | HttpTransportConfig
37 | SseTransportConfig
38 | StdioTransportConfig
39​
40/** Either a built-in config or a ready-made Transport instance (escape hatch). */
41export type TransportInput = TransportConfig | Transport
42​
43/**
44 * Return true when `input` is already a Transport, not a config object.
45 */
46export function isTransportInstance(input: TransportInput): input is Transport {
47 return 'start' in input && typeof input.start === 'function'
49​
50/**
51 * Build a Transport from HTTP config, SSE config, or an existing Transport.
52 *
53 * For stdio, build the Transport with `stdioTransport` and pass that instance.
54 * Throws an Error when the config type is `stdio` or is not a known type.
55 */
56export async function resolveTransport(input: TransportInput) {
57 if (isTransportInstance(input)) return input
58​
59 switch (input.type) {
60 case 'http':
61 return new StreamableHTTPClientTransport(new URL(input.url), {
62 requestInit: { headers: input.headers },
63 fetch: input.fetch,
64 authProvider: input.authProvider,
65 })
66 case 'sse':
67 return new SSEClientTransport(new URL(input.url), {
68 requestInit: { headers: input.headers },
69 fetch: input.fetch,
70 authProvider: input.authProvider,
71 })
72 case 'stdio':
73 throw new Error(
74 "stdio transport must be created via '@tanstack/ai-mcp/stdio': " +
75 "import { stdioTransport } from '@tanstack/ai-mcp/stdio' and pass the result as `transport`.",
76 )
77 default: {
78 const unknownConfig: never = input
79 throw new Error(
80 `Unknown MCP transport config: ${JSON.stringify(unknownConfig)}`,
81 )
82 }
83 }