@mcp-z/client 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/auth/discovery-fetch.ts"],"sourcesContent":["/**\n * Hardened fetch for OAuth discovery URLs, which the remote MCP server\n * controls (SSRF mitigation). See ARCHITECTURE.md's \"SSRF mitigation\" section for the threat model.\n */\nimport dns from 'node:dns/promises';\nimport { isIP } from 'node:net';\nimport ipaddr from 'ipaddr.js';\n\nexport class DiscoveryFetchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'DiscoveryFetchError';\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_REDIRECTS = 5;\nconst MAX_BODY_BYTES = 1_000_000; // 1 MB - discovery documents are small JSON\n\nfunction stripBrackets(hostname: string): string {\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n}\n\n/** True for the literal hostname `localhost` or an IP literal in the loopback range. */\nfunction isLoopbackHost(hostname: string): boolean {\n const host = stripBrackets(hostname).toLowerCase();\n if (host === 'localhost') return true;\n if (isIP(host)) {\n try {\n return ipaddr.process(host).range() === 'loopback';\n } catch {\n return false;\n }\n }\n return false;\n}\n\n/**\n * True if `rawUrl`'s host is loopback, used to decide `allowLoopback` grants\n * from the URL the caller configured, not remote-supplied data. Fails closed on an unparseable URL.\n */\nexport function isLoopbackUrl(rawUrl: string): boolean {\n try {\n return isLoopbackHost(new URL(rawUrl).hostname);\n } catch {\n return false;\n }\n}\n\n/** True when the address is anything other than ordinary public unicast space. */\nfunction isBlockedAddress(address: string): boolean {\n try {\n // ipaddr.process() normalizes IPv4-mapped IPv6 (::ffff:a.b.c.d) to IPv4 first.\n return ipaddr.process(address).range() !== 'unicast';\n } catch {\n return true; // unparseable - fail closed\n }\n}\n\n/**\n * Validates scheme and, for literal-IP hosts, address range. `allowLoopback`\n * reflects trust in the calling server, never in `rawUrl` itself.\n */\nfunction assertSafeUrl(rawUrl: string, context: string, allowLoopback: boolean): URL {\n let url: URL;\n try {\n url = new URL(rawUrl);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid URL`);\n }\n\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: unsupported scheme`);\n }\n\n const host = stripBrackets(url.hostname);\n const trustedLoopback = allowLoopback && isLoopbackHost(host);\n if (trustedLoopback) return url; // this call's own grant covers it, regardless of scheme\n\n if (url.protocol === 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: http:// is only allowed for a trusted loopback origin`);\n }\n\n if (isIP(host) && isBlockedAddress(host)) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: address is not publicly routable`);\n }\n\n return url;\n}\n\n/**\n * Resolves the hostname and rejects it if any address is private/reserved.\n * Does not close the DNS-rebinding TOCTOU race against `fetch`'s own resolution a moment later.\n */\nasync function assertResolvesToSafeAddress(url: URL, context: string, allowLoopback: boolean): Promise<void> {\n const host = stripBrackets(url.hostname);\n if (isIP(host)) return; // literal IP already fully checked in assertSafeUrl\n if (allowLoopback && isLoopbackHost(host)) return; // literal \"localhost\" under a trusted-loopback grant\n\n let addresses: string[];\n try {\n const records = await dns.lookup(host, { all: true, verbatim: true });\n addresses = records.map((record) => record.address);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host could not be resolved`);\n }\n\n if (addresses.length === 0 || addresses.some((address) => isBlockedAddress(address))) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host resolves to an address that is not publicly routable`);\n }\n}\n\nasync function readLimited(response: Response, context: string, maxBytes: number): Promise<string> {\n const contentLength = response.headers.get('content-length');\n if (contentLength && Number(contentLength) > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n const text = await response.text();\n if (Buffer.byteLength(text, 'utf8') > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n return text;\n }\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString('utf8');\n}\n\nasync function fetchOnce(url: URL, init: RequestInit, context: string, allowLoopback: boolean, timeoutMs: number): Promise<Response> {\n await assertResolvesToSafeAddress(url, context, allowLoopback);\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { ...init, redirect: 'manual', signal: controller.signal });\n } catch {\n // Never surface the underlying error (ECONNREFUSED host/port, DNS detail, etc.)\n throw new DiscoveryFetchError(`Failed to fetch ${context}`);\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport interface DiscoveryFetchOptions {\n /**\n * Loopback trust grant for this fetch, computed from the server the caller\n * is actually talking to - never from the URL being fetched. Defaults to `false`.\n */\n allowLoopback?: boolean;\n /**\n * Per-request connect/read timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`;\n * overridable so tests can bound slow-failure cases.\n */\n timeoutMs?: number;\n}\n\n/**\n * Fetches an OAuth-discovery URL with SSRF mitigations applied to the\n * initial URL and every redirect hop; redirects are validated, not auto-followed.\n *\n * @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).\n * @param init - Standard fetch options; `redirect` is always forced to `'manual'`.\n * @param context - Short label used only in error messages, never echoing the URL.\n * @param options - See `DiscoveryFetchOptions`.\n */\nexport async function discoveryFetch(rawUrl: string, init: RequestInit = {}, context = 'discovery URL', options: DiscoveryFetchOptions = {}): Promise<Response> {\n const { allowLoopback = false, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n\n let url = assertSafeUrl(rawUrl, context, allowLoopback);\n let response = await fetchOnce(url, init, context, allowLoopback, timeoutMs);\n\n let redirectsLeft = MAX_REDIRECTS;\n while (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n if (!location) break;\n if (redirectsLeft <= 0) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: too many redirects`);\n }\n redirectsLeft -= 1;\n\n let nextUrl: URL;\n try {\n nextUrl = new URL(location, url);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid redirect target`);\n }\n url = assertSafeUrl(nextUrl.toString(), context, allowLoopback);\n response = await fetchOnce(url, init, context, allowLoopback, timeoutMs);\n }\n\n return response;\n}\n\n/**\n * Parse a `discoveryFetch` response body as JSON, enforcing `MAX_BODY_BYTES`\n * while reading (not after buffering the whole thing).\n */\nexport async function readDiscoveryJson<T>(response: Response, context: string): Promise<T> {\n const text = await readLimited(response, context, MAX_BODY_BYTES);\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new DiscoveryFetchError(`Refusing to parse ${context}: invalid JSON`);\n }\n}\n"],"names":["DiscoveryFetchError","discoveryFetch","isLoopbackUrl","readDiscoveryJson","message","name","Error","DEFAULT_TIMEOUT_MS","MAX_REDIRECTS","MAX_BODY_BYTES","stripBrackets","hostname","startsWith","endsWith","slice","isLoopbackHost","host","toLowerCase","isIP","ipaddr","process","range","rawUrl","URL","isBlockedAddress","address","assertSafeUrl","context","allowLoopback","url","protocol","trustedLoopback","assertResolvesToSafeAddress","addresses","records","dns","lookup","all","verbatim","map","record","length","some","readLimited","response","maxBytes","contentLength","reader","text","chunks","total","done","value","headers","get","Number","body","getReader","Buffer","byteLength","read","push","releaseLock","concat","chunk","from","toString","fetchOnce","init","timeoutMs","controller","timeout","AbortController","setTimeout","abort","fetch","redirect","signal","clearTimeout","options","redirectsLeft","location","nextUrl","status","JSON","parse"],"mappings":"AAAA;;;CAGC;;;;;;;;;;;QAKYA;eAAAA;;QAgLSC;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AAA,KAAAA;oBACJ,IAAI;wBACFA,UAAU,IAAI3D,IAAI0D,UAAUpD;oBAC9B,EAAE,eAAM;wBACN,MAAM,IAAI7B,oBAAoB,AAAC,qBAA4B,OAAR2B,SAAQ;oBAC7D;oBACAE,MAAMH,cAAcwD,QAAQhB,QAAQ,IAAIvC,SAASC;oBACtC;;wBAAMuC,UAAUtC,KAAKuC,MAAMzC,SAASC,eAAeyC;;;oBAA9DzB,WAAW;;;;;;oBAGb;;wBAAOA;;;;IACT;;AAMO,SAAezC,kBAAqByC,QAAkB,EAAEjB,OAAe;;YACtEqB;;;;oBAAO;;wBAAML,YAAYC,UAAUjB,SAASlB;;;oBAA5CuC,OAAO;oBACb,IAAI;wBACF;;4BAAOoC,KAAKC,KAAK,CAACrC;;oBACpB,EAAE,eAAM;wBACN,MAAM,IAAIhD,oBAAoB,AAAC,qBAA4B,OAAR2B,SAAQ;oBAC7D;;;;;;IACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/auth/discovery-fetch.ts"],"sourcesContent":["/**\n * Hardened fetch for OAuth discovery URLs, which the remote MCP server\n * controls (SSRF mitigation). See ARCHITECTURE.md's \"SSRF mitigation\" section for the threat model.\n */\nimport dns from 'node:dns';\nimport http from 'node:http';\nimport https from 'node:https';\nimport { isIP, type LookupFunction } from 'node:net';\nimport ipaddr from 'ipaddr.js';\n\nexport class DiscoveryFetchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'DiscoveryFetchError';\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_REDIRECTS = 5;\nconst MAX_BODY_BYTES = 1_000_000; // 1 MB - discovery documents are small JSON\n\ntype LookupRecord = { address: string; family: number };\n/** DNS implementation, injectable for deterministic tests. Same contract as `dns.lookup` with `{ all: true, verbatim: true }`. */\ntype Lookup = (hostname: string, options: { all: true; verbatim: true }, callback: (error: NodeJS.ErrnoException | null, addresses: LookupRecord[]) => void) => void;\n\nfunction stripBrackets(hostname: string): string {\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n}\n\n/** True for the literal hostname `localhost` or an IP literal in the loopback range. */\nfunction isLoopbackHost(hostname: string): boolean {\n const host = stripBrackets(hostname).toLowerCase();\n if (host === 'localhost') return true;\n if (isIP(host)) {\n try {\n return ipaddr.process(host).range() === 'loopback';\n } catch {\n return false;\n }\n }\n return false;\n}\n\n/**\n * True if `rawUrl`'s host is loopback, used to decide `allowLoopback` grants\n * from the URL the caller configured, not remote-supplied data. Fails closed on an unparseable URL.\n */\nexport function isLoopbackUrl(rawUrl: string): boolean {\n try {\n return isLoopbackHost(new URL(rawUrl).hostname);\n } catch {\n return false;\n }\n}\n\n/** True when the address is anything other than ordinary public unicast space. */\nfunction isBlockedAddress(address: string): boolean {\n try {\n // ipaddr.process() normalizes IPv4-mapped IPv6 (::ffff:a.b.c.d) to IPv4 first.\n return ipaddr.process(address).range() !== 'unicast';\n } catch {\n return true; // unparseable - fail closed\n }\n}\n\nfunction isLoopbackAddress(address: string): boolean {\n try {\n return ipaddr.process(address).range() === 'loopback';\n } catch {\n return false;\n }\n}\n\n/**\n * Validates scheme and, for literal-IP hosts, address range. `allowLoopback`\n * reflects trust in the calling server, never in `rawUrl` itself.\n */\nfunction assertSafeUrl(rawUrl: string, context: string, allowLoopback: boolean): URL {\n let url: URL;\n try {\n url = new URL(rawUrl);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid URL`);\n }\n\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: unsupported scheme`);\n }\n\n const host = stripBrackets(url.hostname);\n const trustedLoopback = allowLoopback && isLoopbackHost(host);\n if (trustedLoopback) return url; // this call's own grant covers it, regardless of scheme\n\n if (url.protocol === 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: http:// is only allowed for a trusted loopback origin`);\n }\n\n if (isIP(host) && isBlockedAddress(host)) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: address is not publicly routable`);\n }\n\n return url;\n}\n\nfunction lookupAll(hostname: string, lookup: Lookup, timeoutMs: number): Promise<LookupRecord[]> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const deadline = setTimeout(() => {\n if (!settled) {\n settled = true;\n reject(new Error('DNS resolution timed out'));\n }\n }, timeoutMs);\n try {\n lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {\n if (settled) return;\n settled = true;\n clearTimeout(deadline);\n if (error || addresses.length === 0) reject(new Error('DNS resolution failed'));\n else resolve(addresses);\n });\n } catch {\n if (!settled) {\n settled = true;\n clearTimeout(deadline);\n reject(new Error('DNS resolution failed'));\n }\n }\n });\n}\n\n/**\n * Resolves the hostname once, rejects it unless every returned address is\n * acceptable, and returns the validated set. The set is pinned into the\n * request itself (see `requestOnce`), which is what closes the DNS-rebinding\n * TOCTOU: the transport can only dial addresses that were already validated,\n * and it never resolves the hostname a second time.\n */\nasync function resolveSafeAddresses(url: URL, context: string, allowLoopback: boolean, lookup: Lookup, timeoutMs: number): Promise<LookupRecord[]> {\n const host = stripBrackets(url.hostname);\n if (isIP(host)) return [{ address: host, family: host.includes(':') ? 6 : 4 }]; // literal IP already fully checked in assertSafeUrl\n\n // Literal `localhost` under a trusted-loopback grant: still resolved, and the\n // answers must be loopback - the grant covers loopback, not \"wherever\n // localhost happens to point\".\n const loopbackGrant = allowLoopback && isLoopbackHost(host);\n\n let addresses: LookupRecord[];\n try {\n addresses = await lookupAll(host, lookup, timeoutMs);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host could not be resolved`);\n }\n\n if (loopbackGrant) {\n if (!addresses.every((record) => isLoopbackAddress(record.address))) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host does not resolve to a loopback address`);\n }\n } else if (addresses.some((record) => isBlockedAddress(record.address))) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host resolves to an address that is not publicly routable`);\n }\n\n return addresses;\n}\n\n/**\n * A `net` lookup that can only ever answer with `addresses` - the set already\n * validated for this URL. The request is built against the original URL (so\n * SNI and certificate verification still see the hostname), but the\n * connection can only land on a validated address.\n */\nfunction pinnedLookup(addresses: LookupRecord[]): LookupFunction {\n return (_hostname, options, callback) => {\n if (typeof options === 'object' && options.all === true) {\n callback(null, addresses);\n return;\n }\n const first = addresses[0];\n if (!first) {\n callback(Object.assign(new Error('no validated address'), { code: 'ENOTFOUND' }) as NodeJS.ErrnoException, '', 0);\n return;\n }\n callback(null, first.address, first.family);\n };\n}\n\nfunction toRequestHeaders(init: RequestInit): Record<string, string> {\n const headers = new Headers(init.headers);\n const out: Record<string, string> = {};\n for (const [name, value] of headers) out[name] = value;\n return out;\n}\n\nasync function toRequestBody(body: RequestInit['body']): Promise<Buffer | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return Buffer.from(body);\n if (body instanceof URLSearchParams) return Buffer.from(body.toString());\n if (body instanceof Blob) return Buffer.from(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return Buffer.from(body);\n if (ArrayBuffer.isView(body)) return Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n }\n throw new Error('unsupported request body');\n}\n\nfunction toResponse(status: number, statusText: string, headers: http.IncomingHttpHeaders, body: Buffer): Response {\n const responseHeaders = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const entry of value) responseHeaders.append(name, entry);\n } else {\n responseHeaders.append(name, value);\n }\n }\n // The fetch spec gives these statuses a null body, and the Response\n // constructor rejects a body for them.\n const nullBody = status === 204 || status === 205 || status === 304;\n return new Response(nullBody ? null : body, { status, statusText, headers: responseHeaders });\n}\n\nasync function requestOnce(url: URL, init: RequestInit, context: string, addresses: LookupRecord[], timeoutMs: number): Promise<Response> {\n let body: Buffer | undefined;\n try {\n body = await toRequestBody(init.body);\n } catch {\n throw new DiscoveryFetchError(`Failed to fetch ${context}`);\n }\n\n const transport = url.protocol === 'https:' ? https : http;\n const options: http.RequestOptions = { method: (init.method ?? 'GET').toUpperCase(), headers: toRequestHeaders(init), agent: false, lookup: pinnedLookup(addresses) };\n\n return new Promise<Response>((resolve, reject) => {\n let settled = false;\n let req: http.ClientRequest | undefined;\n let res: http.IncomingMessage | undefined;\n const fail = (message: string): void => {\n if (!settled) {\n settled = true;\n clearTimeout(deadline);\n reject(new DiscoveryFetchError(message));\n }\n };\n const deadline = setTimeout(() => {\n res?.destroy();\n req?.destroy();\n fail(`Failed to fetch ${context}`);\n }, timeoutMs);\n\n try {\n req = transport.request(url, options, (response) => {\n res = response;\n const status = response.statusCode;\n const statusText = response.statusMessage ?? '';\n if (status === undefined || status < 200 || status > 599) {\n response.destroy();\n fail(`Failed to fetch ${context}`);\n return;\n }\n const chunks: Buffer[] = [];\n let total = 0;\n response.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > MAX_BODY_BYTES) {\n response.destroy();\n fail(`Refusing to read ${context}: response too large`);\n return;\n }\n chunks.push(chunk);\n });\n response.once('error', () => fail(`Failed to fetch ${context}`));\n response.once('end', () => {\n if (settled) return;\n settled = true;\n clearTimeout(deadline);\n resolve(toResponse(status, statusText, response.headers, Buffer.concat(chunks)));\n });\n });\n } catch {\n fail(`Failed to fetch ${context}`);\n return;\n }\n\n req.once('error', () => fail(`Failed to fetch ${context}`));\n req.end(body);\n });\n}\n\nasync function fetchOnce(url: URL, init: RequestInit, context: string, allowLoopback: boolean, timeoutMs: number, lookup: Lookup): Promise<Response> {\n const addresses = await resolveSafeAddresses(url, context, allowLoopback, lookup, timeoutMs);\n return requestOnce(url, init, context, addresses, timeoutMs);\n}\n\nexport interface DiscoveryFetchOptions {\n /**\n * Loopback trust grant for this fetch, computed from the server the caller\n * is actually talking to - never from the URL being fetched. Defaults to `false`.\n */\n allowLoopback?: boolean;\n /**\n * Per-hop timeout in ms, applied to both the DNS resolution and the request.\n * Defaults to `DEFAULT_TIMEOUT_MS`; overridable so tests can bound slow-failure cases.\n */\n timeoutMs?: number;\n /**\n * DNS implementation used for the pre-request resolution, injectable for\n * deterministic tests. Defaults to `dns.lookup`.\n */\n lookup?: Lookup;\n}\n\n/**\n * Fetches an OAuth-discovery URL with SSRF mitigations applied to the\n * initial URL and every redirect hop; redirects are validated, not auto-followed.\n *\n * The hostname is resolved once, every returned address is validated, and the\n * validated set is pinned into the request through a custom `lookup`, so the\n * request cannot resolve the hostname a second time and cannot be steered to\n * a different address by a DNS-rebinding answer.\n *\n * @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).\n * @param init - Standard fetch options; `redirect` is always forced to `'manual'`.\n * @param context - Short label used only in error messages, never echoing the URL.\n * @param options - See `DiscoveryFetchOptions`.\n */\nexport async function discoveryFetch(rawUrl: string, init: RequestInit = {}, context = 'discovery URL', options: DiscoveryFetchOptions = {}): Promise<Response> {\n const { allowLoopback = false, timeoutMs = DEFAULT_TIMEOUT_MS, lookup = dns.lookup as unknown as Lookup } = options;\n\n let url = assertSafeUrl(rawUrl, context, allowLoopback);\n let response = await fetchOnce(url, init, context, allowLoopback, timeoutMs, lookup);\n\n let redirectsLeft = MAX_REDIRECTS;\n while (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n if (!location) break;\n if (redirectsLeft <= 0) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: too many redirects`);\n }\n redirectsLeft -= 1;\n\n let nextUrl: URL;\n try {\n nextUrl = new URL(location, url);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid redirect target`);\n }\n url = assertSafeUrl(nextUrl.toString(), context, allowLoopback);\n response = await fetchOnce(url, init, context, allowLoopback, timeoutMs, lookup);\n }\n\n return response;\n}\n\n/**\n * Parse a `discoveryFetch` response body as JSON, enforcing `MAX_BODY_BYTES`\n * while reading (not after buffering the whole thing).\n */\nexport async function readDiscoveryJson<T>(response: Response, context: string): Promise<T> {\n const text = await readLimited(response, context, MAX_BODY_BYTES);\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new DiscoveryFetchError(`Refusing to parse ${context}: invalid JSON`);\n }\n}\n\nasync function readLimited(response: Response, context: string, maxBytes: number): Promise<string> {\n const contentLength = response.headers.get('content-length');\n if (contentLength && Number(contentLength) > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n const text = await response.text();\n if (Buffer.byteLength(text, 'utf8') > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n return text;\n }\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString('utf8');\n}\n"],"names":["DiscoveryFetchError","discoveryFetch","isLoopbackUrl","readDiscoveryJson","message","name","Error","DEFAULT_TIMEOUT_MS","MAX_REDIRECTS","MAX_BODY_BYTES","stripBrackets","hostname","startsWith","endsWith","slice","isLoopbackHost","host","toLowerCase","isIP","ipaddr","process","range","rawUrl","URL","isBlockedAddress","address","isLoopbackAddress","assertSafeUrl","context","allowLoopback","url","protocol","trustedLoopback","lookupAll","lookup","timeoutMs","Promise","resolve","reject","settled","deadline","setTimeout","all","verbatim","error","addresses","clearTimeout","length","resolveSafeAddresses","loopbackGrant","family","includes","every","record","some","pinnedLookup","_hostname","options","callback","first","Object","assign","code","toRequestHeaders","init","headers","Headers","out","value","toRequestBody","body","reader","chunks","done","undefined","Buffer","from","URLSearchParams","toString","Blob","arrayBuffer","ArrayBuffer","isView","buffer","byteOffset","byteLength","ReadableStream","getReader","read","push","releaseLock","concat","map","chunk","toResponse","status","statusText","responseHeaders","entries","Array","isArray","entry","append","nullBody","Response","requestOnce","transport","https","http","method","toUpperCase","agent","req","res","fail","destroy","request","response","statusCode","statusMessage","total","on","once","end","fetchOnce","redirectsLeft","location","nextUrl","dns","get","text","readLimited","JSON","parse","maxBytes","contentLength","Number"],"mappings":"AAAA;;;CAGC;;;;;;;;;;;QAOYA;eAAAA;;QAuUSC;eAAAA;;QAlSNC;eAAAA;;QAkUMC;eAAAA;;;8DA7WN;+DACC;gEACC;uBACwB;6DACvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEZ,IAAA,AAAMH,oCAAN;;cAAMA;aAAAA,oBACCI,OAAe;gCADhBJ;;gBAET,kBAFSA;YAEHI;;QACN,MAAKC,IAAI,GAAG;;;WAHHL;qBAA4BM;AAOzC,IAAMC,qBAAqB;AAC3B,IAAMC,gBAAgB;AACtB,IAAMC,iBAAiB,SAAW,4CAA4C;AAM9E,SAASC,cAAcC,QAAgB;IACrC,OAAOA,SAASC,UAAU,CAAC,QAAQD,SAASE,QAAQ,CAAC,OAAOF,SAASG,KAAK,CAAC,GAAG,CAAC,KAAKH;AACtF;AAEA,sFAAsF,GACtF,SAASI,eAAeJ,QAAgB;IACtC,IAAMK,OAAON,cAAcC,UAAUM,WAAW;IAChD,IAAID,SAAS,aAAa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AAI,CAACrB;;;;;;;;;;;;;oBAGdG,OAAOmB,WAAW;;;;;oBAGpB;;wBAAOf,OAAOgB,MAAM,CAACnB,OAAOoB,GAAG,CAAC,SAACC;mCAAUlB,OAAOC,IAAI,CAACiB;4BAASf,QAAQ,CAAC;;;;IAC3E"}
@@ -4,6 +4,7 @@
4
4
  * Helper to connect MCP SDK clients to servers with intelligent transport inference.
5
5
  * Automatically detects transport type from URL protocol or type field.
6
6
  */
7
+ import type { VersionNegotiationOptions } from '@modelcontextprotocol/client';
7
8
  import { Client } from '@modelcontextprotocol/client';
8
9
  import { type DcrAuthenticatorOptions } from '../dcr/index.js';
9
10
  import type { ServerProcess } from '../spawn/spawn-server.js';
@@ -32,6 +33,15 @@ import { type Logger } from '../utils/logger.js';
32
33
  *
33
34
  * @param registryOrConfig - Result from createServerRegistry() or servers config object
34
35
  * @param serverName - Server name from servers config
36
+ * @param options - Connection options (see below)
37
+ * @param options.dcrAuthenticator - DCR authenticator options
38
+ * @param options.logger - Logger for connection diagnostics
39
+ * @param options.versionNegotiation - SDK protocol version negotiation (protocol revision
40
+ * 2026-07-28 and later). Omitted by default, which keeps the SDK's `'legacy'` mode:
41
+ * the plain 2025 connect sequence. Pass `{ mode: 'auto' }` to probe the server and
42
+ * fall back to 2025 when it cannot serve the modern era, or `{ mode: { pin: '2026-07-28' } }`
43
+ * to require the pinned revision (a server that cannot serve it fails the connect with
44
+ * a typed era-negotiation error).
35
45
  * @returns Connected MCP SDK Client (guaranteed ready)
36
46
  *
37
47
  * @example
@@ -54,5 +64,6 @@ import { type Logger } from '../utils/logger.js';
54
64
  export declare function connectMcpClient(registryOrConfig: RegistryLike | ServersConfig, serverName: string, options?: {
55
65
  dcrAuthenticator?: Partial<DcrAuthenticatorOptions>;
56
66
  logger?: Logger;
67
+ versionNegotiation?: VersionNegotiationOptions;
57
68
  }): Promise<Client>;
58
69
  export {};
@@ -4,6 +4,7 @@
4
4
  * Helper to connect MCP SDK clients to servers with intelligent transport inference.
5
5
  * Automatically detects transport type from URL protocol or type field.
6
6
  */
7
+ import type { VersionNegotiationOptions } from '@modelcontextprotocol/client';
7
8
  import { Client } from '@modelcontextprotocol/client';
8
9
  import { type DcrAuthenticatorOptions } from '../dcr/index.js';
9
10
  import type { ServerProcess } from '../spawn/spawn-server.js';
@@ -32,6 +33,15 @@ import { type Logger } from '../utils/logger.js';
32
33
  *
33
34
  * @param registryOrConfig - Result from createServerRegistry() or servers config object
34
35
  * @param serverName - Server name from servers config
36
+ * @param options - Connection options (see below)
37
+ * @param options.dcrAuthenticator - DCR authenticator options
38
+ * @param options.logger - Logger for connection diagnostics
39
+ * @param options.versionNegotiation - SDK protocol version negotiation (protocol revision
40
+ * 2026-07-28 and later). Omitted by default, which keeps the SDK's `'legacy'` mode:
41
+ * the plain 2025 connect sequence. Pass `{ mode: 'auto' }` to probe the server and
42
+ * fall back to 2025 when it cannot serve the modern era, or `{ mode: { pin: '2026-07-28' } }`
43
+ * to require the pinned revision (a server that cannot serve it fails the connect with
44
+ * a typed era-negotiation error).
35
45
  * @returns Connected MCP SDK Client (guaranteed ready)
36
46
  *
37
47
  * @example
@@ -54,5 +64,6 @@ import { type Logger } from '../utils/logger.js';
54
64
  export declare function connectMcpClient(registryOrConfig: RegistryLike | ServersConfig, serverName: string, options?: {
55
65
  dcrAuthenticator?: Partial<DcrAuthenticatorOptions>;
56
66
  logger?: Logger;
67
+ versionNegotiation?: VersionNegotiationOptions;
57
68
  }): Promise<Client>;
58
69
  export {};
@@ -253,7 +253,7 @@ function _ts_generator(thisArg, body) {
253
253
  }
254
254
  function connectMcpClient(registryOrConfig, serverName, options) {
255
255
  return _async_to_generator(function() {
256
- var _ref, isRegistry, serversConfig, registry, logger, serverConfig, available, transportType, client, serverHandle, transport, transport1, isSpawnedHttp, url, mcpServerUrl, capabilities, authToken, port, redirectUri, authenticator, tokens, staticHeaders, dcrHeaders, mergedHeaders, transportOptions, transport2, error, errorMessage, cause, isConnectionRefused, shouldFallback, sseClient, staticHeaders1, dcrHeaders1, mergedHeaders1, sseTransportOptions, sseTransport, sseError;
256
+ var _ref, isRegistry, serversConfig, registry, logger, serverConfig, available, transportType, clientOptions, client, serverHandle, transport, transport1, isSpawnedHttp, url, mcpServerUrl, capabilities, authToken, port, redirectUri, authenticator, tokens, staticHeaders, dcrHeaders, mergedHeaders, transportOptions, transport2, error, errorMessage, cause, isConnectionRefused, shouldFallback, sseClient, staticHeaders1, dcrHeaders1, mergedHeaders1, sseTransportOptions, sseTransport, sseError;
257
257
  return _ts_generator(this, function(_state) {
258
258
  switch(_state.label){
259
259
  case 0:
@@ -269,13 +269,20 @@ function connectMcpClient(registryOrConfig, serverName, options) {
269
269
  }
270
270
  // Infer transport type with validation
271
271
  transportType = inferTransportType(serverConfig);
272
+ // SDK client options for both transports (main + SSE fallback). versionNegotiation is
273
+ // omitted rather than set to undefined so the default stays the SDK's 'legacy' mode —
274
+ // the plain 2025 connect sequence — for callers that do not pass it.
275
+ clientOptions = {
276
+ capabilities: {}
277
+ };
278
+ if ((options === null || options === void 0 ? void 0 : options.versionNegotiation) !== undefined) {
279
+ clientOptions.versionNegotiation = options.versionNegotiation;
280
+ }
272
281
  // Create MCP client
273
282
  client = new _client.Client({
274
283
  name: 'mcp-cli-client',
275
284
  version: '1.0.0'
276
- }, {
277
- capabilities: {}
278
- });
285
+ }, clientOptions);
279
286
  if (!(transportType === 'stdio')) return [
280
287
  3,
281
288
  5
@@ -462,9 +469,7 @@ function connectMcpClient(registryOrConfig, serverName, options) {
462
469
  sseClient = new _client.Client({
463
470
  name: 'mcp-cli-client',
464
471
  version: '1.0.0'
465
- }, {
466
- capabilities: {}
467
- });
472
+ }, clientOptions);
468
473
  // SSE transport with merged headers (static + DCR auth)
469
474
  // Reuse the same header merging logic as Streamable HTTP
470
475
  staticHeaders1 = serverConfig.headers || {};
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/connection/connect-client.ts"],"sourcesContent":["/**\n * connect-mcp-client.ts\n *\n * Helper to connect MCP SDK clients to servers with intelligent transport inference.\n * Automatically detects transport type from URL protocol or type field.\n */\n\nimport type { Transport } from '@modelcontextprotocol/client';\nimport { Client, SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';\nimport { StdioClientTransport } from '@modelcontextprotocol/client/stdio';\nimport getPort from 'get-port';\nimport { probeAuthCapabilities } from '../auth/index.ts';\nimport { DCR_CAPABILTY_DISCOVERY_TIMEOUT } from '../constants.ts';\nimport { DcrAuthenticator, type DcrAuthenticatorOptions } from '../dcr/index.ts';\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport type { ServerProcess } from '../spawn/spawn-server.ts';\nimport type { ServersConfig } from '../spawn/spawn-servers.ts';\n\n/**\n * Minimal interface for connecting to servers.\n * Only needs config and servers map for connection logic.\n */\ninterface RegistryLike {\n config: ServersConfig;\n servers: Map<string, ServerProcess>;\n}\n\nimport type { McpServerEntry, TransportType } from '../types.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { ExistingProcessTransport } from './existing-process-transport.ts';\nimport { waitForHttpReady } from './wait-for-http-ready.ts';\n\n/**\n * Wrap promise with timeout - throws if promise takes too long\n * Clears timeout when promise completes to prevent hanging event loop\n * @param promise - Promise to wrap\n * @param ms - Timeout in milliseconds\n * @param operation - Description of operation for error message\n * @returns Promise result or timeout error\n */\nasync function withTimeout<T>(promise: Promise<T>, ms: number, operation: string): Promise<T> {\n let timeoutId: NodeJS.Timeout;\n\n return Promise.race([\n promise.finally(() => clearTimeout(timeoutId)),\n new Promise<T>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(`Timeout after ${ms}ms: ${operation}`)), ms);\n }),\n ]);\n}\n\n/**\n * Infer transport type from server configuration with validation.\n *\n * Priority:\n * 1. Explicit type field (if present)\n * 2. URL protocol (if URL present): http://, https://\n * 3. Default to 'stdio' (if neither present)\n *\n * @param config - Server configuration\n * @returns Transport type\n * @throws Error if configuration is invalid or has conflicts\n */\nfunction inferTransportType(config: McpServerEntry): TransportType {\n // Priority 1: Explicit type field\n if (config.type) {\n // Validate consistency with URL if both present\n if (config.url) {\n const url = new URL(config.url);\n const protocol = url.protocol;\n\n if ((protocol === 'http:' || protocol === 'https:') && config.type !== 'http' && config.type !== 'sse-ide') {\n throw new Error(`Conflicting transport: URL protocol '${protocol}' requires type 'http', but got '${config.type}'`);\n }\n }\n\n // Return normalized type\n if (config.type === 'http' || config.type === 'sse-ide') return 'http';\n if (config.type === 'stdio') return 'stdio';\n\n throw new Error(`Unsupported transport type: ${config.type}`);\n }\n\n // Priority 2: Infer from URL protocol\n if (config.url) {\n const url = new URL(config.url);\n const protocol = url.protocol;\n\n if (protocol === 'http:' || protocol === 'https:') {\n return 'http';\n }\n throw new Error(`Unsupported URL protocol: ${protocol}`);\n }\n\n // Priority 3: Default to stdio\n return 'stdio';\n}\n\n/**\n * Connect MCP SDK client to server with full readiness handling.\n * @internal - Use registry.connect() instead\n *\n * **Completely handles readiness**: transport availability + MCP protocol handshake.\n *\n * Transport is intelligently inferred and handled:\n * - **Stdio servers**: Direct MCP connect (fast for spawned processes)\n * - **HTTP servers**: Transport polling (/mcp endpoint) + MCP connect\n * - **Registry result**: Handles both spawned and external servers\n *\n * Returns only when server is fully MCP-ready (initialize handshake complete).\n *\n * @param registryOrConfig - Result from createServerRegistry() or servers config object\n * @param serverName - Server name from servers config\n * @returns Connected MCP SDK Client (guaranteed ready)\n *\n * @example\n * // Using registry (recommended)\n * const registry = createServerRegistry({ echo: { command: 'node', args: ['server.ts'] } });\n * const client = await registry.connect('echo');\n * // Server is fully ready - transport available + MCP handshake complete\n *\n * @example\n * // HTTP server readiness (waits for /mcp polling + MCP handshake)\n * const registry = createServerRegistry(\n * { http: { type: 'http', url: 'http://localhost:3000/mcp', start: {...} } },\n * { dialects: ['start'] }\n * );\n * const client = await registry.connect('http');\n * // 1. Waits for HTTP server to respond on /mcp\n * // 2. Performs MCP initialize handshake\n * // 3. Returns ready client\n */\nexport async function connectMcpClient(\n registryOrConfig: RegistryLike | ServersConfig,\n serverName: string,\n options?: {\n dcrAuthenticator?: Partial<DcrAuthenticatorOptions>;\n logger?: Logger;\n }\n): Promise<Client> {\n // Detect whether we have a RegistryLike instance or just config\n const isRegistry = 'servers' in registryOrConfig && registryOrConfig.servers instanceof Map;\n const serversConfig: ServersConfig = isRegistry ? (registryOrConfig as RegistryLike).config : (registryOrConfig as ServersConfig);\n const registry = isRegistry ? (registryOrConfig as RegistryLike) : undefined;\n const logger = options?.logger ?? defaultLogger;\n\n const serverConfig = serversConfig[serverName];\n\n if (!serverConfig) {\n const available = Object.keys(serversConfig).join(', ');\n throw new Error(`Server '${serverName}' not found in config. Available servers: ${available || 'none'}`);\n }\n\n // Infer transport type with validation\n const transportType = inferTransportType(serverConfig);\n\n // Create MCP client\n const client = new Client({ name: 'mcp-cli-client', version: '1.0.0' }, { capabilities: {} });\n\n // Connect based on inferred transport\n if (transportType === 'stdio') {\n // Check if we have a spawned process in the registry\n const serverHandle = registry?.servers.get(serverName);\n\n if (serverHandle) {\n // Reuse the already-spawned process\n const transport = new ExistingProcessTransport(serverHandle.process);\n await client.connect(transport);\n } else {\n // No registry or server not in registry - spawn new process directly\n // This is the standard fallback when process management is not used\n if (!serverConfig.command) {\n throw new Error(`Server '${serverName}' has stdio transport but missing 'command' field`);\n }\n\n const transport = new StdioClientTransport({\n command: serverConfig.command,\n args: serverConfig.args || [],\n env: serverConfig.env || {},\n });\n\n // client.connect() performs initialize handshake - when it resolves, server is ready\n await client.connect(transport);\n }\n } else if (transportType === 'http') {\n if (!('url' in serverConfig) || !serverConfig.url) {\n throw new Error(`Server '${serverName}' has http transport but missing 'url' field`);\n }\n\n // Check if this is a freshly spawned HTTP server (from registry)\n // that might not be ready yet - transport readiness check needed\n const isSpawnedHttp = registry?.servers.has(serverName);\n\n if (isSpawnedHttp) {\n logger.debug(`[connectMcpClient] waiting for HTTP server '${serverName}' at ${serverConfig.url}`);\n await waitForHttpReady(serverConfig.url);\n logger.debug(`[connectMcpClient] HTTP server '${serverName}' ready`);\n }\n\n const url = new URL(serverConfig.url);\n\n // Check for DCR support and handle authentication automatically\n // The canonical MCP server URI, path segment and all. Both calls below need\n // the server's identity, not its deployment root: discovery uses the path to\n // find resource-specific metadata (RFC 9728 sub-path), and the authenticator\n // audience-binds tokens to it (RFC 8707). Handing either the `/mcp`-stripped\n // base names a different resource, which authorization servers that validate\n // the `resource` indicator reject as `invalid_target`.\n const mcpServerUrl = normalizeUrl(serverConfig.url);\n const capabilities = await withTimeout(probeAuthCapabilities(mcpServerUrl), DCR_CAPABILTY_DISCOVERY_TIMEOUT, 'DCR capability discovery');\n\n let authToken: string | undefined;\n\n if (capabilities.supportsDcr) {\n logger.debug(`🔐 Server '${serverName}' supports DCR authentication`);\n\n // Get available port and create the exact redirect URI to use\n const port = await getPort();\n const redirectUri = `http://localhost:${port}/callback`;\n\n // Handle authentication using DcrAuthenticator with fully resolved redirectUri\n const authenticator = new DcrAuthenticator({\n headless: false,\n redirectUri,\n logger,\n ...options?.dcrAuthenticator,\n });\n\n // Ensure we have valid tokens (performs DCR + OAuth if needed)\n const tokens = await authenticator.ensureAuthenticated(mcpServerUrl, capabilities);\n authToken = tokens.accessToken;\n\n logger.debug(`✅ Authentication complete for '${serverName}'`);\n } else {\n logger.debug(`ℹ️ Server '${serverName}' does not support DCR - connecting without authentication`);\n }\n\n try {\n // Try modern Streamable HTTP first (protocol version 2025-03-26)\n // Merge static headers from config with DCR auth headers (DCR Authorization takes precedence)\n const staticHeaders = serverConfig.headers || {};\n const dcrHeaders = authToken ? { Authorization: `Bearer ${authToken}` } : {};\n const mergedHeaders = { ...staticHeaders, ...dcrHeaders };\n\n const transportOptions =\n Object.keys(mergedHeaders).length > 0\n ? {\n requestInit: {\n headers: mergedHeaders,\n },\n }\n : undefined;\n\n const transport = new StreamableHTTPClientTransport(url, transportOptions);\n // Type assertion: SDK transport has sessionId: string | undefined but Transport expects string\n // This is safe at runtime - the undefined is valid per MCP spec\n await withTimeout(client.connect(transport as unknown as Transport), 30000, 'StreamableHTTP connection');\n } catch (error) {\n // Fall back to SSE transport (MCP protocol version 2024-11-05)\n // SSE is a standard MCP transport used by many servers (e.g., FastMCP ecosystem)\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n // Fast-fail: Don't try SSE if connection was refused (server not running)\n // Check error.cause.code for ECONNREFUSED (fetch errors wrap the actual error in cause)\n const cause = error instanceof Error ? (error as Error & { cause?: { code?: string } }).cause : undefined;\n const isConnectionRefused = cause?.code === 'ECONNREFUSED' || errorMessage.includes('Connection refused');\n\n if (isConnectionRefused) {\n // Clean up client resources before throwing\n await client.close().catch(() => {});\n throw new Error(`Server not running at ${url}`);\n }\n\n // Check for known errors that indicate SSE fallback is needed\n const shouldFallback =\n errorMessage.includes('Missing session ID') || // FastMCP specific\n errorMessage.includes('404') || // Server doesn't have streamable HTTP endpoint\n errorMessage.includes('405'); // Method not allowed\n\n if (shouldFallback) {\n logger.warn(`Streamable HTTP failed (${errorMessage}), falling back to SSE transport`);\n } else {\n logger.warn('Streamable HTTP connection failed, trying SSE transport as fallback');\n }\n\n // Create new client for SSE transport (required per SDK pattern)\n const sseClient = new Client({ name: 'mcp-cli-client', version: '1.0.0' }, { capabilities: {} });\n\n // SSE transport with merged headers (static + DCR auth)\n // Reuse the same header merging logic as Streamable HTTP\n const staticHeaders = serverConfig.headers || {};\n const dcrHeaders = authToken ? { Authorization: `Bearer ${authToken}` } : {};\n const mergedHeaders = { ...staticHeaders, ...dcrHeaders };\n\n const sseTransportOptions =\n Object.keys(mergedHeaders).length > 0\n ? {\n requestInit: {\n headers: mergedHeaders,\n },\n }\n : undefined;\n\n const sseTransport = new SSEClientTransport(url, sseTransportOptions);\n\n try {\n await withTimeout(sseClient.connect(sseTransport), 30000, 'SSE connection');\n // Return SSE client instead of original\n return sseClient;\n } catch (sseError) {\n // SSE connection failed - clean up both clients before throwing\n await Promise.all([client.close().catch(() => {}), sseClient.close().catch(() => {})]);\n throw sseError;\n }\n }\n }\n\n return client; // Guaranteed ready when returned\n}\n"],"names":["connectMcpClient","withTimeout","promise","ms","operation","timeoutId","Promise","race","finally","clearTimeout","_","reject","setTimeout","Error","inferTransportType","config","type","url","URL","protocol","registryOrConfig","serverName","options","isRegistry","serversConfig","registry","logger","serverConfig","available","transportType","client","serverHandle","transport","isSpawnedHttp","mcpServerUrl","capabilities","authToken","port","redirectUri","authenticator","tokens","staticHeaders","dcrHeaders","mergedHeaders","transportOptions","error","errorMessage","cause","isConnectionRefused","shouldFallback","sseClient","sseTransportOptions","sseTransport","sseError","servers","Map","undefined","defaultLogger","Object","keys","join","Client","name","version","get","ExistingProcessTransport","process","connect","command","StdioClientTransport","args","env","has","debug","waitForHttpReady","normalizeUrl","probeAuthCapabilities","DCR_CAPABILTY_DISCOVERY_TIMEOUT","supportsDcr","getPort","DcrAuthenticator","headless","dcrAuthenticator","ensureAuthenticated","accessToken","headers","Authorization","length","requestInit","StreamableHTTPClientTransport","message","String","code","includes","close","catch","warn","SSEClientTransport","all"],"mappings":"AAAA;;;;;CAKC;;;;+BA+HqBA;;;eAAAA;;;sBA5HoD;qBACrC;8DACjB;uBACkB;2BACU;wBACe;0BAClC;wBAcwB;0CACZ;kCACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEjC;;;;;;;CAOC,GACD,SAAeC,YAAeC,OAAmB,EAAEC,EAAU,EAAEC,SAAiB;;YAC1EC;;YAEJ;;gBAAOC,QAAQC,IAAI;oBACjBL,QAAQM,OAAO,CAAC;+BAAMC,aAAaJ;;oBACnC,IAAIC,QAAW,SAACI,GAAGC;wBACjBN,YAAYO,WAAW;mCAAMD,OAAO,IAAIE,MAAM,AAAC,iBAAy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+C,QAAQ,CAAC,UAAU,+CAA+C;oBAC/E/C,aAAa+C,QAAQ,CAAC,QAAQ,qBAAqB;oBAErD,IAAI5C,gBAAgB;wBAClBvB,OAAOsE,IAAI,CAAC,AAAC,2BAAuC,OAAblD,cAAa;oBACtD,OAAO;wBACLpB,OAAOsE,IAAI,CAAC;oBACd;oBAEA,iEAAiE;oBAC3D9C,YAAY,IAAIW,cAAM,CAAC;wBAAEC,MAAM;wBAAkBC,SAAS;oBAAQ,GAAG;wBAAE5B,cAAc,CAAC;oBAAE;oBAE9F,wDAAwD;oBACxD,yDAAyD;oBACnDM,iBAAgBd,aAAa0D,OAAO,IAAI,CAAC;oBACzC3C,cAAaN,YAAY;wBAAEkD,eAAe,AAAC,UAAmB,OAAVlD;oBAAY,IAAI,CAAC;oBACrEO,iBAAgB,mBAAKF,gBAAkBC;oBAEvCS,sBACJO,OAAOC,IAAI,CAAChB,gBAAe4C,MAAM,GAAG,IAChC;wBACEC,aAAa;4BACXH,SAAS1C;wBACX;oBACF,IACAa;oBAEAJ,eAAe,IAAI6C,0BAAkB,CAAChF,KAAKkC;;;;;;;;;oBAG/C;;wBAAMlD,YAAYiD,UAAUiB,OAAO,CAACf,eAAe,OAAO;;;oBAA1D;oBACA,wCAAwC;oBACxC;;wBAAOF;;;oBACAG;oBACP,gEAAgE;oBAChE;;wBAAM/C,QAAQ4F,GAAG;4BAAEpE,OAAOgE,KAAK,GAAGC,KAAK,CAAC,YAAO;4BAAI7C,UAAU4C,KAAK,GAAGC,KAAK,CAAC,YAAO;;;;oBAAlF;oBACA,MAAM1C;;;;;;;oBAKZ;;wBAAOvB;uBAAQ,iCAAiC;;;IAClD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/connection/connect-client.ts"],"sourcesContent":["/**\n * connect-mcp-client.ts\n *\n * Helper to connect MCP SDK clients to servers with intelligent transport inference.\n * Automatically detects transport type from URL protocol or type field.\n */\n\nimport type { ClientOptions, Transport, VersionNegotiationOptions } from '@modelcontextprotocol/client';\nimport { Client, SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';\nimport { StdioClientTransport } from '@modelcontextprotocol/client/stdio';\nimport getPort from 'get-port';\nimport { probeAuthCapabilities } from '../auth/index.ts';\nimport { DCR_CAPABILTY_DISCOVERY_TIMEOUT } from '../constants.ts';\nimport { DcrAuthenticator, type DcrAuthenticatorOptions } from '../dcr/index.ts';\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport type { ServerProcess } from '../spawn/spawn-server.ts';\nimport type { ServersConfig } from '../spawn/spawn-servers.ts';\n\n/**\n * Minimal interface for connecting to servers.\n * Only needs config and servers map for connection logic.\n */\ninterface RegistryLike {\n config: ServersConfig;\n servers: Map<string, ServerProcess>;\n}\n\nimport type { McpServerEntry, TransportType } from '../types.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { ExistingProcessTransport } from './existing-process-transport.ts';\nimport { waitForHttpReady } from './wait-for-http-ready.ts';\n\n/**\n * Wrap promise with timeout - throws if promise takes too long\n * Clears timeout when promise completes to prevent hanging event loop\n * @param promise - Promise to wrap\n * @param ms - Timeout in milliseconds\n * @param operation - Description of operation for error message\n * @returns Promise result or timeout error\n */\nasync function withTimeout<T>(promise: Promise<T>, ms: number, operation: string): Promise<T> {\n let timeoutId: NodeJS.Timeout;\n\n return Promise.race([\n promise.finally(() => clearTimeout(timeoutId)),\n new Promise<T>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(`Timeout after ${ms}ms: ${operation}`)), ms);\n }),\n ]);\n}\n\n/**\n * Infer transport type from server configuration with validation.\n *\n * Priority:\n * 1. Explicit type field (if present)\n * 2. URL protocol (if URL present): http://, https://\n * 3. Default to 'stdio' (if neither present)\n *\n * @param config - Server configuration\n * @returns Transport type\n * @throws Error if configuration is invalid or has conflicts\n */\nfunction inferTransportType(config: McpServerEntry): TransportType {\n // Priority 1: Explicit type field\n if (config.type) {\n // Validate consistency with URL if both present\n if (config.url) {\n const url = new URL(config.url);\n const protocol = url.protocol;\n\n if ((protocol === 'http:' || protocol === 'https:') && config.type !== 'http' && config.type !== 'sse-ide') {\n throw new Error(`Conflicting transport: URL protocol '${protocol}' requires type 'http', but got '${config.type}'`);\n }\n }\n\n // Return normalized type\n if (config.type === 'http' || config.type === 'sse-ide') return 'http';\n if (config.type === 'stdio') return 'stdio';\n\n throw new Error(`Unsupported transport type: ${config.type}`);\n }\n\n // Priority 2: Infer from URL protocol\n if (config.url) {\n const url = new URL(config.url);\n const protocol = url.protocol;\n\n if (protocol === 'http:' || protocol === 'https:') {\n return 'http';\n }\n throw new Error(`Unsupported URL protocol: ${protocol}`);\n }\n\n // Priority 3: Default to stdio\n return 'stdio';\n}\n\n/**\n * Connect MCP SDK client to server with full readiness handling.\n * @internal - Use registry.connect() instead\n *\n * **Completely handles readiness**: transport availability + MCP protocol handshake.\n *\n * Transport is intelligently inferred and handled:\n * - **Stdio servers**: Direct MCP connect (fast for spawned processes)\n * - **HTTP servers**: Transport polling (/mcp endpoint) + MCP connect\n * - **Registry result**: Handles both spawned and external servers\n *\n * Returns only when server is fully MCP-ready (initialize handshake complete).\n *\n * @param registryOrConfig - Result from createServerRegistry() or servers config object\n * @param serverName - Server name from servers config\n * @param options - Connection options (see below)\n * @param options.dcrAuthenticator - DCR authenticator options\n * @param options.logger - Logger for connection diagnostics\n * @param options.versionNegotiation - SDK protocol version negotiation (protocol revision\n * 2026-07-28 and later). Omitted by default, which keeps the SDK's `'legacy'` mode:\n * the plain 2025 connect sequence. Pass `{ mode: 'auto' }` to probe the server and\n * fall back to 2025 when it cannot serve the modern era, or `{ mode: { pin: '2026-07-28' } }`\n * to require the pinned revision (a server that cannot serve it fails the connect with\n * a typed era-negotiation error).\n * @returns Connected MCP SDK Client (guaranteed ready)\n *\n * @example\n * // Using registry (recommended)\n * const registry = createServerRegistry({ echo: { command: 'node', args: ['server.ts'] } });\n * const client = await registry.connect('echo');\n * // Server is fully ready - transport available + MCP handshake complete\n *\n * @example\n * // HTTP server readiness (waits for /mcp polling + MCP handshake)\n * const registry = createServerRegistry(\n * { http: { type: 'http', url: 'http://localhost:3000/mcp', start: {...} } },\n * { dialects: ['start'] }\n * );\n * const client = await registry.connect('http');\n * // 1. Waits for HTTP server to respond on /mcp\n * // 2. Performs MCP initialize handshake\n * // 3. Returns ready client\n */\nexport async function connectMcpClient(\n registryOrConfig: RegistryLike | ServersConfig,\n serverName: string,\n options?: {\n dcrAuthenticator?: Partial<DcrAuthenticatorOptions>;\n logger?: Logger;\n versionNegotiation?: VersionNegotiationOptions;\n }\n): Promise<Client> {\n // Detect whether we have a RegistryLike instance or just config\n const isRegistry = 'servers' in registryOrConfig && registryOrConfig.servers instanceof Map;\n const serversConfig: ServersConfig = isRegistry ? (registryOrConfig as RegistryLike).config : (registryOrConfig as ServersConfig);\n const registry = isRegistry ? (registryOrConfig as RegistryLike) : undefined;\n const logger = options?.logger ?? defaultLogger;\n\n const serverConfig = serversConfig[serverName];\n\n if (!serverConfig) {\n const available = Object.keys(serversConfig).join(', ');\n throw new Error(`Server '${serverName}' not found in config. Available servers: ${available || 'none'}`);\n }\n\n // Infer transport type with validation\n const transportType = inferTransportType(serverConfig);\n\n // SDK client options for both transports (main + SSE fallback). versionNegotiation is\n // omitted rather than set to undefined so the default stays the SDK's 'legacy' mode —\n // the plain 2025 connect sequence — for callers that do not pass it.\n const clientOptions: ClientOptions = { capabilities: {} };\n if (options?.versionNegotiation !== undefined) {\n clientOptions.versionNegotiation = options.versionNegotiation;\n }\n\n // Create MCP client\n const client = new Client({ name: 'mcp-cli-client', version: '1.0.0' }, clientOptions);\n\n // Connect based on inferred transport\n if (transportType === 'stdio') {\n // Check if we have a spawned process in the registry\n const serverHandle = registry?.servers.get(serverName);\n\n if (serverHandle) {\n // Reuse the already-spawned process\n const transport = new ExistingProcessTransport(serverHandle.process);\n await client.connect(transport);\n } else {\n // No registry or server not in registry - spawn new process directly\n // This is the standard fallback when process management is not used\n if (!serverConfig.command) {\n throw new Error(`Server '${serverName}' has stdio transport but missing 'command' field`);\n }\n\n const transport = new StdioClientTransport({\n command: serverConfig.command,\n args: serverConfig.args || [],\n env: serverConfig.env || {},\n });\n\n // client.connect() performs initialize handshake - when it resolves, server is ready\n await client.connect(transport);\n }\n } else if (transportType === 'http') {\n if (!('url' in serverConfig) || !serverConfig.url) {\n throw new Error(`Server '${serverName}' has http transport but missing 'url' field`);\n }\n\n // Check if this is a freshly spawned HTTP server (from registry)\n // that might not be ready yet - transport readiness check needed\n const isSpawnedHttp = registry?.servers.has(serverName);\n\n if (isSpawnedHttp) {\n logger.debug(`[connectMcpClient] waiting for HTTP server '${serverName}' at ${serverConfig.url}`);\n await waitForHttpReady(serverConfig.url);\n logger.debug(`[connectMcpClient] HTTP server '${serverName}' ready`);\n }\n\n const url = new URL(serverConfig.url);\n\n // Check for DCR support and handle authentication automatically\n // The canonical MCP server URI, path segment and all. Both calls below need\n // the server's identity, not its deployment root: discovery uses the path to\n // find resource-specific metadata (RFC 9728 sub-path), and the authenticator\n // audience-binds tokens to it (RFC 8707). Handing either the `/mcp`-stripped\n // base names a different resource, which authorization servers that validate\n // the `resource` indicator reject as `invalid_target`.\n const mcpServerUrl = normalizeUrl(serverConfig.url);\n const capabilities = await withTimeout(probeAuthCapabilities(mcpServerUrl), DCR_CAPABILTY_DISCOVERY_TIMEOUT, 'DCR capability discovery');\n\n let authToken: string | undefined;\n\n if (capabilities.supportsDcr) {\n logger.debug(`🔐 Server '${serverName}' supports DCR authentication`);\n\n // Get available port and create the exact redirect URI to use\n const port = await getPort();\n const redirectUri = `http://localhost:${port}/callback`;\n\n // Handle authentication using DcrAuthenticator with fully resolved redirectUri\n const authenticator = new DcrAuthenticator({\n headless: false,\n redirectUri,\n logger,\n ...options?.dcrAuthenticator,\n });\n\n // Ensure we have valid tokens (performs DCR + OAuth if needed)\n const tokens = await authenticator.ensureAuthenticated(mcpServerUrl, capabilities);\n authToken = tokens.accessToken;\n\n logger.debug(`✅ Authentication complete for '${serverName}'`);\n } else {\n logger.debug(`ℹ️ Server '${serverName}' does not support DCR - connecting without authentication`);\n }\n\n try {\n // Try modern Streamable HTTP first (protocol version 2025-03-26)\n // Merge static headers from config with DCR auth headers (DCR Authorization takes precedence)\n const staticHeaders = serverConfig.headers || {};\n const dcrHeaders = authToken ? { Authorization: `Bearer ${authToken}` } : {};\n const mergedHeaders = { ...staticHeaders, ...dcrHeaders };\n\n const transportOptions =\n Object.keys(mergedHeaders).length > 0\n ? {\n requestInit: {\n headers: mergedHeaders,\n },\n }\n : undefined;\n\n const transport = new StreamableHTTPClientTransport(url, transportOptions);\n // Type assertion: SDK transport has sessionId: string | undefined but Transport expects string\n // This is safe at runtime - the undefined is valid per MCP spec\n await withTimeout(client.connect(transport as unknown as Transport), 30000, 'StreamableHTTP connection');\n } catch (error) {\n // Fall back to SSE transport (MCP protocol version 2024-11-05)\n // SSE is a standard MCP transport used by many servers (e.g., FastMCP ecosystem)\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n // Fast-fail: Don't try SSE if connection was refused (server not running)\n // Check error.cause.code for ECONNREFUSED (fetch errors wrap the actual error in cause)\n const cause = error instanceof Error ? (error as Error & { cause?: { code?: string } }).cause : undefined;\n const isConnectionRefused = cause?.code === 'ECONNREFUSED' || errorMessage.includes('Connection refused');\n\n if (isConnectionRefused) {\n // Clean up client resources before throwing\n await client.close().catch(() => {});\n throw new Error(`Server not running at ${url}`);\n }\n\n // Check for known errors that indicate SSE fallback is needed\n const shouldFallback =\n errorMessage.includes('Missing session ID') || // FastMCP specific\n errorMessage.includes('404') || // Server doesn't have streamable HTTP endpoint\n errorMessage.includes('405'); // Method not allowed\n\n if (shouldFallback) {\n logger.warn(`Streamable HTTP failed (${errorMessage}), falling back to SSE transport`);\n } else {\n logger.warn('Streamable HTTP connection failed, trying SSE transport as fallback');\n }\n\n // Create new client for SSE transport (required per SDK pattern)\n const sseClient = new Client({ name: 'mcp-cli-client', version: '1.0.0' }, clientOptions);\n\n // SSE transport with merged headers (static + DCR auth)\n // Reuse the same header merging logic as Streamable HTTP\n const staticHeaders = serverConfig.headers || {};\n const dcrHeaders = authToken ? { Authorization: `Bearer ${authToken}` } : {};\n const mergedHeaders = { ...staticHeaders, ...dcrHeaders };\n\n const sseTransportOptions =\n Object.keys(mergedHeaders).length > 0\n ? {\n requestInit: {\n headers: mergedHeaders,\n },\n }\n : undefined;\n\n const sseTransport = new SSEClientTransport(url, sseTransportOptions);\n\n try {\n await withTimeout(sseClient.connect(sseTransport), 30000, 'SSE connection');\n // Return SSE client instead of original\n return sseClient;\n } catch (sseError) {\n // SSE connection failed - clean up both clients before throwing\n await Promise.all([client.close().catch(() => {}), sseClient.close().catch(() => {})]);\n throw sseError;\n }\n }\n }\n\n return client; // Guaranteed ready when returned\n}\n"],"names":["connectMcpClient","withTimeout","promise","ms","operation","timeoutId","Promise","race","finally","clearTimeout","_","reject","setTimeout","Error","inferTransportType","config","type","url","URL","protocol","registryOrConfig","serverName","options","isRegistry","serversConfig","registry","logger","serverConfig","available","transportType","clientOptions","client","serverHandle","transport","isSpawnedHttp","mcpServerUrl","capabilities","authToken","port","redirectUri","authenticator","tokens","staticHeaders","dcrHeaders","mergedHeaders","transportOptions","error","errorMessage","cause","isConnectionRefused","shouldFallback","sseClient","sseTransportOptions","sseTransport","sseError","servers","Map","undefined","defaultLogger","Object","keys","join","versionNegotiation","Client","name","version","get","ExistingProcessTransport","process","connect","command","StdioClientTransport","args","env","has","debug","waitForHttpReady","normalizeUrl","probeAuthCapabilities","DCR_CAPABILTY_DISCOVERY_TIMEOUT","supportsDcr","getPort","DcrAuthenticator","headless","dcrAuthenticator","ensureAuthenticated","accessToken","headers","Authorization","length","requestInit","StreamableHTTPClientTransport","message","String","code","includes","close","catch","warn","SSEClientTransport","all"],"mappings":"AAAA;;;;;CAKC;;;;+BAwIqBA;;;eAAAA;;;sBArIoD;qBACrC;8DACjB;uBACkB;2BACU;wBACe;0BAClC;wBAcwB;0CACZ;kCAC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;4BACXH,SAAS3C;wBACX;oBACF,IACAa;oBAEAJ,eAAe,IAAI8C,0BAAkB,CAAClF,KAAKmC;;;;;;;;;oBAG/C;;wBAAMnD,YAAYkD,UAAUkB,OAAO,CAAChB,eAAe,OAAO;;;oBAA1D;oBACA,wCAAwC;oBACxC;;wBAAOF;;;oBACAG;oBACP,gEAAgE;oBAChE;;wBAAMhD,QAAQ8F,GAAG;4BAAErE,OAAOiE,KAAK,GAAGC,KAAK,CAAC,YAAO;4BAAI9C,UAAU6C,KAAK,GAAGC,KAAK,CAAC,YAAO;;;;oBAAlF;oBACA,MAAM3C;;;;;;;oBAKZ;;wBAAOvB;uBAAQ,iCAAiC;;;IAClD"}
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * @mcp-z/client - MCP Client Library
3
3
  */
4
+ export type { VersionNegotiationOptions } from '@modelcontextprotocol/client';
5
+ export { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
4
6
  export type { McpServerEntry, StartConfig } from '../schemas/servers.d.js';
5
7
  export { probeAuthCapabilities } from './auth/capability-discovery.js';
6
8
  export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * @mcp-z/client - MCP Client Library
3
3
  */
4
+ export type { VersionNegotiationOptions } from '@modelcontextprotocol/client';
5
+ export { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
4
6
  export type { McpServerEntry, StartConfig } from '../schemas/servers.d.js';
5
7
  export { probeAuthCapabilities } from './auth/capability-discovery.js';
6
8
  export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * @mcp-z/client - MCP Client Library
3
- */ // Config types (from schema)
4
- "use strict";
3
+ */ "use strict";
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
@@ -39,6 +38,12 @@ _export(exports, {
39
38
  get ResourceResponseWrapper () {
40
39
  return _responsewrappersts.ResourceResponseWrapper;
41
40
  },
41
+ get SdkError () {
42
+ return _client.SdkError;
43
+ },
44
+ get SdkErrorCode () {
45
+ return _client.SdkErrorCode;
46
+ },
42
47
  get ToolResponseError () {
43
48
  return _responsewrappersts.ToolResponseError;
44
49
  },
@@ -85,6 +90,7 @@ _export(exports, {
85
90
  return _validateconfigts.validateServers;
86
91
  }
87
92
  });
93
+ var _client = require("@modelcontextprotocol/client");
88
94
  var _capabilitydiscoveryts = require("./auth/capability-discovery.js");
89
95
  var _discoveryfetchts = require("./auth/discovery-fetch.js");
90
96
  var _interactiveoauthflowts = require("./auth/interactive-oauth-flow.js");
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/index.ts"],"sourcesContent":["/**\n * @mcp-z/client - MCP Client Library\n */\n\n// Config types (from schema)\nexport type { McpServerEntry, StartConfig } from '../schemas/servers.d.ts';\n// Auth - OAuth utilities\nexport { probeAuthCapabilities } from './auth/capability-discovery.ts';\nexport { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.ts';\nexport type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.ts';\nexport { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.ts';\nexport { OAuthCallbackListener } from './auth/oauth-callback-listener.ts';\n// Client helpers and lightweight overloads\nexport { decorateClient, type ManagedClient, type PromptArguments, type WrappedCallToolReturn, type WrappedGetPromptReturn, type WrappedReadResourceReturn } from './client-helpers.ts';\n// Config - Configuration validation\nexport { type ValidationResult, validateServers } from './config/validate-config.ts';\n// Connection - MCP client connection utilities (internal helpers exposed for advanced use)\nexport type { JsonValue, PromptArgument, ToolArguments } from './connection/types.ts';\n// DCR - Dynamic Client Registration utilities\nexport { DcrAuthenticator } from './dcr/dcr-authenticator.ts';\nexport { DynamicClientRegistrar } from './dcr/dynamic-client-registrar.ts';\nexport type { ClientCredentials, DcrAuthenticatorOptions, DcrRegistrationOptions } from './dcr/index.ts';\nexport {\n type JsonValidator,\n type NativeCallToolResponse,\n type NativeGetPromptResponse,\n type NativeReadResourceResponse,\n PromptResponseError,\n PromptResponseWrapper,\n ResourceResponseError,\n ResourceResponseWrapper,\n ToolResponseError,\n ToolResponseWrapper,\n} from './response-wrappers.ts';\nexport type { CapabilityClient, CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './search/index.ts';\n// Search - Capability discovery\nexport { buildCapabilityIndex, search, searchCapabilities } from './search/index.ts';\n// Spawn - Server registry (v3 API)\nexport { type CloseResult, type CreateServerRegistryOptions, createServerRegistry, type Dialect, type ServerRegistry, type ServersConfig } from './spawn/spawn-servers.ts';\nexport type { TransportType } from './types.ts';\n// Utils - Shared utilities\nexport { getLogLevel, type Logger, type LogLevel, logger, setLogLevel } from './utils/logger.ts';\nexport { resolveArgsPaths, resolvePath } from './utils/path-utils.ts';\n"],"names":["DcrAuthenticator","DiscoveryFetchError","DynamicClientRegistrar","InteractiveOAuthFlow","OAuthCallbackListener","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","createServerRegistry","decorateClient","getLogLevel","isLoopbackUrl","logger","probeAuthCapabilities","resolveArgsPaths","resolvePath","search","searchCapabilities","setLogLevel","validateServers"],"mappings":"AAAA;;CAEC,GAED,6BAA6B;;;;;;;;;;;;QAepBA;eAAAA,oCAAgB;;QAXhBC;eAAAA,qCAAmB;;QAYnBC;eAAAA,gDAAsB;;QAVtBC;eAAAA,4CAAoB;;QACpBC;eAAAA,8CAAqB;;QAgB5BC;eAAAA,uCAAmB;;QACnBC;eAAAA,yCAAqB;;QACrBC;eAAAA,yCAAqB;;QACrBC;eAAAA,2CAAuB;;QACvBC;eAAAA,qCAAiB;;QACjBC;eAAAA,uCAAmB;;QAIZC;eAAAA,6BAAoB;;QAEgCC;eAAAA,oCAAoB;;QAzBxEC;eAAAA,+BAAc;;QA4BdC;eAAAA,qBAAW;;QAjCUC;eAAAA,+BAAa;;QAiCOC;eAAAA,gBAAM;;QAlC/CC;eAAAA,4CAAqB;;QAmCrBC;eAAAA,6BAAgB;;QAAEC;eAAAA,wBAAW;;QANPC;eAAAA,eAAM;;QAAEC;eAAAA,2BAAkB;;QAKCC;eAAAA,qBAAW;;QA1BrCC;eAAAA,iCAAe;;;qCART;gCACa;sCAEd;uCACC;+BAE4H;gCAE3G;kCAItB;wCACM;kCAahC;uBAG0D;8BAE+E;wBAGnE;2BAC/B"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/index.ts"],"sourcesContent":["/**\n * @mcp-z/client - MCP Client Library\n */\n\nexport type { VersionNegotiationOptions } from '@modelcontextprotocol/client';\n// SDK re-exports for protocol version negotiation: the connect-option type and the typed\n// errors a negotiation can fail with, so callers can handle era mismatch without\n// depending on the SDK themselves.\nexport { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';\n// Config types (from schema)\nexport type { McpServerEntry, StartConfig } from '../schemas/servers.d.ts';\n// Auth - OAuth utilities\nexport { probeAuthCapabilities } from './auth/capability-discovery.ts';\nexport { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.ts';\nexport type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.ts';\nexport { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.ts';\nexport { OAuthCallbackListener } from './auth/oauth-callback-listener.ts';\n// Client helpers and lightweight overloads\nexport { decorateClient, type ManagedClient, type PromptArguments, type WrappedCallToolReturn, type WrappedGetPromptReturn, type WrappedReadResourceReturn } from './client-helpers.ts';\n// Config - Configuration validation\nexport { type ValidationResult, validateServers } from './config/validate-config.ts';\n// Connection - MCP client connection utilities (internal helpers exposed for advanced use)\nexport type { JsonValue, PromptArgument, ToolArguments } from './connection/types.ts';\n// DCR - Dynamic Client Registration utilities\nexport { DcrAuthenticator } from './dcr/dcr-authenticator.ts';\nexport { DynamicClientRegistrar } from './dcr/dynamic-client-registrar.ts';\nexport type { ClientCredentials, DcrAuthenticatorOptions, DcrRegistrationOptions } from './dcr/index.ts';\nexport {\n type JsonValidator,\n type NativeCallToolResponse,\n type NativeGetPromptResponse,\n type NativeReadResourceResponse,\n PromptResponseError,\n PromptResponseWrapper,\n ResourceResponseError,\n ResourceResponseWrapper,\n ToolResponseError,\n ToolResponseWrapper,\n} from './response-wrappers.ts';\nexport type { CapabilityClient, CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './search/index.ts';\n// Search - Capability discovery\nexport { buildCapabilityIndex, search, searchCapabilities } from './search/index.ts';\n// Spawn - Server registry (v3 API)\nexport { type CloseResult, type CreateServerRegistryOptions, createServerRegistry, type Dialect, type ServerRegistry, type ServersConfig } from './spawn/spawn-servers.ts';\nexport type { TransportType } from './types.ts';\n// Utils - Shared utilities\nexport { getLogLevel, type Logger, type LogLevel, logger, setLogLevel } from './utils/logger.ts';\nexport { resolveArgsPaths, resolvePath } from './utils/path-utils.ts';\n"],"names":["DcrAuthenticator","DiscoveryFetchError","DynamicClientRegistrar","InteractiveOAuthFlow","OAuthCallbackListener","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","SdkError","SdkErrorCode","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","createServerRegistry","decorateClient","getLogLevel","isLoopbackUrl","logger","probeAuthCapabilities","resolveArgsPaths","resolvePath","search","searchCapabilities","setLogLevel","validateServers"],"mappings":"AAAA;;CAEC;;;;;;;;;;;QAsBQA;eAAAA,oCAAgB;;QAXhBC;eAAAA,qCAAmB;;QAYnBC;eAAAA,gDAAsB;;QAVtBC;eAAAA,4CAAoB;;QACpBC;eAAAA,8CAAqB;;QAgB5BC;eAAAA,uCAAmB;;QACnBC;eAAAA,yCAAqB;;QACrBC;eAAAA,yCAAqB;;QACrBC;eAAAA,2CAAuB;;QA3BhBC;eAAAA,gBAAQ;;QAAEC;eAAAA,oBAAY;;QA4B7BC;eAAAA,qCAAiB;;QACjBC;eAAAA,uCAAmB;;QAIZC;eAAAA,6BAAoB;;QAEgCC;eAAAA,oCAAoB;;QAzBxEC;eAAAA,+BAAc;;QA4BdC;eAAAA,qBAAW;;QAjCUC;eAAAA,+BAAa;;QAiCOC;eAAAA,gBAAM;;QAlC/CC;eAAAA,4CAAqB;;QAmCrBC;eAAAA,6BAAgB;;QAAEC;eAAAA,wBAAW;;QANPC;eAAAA,eAAM;;QAAEC;eAAAA,2BAAkB;;QAKCC;eAAAA,qBAAW;;QA1BrCC;eAAAA,iCAAe;;;sBAZR;qCAID;gCACa;sCAEd;uCACC;+BAE4H;gCAE3G;kCAItB;wCACM;kCAahC;uBAG0D;8BAE+E;wBAGnE;2BAC/B"}
@@ -1,6 +1,15 @@
1
1
  export declare class DiscoveryFetchError extends Error {
2
2
  constructor(message: string);
3
3
  }
4
+ type LookupRecord = {
5
+ address: string;
6
+ family: number;
7
+ };
8
+ /** DNS implementation, injectable for deterministic tests. Same contract as `dns.lookup` with `{ all: true, verbatim: true }`. */
9
+ type Lookup = (hostname: string, options: {
10
+ all: true;
11
+ verbatim: true;
12
+ }, callback: (error: NodeJS.ErrnoException | null, addresses: LookupRecord[]) => void) => void;
4
13
  /**
5
14
  * True if `rawUrl`'s host is loopback, used to decide `allowLoopback` grants
6
15
  * from the URL the caller configured, not remote-supplied data. Fails closed on an unparseable URL.
@@ -13,15 +22,25 @@ export interface DiscoveryFetchOptions {
13
22
  */
14
23
  allowLoopback?: boolean;
15
24
  /**
16
- * Per-request connect/read timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`;
17
- * overridable so tests can bound slow-failure cases.
25
+ * Per-hop timeout in ms, applied to both the DNS resolution and the request.
26
+ * Defaults to `DEFAULT_TIMEOUT_MS`; overridable so tests can bound slow-failure cases.
18
27
  */
19
28
  timeoutMs?: number;
29
+ /**
30
+ * DNS implementation used for the pre-request resolution, injectable for
31
+ * deterministic tests. Defaults to `dns.lookup`.
32
+ */
33
+ lookup?: Lookup;
20
34
  }
21
35
  /**
22
36
  * Fetches an OAuth-discovery URL with SSRF mitigations applied to the
23
37
  * initial URL and every redirect hop; redirects are validated, not auto-followed.
24
38
  *
39
+ * The hostname is resolved once, every returned address is validated, and the
40
+ * validated set is pinned into the request through a custom `lookup`, so the
41
+ * request cannot resolve the hostname a second time and cannot be steered to
42
+ * a different address by a DNS-rebinding answer.
43
+ *
25
44
  * @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).
26
45
  * @param init - Standard fetch options; `redirect` is always forced to `'manual'`.
27
46
  * @param context - Short label used only in error messages, never echoing the URL.
@@ -33,3 +52,4 @@ export declare function discoveryFetch(rawUrl: string, init?: RequestInit, conte
33
52
  * while reading (not after buffering the whole thing).
34
53
  */
35
54
  export declare function readDiscoveryJson<T>(response: Response, context: string): Promise<T>;
55
+ export {};