@mcp-z/client 2.0.1 → 2.1.0

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.
Files changed (31) hide show
  1. package/dist/cjs/auth/capability-discovery.js +11 -5
  2. package/dist/cjs/auth/capability-discovery.js.map +1 -1
  3. package/dist/cjs/auth/types.d.cts +11 -0
  4. package/dist/cjs/auth/types.d.ts +11 -0
  5. package/dist/cjs/auth/types.js.map +1 -1
  6. package/dist/cjs/connection/connect-client.d.cts +0 -9
  7. package/dist/cjs/connection/connect-client.d.ts +0 -9
  8. package/dist/cjs/connection/connect-client.js +14 -32
  9. package/dist/cjs/connection/connect-client.js.map +1 -1
  10. package/dist/cjs/dcr/dcr-authenticator.d.cts +30 -4
  11. package/dist/cjs/dcr/dcr-authenticator.d.ts +30 -4
  12. package/dist/cjs/dcr/dcr-authenticator.js +57 -24
  13. package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
  14. package/dist/cjs/lib/url-utils.d.cts +17 -0
  15. package/dist/cjs/lib/url-utils.d.ts +17 -0
  16. package/dist/cjs/lib/url-utils.js +20 -0
  17. package/dist/cjs/lib/url-utils.js.map +1 -1
  18. package/dist/esm/auth/capability-discovery.js +11 -5
  19. package/dist/esm/auth/capability-discovery.js.map +1 -1
  20. package/dist/esm/auth/types.d.ts +11 -0
  21. package/dist/esm/auth/types.js.map +1 -1
  22. package/dist/esm/connection/connect-client.d.ts +0 -9
  23. package/dist/esm/connection/connect-client.js +10 -27
  24. package/dist/esm/connection/connect-client.js.map +1 -1
  25. package/dist/esm/dcr/dcr-authenticator.d.ts +30 -4
  26. package/dist/esm/dcr/dcr-authenticator.js +56 -23
  27. package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
  28. package/dist/esm/lib/url-utils.d.ts +17 -0
  29. package/dist/esm/lib/url-utils.js +32 -0
  30. package/dist/esm/lib/url-utils.js.map +1 -1
  31. package/package.json +1 -2
@@ -9,6 +9,7 @@ import getPort from 'get-port';
9
9
  import { probeAuthCapabilities } from '../auth/index.js';
10
10
  import { DCR_CAPABILTY_DISCOVERY_TIMEOUT } from '../constants.js';
11
11
  import { DcrAuthenticator } from '../dcr/index.js';
12
+ import { normalizeUrl } from '../lib/url-utils.js';
12
13
  import { logger as defaultLogger } from '../utils/logger.js';
13
14
  import { ExistingProcessTransport } from './existing-process-transport.js';
14
15
  import { waitForHttpReady } from './wait-for-http-ready.js';
@@ -28,30 +29,6 @@ import { waitForHttpReady } from './wait-for-http-ready.js';
28
29
  })
29
30
  ]);
30
31
  }
31
- /**
32
- * Extract the "server base" by removing a trailing `/mcp` path segment if present.
33
- * Examples:
34
- * - https://example.com/mcp -> https://example.com
35
- * - https://example.com/sheets/mcp -> https://example.com/sheets
36
- * - https://example.com/sheets/mcp/ -> https://example.com/sheets
37
- * - https://example.com/sheets -> https://example.com/sheets
38
- */ export function extractBaseUrl(mcpUrl) {
39
- const url = new URL(mcpUrl);
40
- // Ignore query/hash for base URL purposes
41
- url.search = '';
42
- url.hash = '';
43
- // Normalize path segments (removes empty segments from leading/trailing slashes)
44
- const segments = url.pathname.split('/').filter(Boolean);
45
- // If last segment is exactly "mcp", drop it
46
- if (segments[segments.length - 1] === 'mcp') {
47
- segments.pop();
48
- }
49
- // Rebuild pathname; empty means root
50
- url.pathname = segments.length ? `/${segments.join('/')}` : '';
51
- // Return without trailing slash (except root origin)
52
- const out = url.origin + url.pathname;
53
- return out === url.origin ? out : out.replace(/\/+$/, '');
54
- }
55
32
  /**
56
33
  * Infer transport type from server configuration with validation.
57
34
  *
@@ -181,8 +158,14 @@ import { waitForHttpReady } from './wait-for-http-ready.js';
181
158
  }
182
159
  const url = new URL(serverConfig.url);
183
160
  // Check for DCR support and handle authentication automatically
184
- const baseUrl = extractBaseUrl(serverConfig.url);
185
- const capabilities = await withTimeout(probeAuthCapabilities(baseUrl), DCR_CAPABILTY_DISCOVERY_TIMEOUT, 'DCR capability discovery');
161
+ // The canonical MCP server URI, path segment and all. Both calls below need
162
+ // the server's identity, not its deployment root: discovery uses the path to
163
+ // find resource-specific metadata (RFC 9728 sub-path), and the authenticator
164
+ // audience-binds tokens to it (RFC 8707). Handing either the `/mcp`-stripped
165
+ // base names a different resource, which authorization servers that validate
166
+ // the `resource` indicator reject as `invalid_target`.
167
+ const mcpServerUrl = normalizeUrl(serverConfig.url);
168
+ const capabilities = await withTimeout(probeAuthCapabilities(mcpServerUrl), DCR_CAPABILTY_DISCOVERY_TIMEOUT, 'DCR capability discovery');
186
169
  let authToken;
187
170
  if (capabilities.supportsDcr) {
188
171
  logger.debug(`🔐 Server '${serverName}' supports DCR authentication`);
@@ -197,7 +180,7 @@ import { waitForHttpReady } from './wait-for-http-ready.js';
197
180
  ...options === null || options === void 0 ? void 0 : options.dcrAuthenticator
198
181
  });
199
182
  // Ensure we have valid tokens (performs DCR + OAuth if needed)
200
- const tokens = await authenticator.ensureAuthenticated(baseUrl, capabilities);
183
+ const tokens = await authenticator.ensureAuthenticated(mcpServerUrl, capabilities);
201
184
  authToken = tokens.accessToken;
202
185
  logger.debug(`✅ Authentication complete for '${serverName}'`);
203
186
  } else {
@@ -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 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 * Extract the \"server base\" by removing a trailing `/mcp` path segment if present.\n * Examples:\n * - https://example.com/mcp -> https://example.com\n * - https://example.com/sheets/mcp -> https://example.com/sheets\n * - https://example.com/sheets/mcp/ -> https://example.com/sheets\n * - https://example.com/sheets -> https://example.com/sheets\n */\nexport function extractBaseUrl(mcpUrl: string): string {\n const url = new URL(mcpUrl);\n\n // Ignore query/hash for base URL purposes\n url.search = '';\n url.hash = '';\n\n // Normalize path segments (removes empty segments from leading/trailing slashes)\n const segments = url.pathname.split('/').filter(Boolean);\n\n // If last segment is exactly \"mcp\", drop it\n if (segments[segments.length - 1] === 'mcp') {\n segments.pop();\n }\n\n // Rebuild pathname; empty means root\n url.pathname = segments.length ? `/${segments.join('/')}` : '';\n\n // Return without trailing slash (except root origin)\n const out = url.origin + url.pathname;\n return out === url.origin ? out : out.replace(/\\/+$/, '');\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 const baseUrl = extractBaseUrl(serverConfig.url);\n const capabilities = await withTimeout(probeAuthCapabilities(baseUrl), 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(baseUrl, 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":["Client","SSEClientTransport","StreamableHTTPClientTransport","StdioClientTransport","getPort","probeAuthCapabilities","DCR_CAPABILTY_DISCOVERY_TIMEOUT","DcrAuthenticator","logger","defaultLogger","ExistingProcessTransport","waitForHttpReady","withTimeout","promise","ms","operation","timeoutId","Promise","race","finally","clearTimeout","_","reject","setTimeout","Error","extractBaseUrl","mcpUrl","url","URL","search","hash","segments","pathname","split","filter","Boolean","length","pop","join","out","origin","replace","inferTransportType","config","type","protocol","connectMcpClient","registryOrConfig","serverName","options","isRegistry","servers","Map","serversConfig","registry","undefined","serverConfig","available","Object","keys","transportType","client","name","version","capabilities","serverHandle","get","transport","process","connect","command","args","env","isSpawnedHttp","has","debug","baseUrl","authToken","supportsDcr","port","redirectUri","authenticator","headless","dcrAuthenticator","tokens","ensureAuthenticated","accessToken","staticHeaders","headers","dcrHeaders","Authorization","mergedHeaders","transportOptions","requestInit","error","errorMessage","message","String","cause","isConnectionRefused","code","includes","close","catch","shouldFallback","warn","sseClient","sseTransportOptions","sseTransport","sseError","all"],"mappings":"AAAA;;;;;CAKC,GAGD,SAASA,MAAM,EAAEC,kBAAkB,EAAEC,6BAA6B,QAAQ,+BAA+B;AACzG,SAASC,oBAAoB,QAAQ,qCAAqC;AAC1E,OAAOC,aAAa,WAAW;AAC/B,SAASC,qBAAqB,QAAQ,mBAAmB;AACzD,SAASC,+BAA+B,QAAQ,kBAAkB;AAClE,SAASC,gBAAgB,QAAsC,kBAAkB;AAcjF,SAASC,UAAUC,aAAa,QAAqB,qBAAqB;AAC1E,SAASC,wBAAwB,QAAQ,kCAAkC;AAC3E,SAASC,gBAAgB,QAAQ,2BAA2B;AAE5D;;;;;;;CAOC,GACD,eAAeC,YAAeC,OAAmB,EAAEC,EAAU,EAAEC,SAAiB;IAC9E,IAAIC;IAEJ,OAAOC,QAAQC,IAAI,CAAC;QAClBL,QAAQM,OAAO,CAAC,IAAMC,aAAaJ;QACnC,IAAIC,QAAW,CAACI,GAAGC;YACjBN,YAAYO,WAAW,IAAMD,OAAO,IAAIE,MAAM,CAAC,cAAc,EAAEV,GAAG,IAAI,EA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gE;gBAChE,MAAM5F,QAAQ6F,GAAG,CAAC;oBAACjD,OAAOyC,KAAK,GAAGC,KAAK,CAAC,KAAO;oBAAIG,UAAUJ,KAAK,GAAGC,KAAK,CAAC,KAAO;iBAAG;gBACrF,MAAMM;YACR;QACF;IACF;IAEA,OAAOhD,QAAQ,iCAAiC;AAClD"}
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":["Client","SSEClientTransport","StreamableHTTPClientTransport","StdioClientTransport","getPort","probeAuthCapabilities","DCR_CAPABILTY_DISCOVERY_TIMEOUT","DcrAuthenticator","normalizeUrl","logger","defaultLogger","ExistingProcessTransport","waitForHttpReady","withTimeout","promise","ms","operation","timeoutId","Promise","race","finally","clearTimeout","_","reject","setTimeout","Error","inferTransportType","config","type","url","URL","protocol","connectMcpClient","registryOrConfig","serverName","options","isRegistry","servers","Map","serversConfig","registry","undefined","serverConfig","available","Object","keys","join","transportType","client","name","version","capabilities","serverHandle","get","transport","process","connect","command","args","env","isSpawnedHttp","has","debug","mcpServerUrl","authToken","supportsDcr","port","redirectUri","authenticator","headless","dcrAuthenticator","tokens","ensureAuthenticated","accessToken","staticHeaders","headers","dcrHeaders","Authorization","mergedHeaders","transportOptions","length","requestInit","error","errorMessage","message","String","cause","isConnectionRefused","code","includes","close","catch","shouldFallback","warn","sseClient","sseTransportOptions","sseTransport","sseError","all"],"mappings":"AAAA;;;;;CAKC,GAGD,SAASA,MAAM,EAAEC,kBAAkB,EAAEC,6BAA6B,QAAQ,+BAA+B;AACzG,SAASC,oBAAoB,QAAQ,qCAAqC;AAC1E,OAAOC,aAAa,WAAW;AAC/B,SAASC,qBAAqB,QAAQ,mBAAmB;AACzD,SAASC,+BAA+B,QAAQ,kBAAkB;AAClE,SAASC,gBAAgB,QAAsC,kBAAkB;AACjF,SAASC,YAAY,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G;gBACrF,MAAMM;YACR;QACF;IACF;IAEA,OAAOjD,QAAQ,iCAAiC;AAClD"}
@@ -39,7 +39,9 @@ export declare class DcrAuthenticator {
39
39
  * Ensure server is authenticated, performing DCR and OAuth if needed
40
40
  * Proactively refreshes tokens if they're within 5 minutes of expiry
41
41
  *
42
- * @param baseUrl - Base URL of the server (e.g., https://example.com)
42
+ * @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,
43
+ * with its path intact (`https://example.com/mcp`). Not a deployment root:
44
+ * the path is what identifies the resource an issued token is bound to.
43
45
  * @param capabilities - Auth capabilities from .well-known endpoint
44
46
  * @returns Valid token set ready to use
45
47
  *
@@ -48,11 +50,30 @@ export declare class DcrAuthenticator {
48
50
  * @example
49
51
  * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });
50
52
  * const tokens = await authenticator.ensureAuthenticated(
51
- * 'https://example.com',
53
+ * 'https://example.com/mcp',
52
54
  * capabilities
53
55
  * );
54
56
  */
55
- ensureAuthenticated(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet>;
57
+ ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet>;
58
+ /**
59
+ * The three things a server URL is used for here, kept apart on purpose.
60
+ *
61
+ * They were one value once, and collapsing them is what sent an authorization
62
+ * server the wrong audience: `resource` was derived from the deployment root,
63
+ * so a server at `https://host/mcp` was asked to mint a token for
64
+ * `https://host`, and any server that validates the indicator answered
65
+ * `invalid_target`.
66
+ *
67
+ * - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a
68
+ * trailing `/mcp` comes off.
69
+ * - `resource` is the RFC 8707 audience. The resource server names itself in
70
+ * its RFC 9728 metadata; that name wins. Only when no such document exists
71
+ * do we fall back to the URL we were configured with.
72
+ * - `storeKey` identifies the credential locally. It stays the configured URL
73
+ * rather than the discovered `resource`, so it can be computed without a
74
+ * network round trip - `deleteTokens` has only the URL to work from.
75
+ */
76
+ private resolveUrls;
56
77
  /**
57
78
  * Handle authentication for self-hosted DCR servers
58
79
  * Self-hosted servers manage their own token storage via /oauth/verify
@@ -68,9 +89,14 @@ export declare class DcrAuthenticator {
68
89
  private refreshTokens;
69
90
  /**
70
91
  * Deletes both stored token families for a server, across every issuer they were bound to.
92
+ *
93
+ * Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}
94
+ * was given - keys are built from the configured URL, never from the discovered
95
+ * RFC 8707 resource, precisely so this can find them without doing discovery.
96
+ *
71
97
  * @throws CredentialBindingError if the configured store cannot enumerate keys.
72
98
  */
73
- deleteTokens(baseUrl: string): Promise<void>;
99
+ deleteTokens(mcpServerUrl: string): Promise<void>;
74
100
  /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */
75
101
  private loadTokens;
76
102
  private buildFlowOptions;
@@ -7,7 +7,7 @@ import Keyv from 'keyv';
7
7
  import { KeyvFile } from 'keyv-file';
8
8
  import { isLoopbackUrl } from '../auth/discovery-fetch.js';
9
9
  import { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.js';
10
- import { normalizeUrl } from '../lib/url-utils.js';
10
+ import { extractBaseUrl, normalizeUrl } from '../lib/url-utils.js';
11
11
  import { logger as defaultLogger } from '../utils/logger.js';
12
12
  import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
13
13
  /**
@@ -35,13 +35,13 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
35
35
  /**
36
36
  * Detect if server is self-hosted DCR (vs external OAuth provider)
37
37
  * Self-hosted servers have their own OAuth endpoints and manage token storage
38
- */ async detectSelfHostedMode(baseUrl) {
38
+ */ async detectSelfHostedMode(mcpServerUrl) {
39
39
  try {
40
40
  // Self-hosted DCR servers typically run their own OAuth server
41
41
  // Check if this is a self-hosted instance by testing OAuth metadata
42
- // For now, assume self-hosted if baseUrl matches common localhost patterns
42
+ // For now, assume self-hosted if the URL matches common localhost patterns
43
43
  // TODO: Implement proper self-hosted detection logic
44
- return baseUrl.includes('localhost') || baseUrl.includes('127.0.0.1');
44
+ return mcpServerUrl.includes('localhost') || mcpServerUrl.includes('127.0.0.1');
45
45
  } catch (_error) {
46
46
  return false; // Assume external mode if detection fails
47
47
  }
@@ -50,7 +50,9 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
50
50
  * Ensure server is authenticated, performing DCR and OAuth if needed
51
51
  * Proactively refreshes tokens if they're within 5 minutes of expiry
52
52
  *
53
- * @param baseUrl - Base URL of the server (e.g., https://example.com)
53
+ * @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,
54
+ * with its path intact (`https://example.com/mcp`). Not a deployment root:
55
+ * the path is what identifies the resource an issued token is bound to.
54
56
  * @param capabilities - Auth capabilities from .well-known endpoint
55
57
  * @returns Valid token set ready to use
56
58
  *
@@ -59,33 +61,59 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
59
61
  * @example
60
62
  * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });
61
63
  * const tokens = await authenticator.ensureAuthenticated(
62
- * 'https://example.com',
64
+ * 'https://example.com/mcp',
63
65
  * capabilities
64
66
  * );
65
- */ async ensureAuthenticated(baseUrl, capabilities) {
67
+ */ async ensureAuthenticated(mcpServerUrl, capabilities) {
66
68
  // Auto-detect server mode
67
- const isSelfHosted = await this.detectSelfHostedMode(baseUrl);
69
+ const isSelfHosted = await this.detectSelfHostedMode(mcpServerUrl);
68
70
  if (isSelfHosted) {
69
- return this.ensureAuthenticatedSelfHosted(baseUrl, capabilities);
71
+ return this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities);
70
72
  }
71
- return this.ensureAuthenticatedExternal(baseUrl, capabilities);
73
+ return this.ensureAuthenticatedExternal(mcpServerUrl, capabilities);
74
+ }
75
+ /**
76
+ * The three things a server URL is used for here, kept apart on purpose.
77
+ *
78
+ * They were one value once, and collapsing them is what sent an authorization
79
+ * server the wrong audience: `resource` was derived from the deployment root,
80
+ * so a server at `https://host/mcp` was asked to mint a token for
81
+ * `https://host`, and any server that validates the indicator answered
82
+ * `invalid_target`.
83
+ *
84
+ * - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a
85
+ * trailing `/mcp` comes off.
86
+ * - `resource` is the RFC 8707 audience. The resource server names itself in
87
+ * its RFC 9728 metadata; that name wins. Only when no such document exists
88
+ * do we fall back to the URL we were configured with.
89
+ * - `storeKey` identifies the credential locally. It stays the configured URL
90
+ * rather than the discovered `resource`, so it can be computed without a
91
+ * network round trip - `deleteTokens` has only the URL to work from.
92
+ */ resolveUrls(mcpServerUrl, capabilities) {
93
+ var _capabilities_resource;
94
+ const storeKey = normalizeUrl(mcpServerUrl);
95
+ return {
96
+ serverBaseUrl: extractBaseUrl(mcpServerUrl),
97
+ resource: (_capabilities_resource = capabilities.resource) !== null && _capabilities_resource !== void 0 ? _capabilities_resource : storeKey,
98
+ storeKey
99
+ };
72
100
  }
73
101
  /**
74
102
  * Handle authentication for self-hosted DCR servers
75
103
  * Self-hosted servers manage their own token storage via /oauth/verify
76
- */ async ensureAuthenticatedSelfHosted(baseUrl, capabilities) {
104
+ */ async ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities) {
77
105
  // Loopback trust for every discovery-derived fetch below, computed from
78
106
  // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).
79
- const allowLoopback = isLoopbackUrl(baseUrl);
107
+ const allowLoopback = isLoopbackUrl(mcpServerUrl);
80
108
  const issuer = requireIssuer(capabilities);
81
- const resource = normalizeUrl(baseUrl);
82
- const dcrTokenKey = `dcr-tokens:${issuer}:${resource}`;
109
+ const { serverBaseUrl, resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);
110
+ const dcrTokenKey = `dcr-tokens:${issuer}:${storeKey}`;
83
111
  // 1. Check for existing DCR tokens (different from external tokens)
84
112
  let tokens = await this.loadTokens(dcrTokenKey, issuer);
85
113
  if (tokens) {
86
114
  // 2. Verify token is still valid by calling /oauth/verify
87
115
  try {
88
- const verifyUrl = `${baseUrl}/oauth/verify`;
116
+ const verifyUrl = `${serverBaseUrl}/oauth/verify`;
89
117
  const verifyResponse = await fetch(verifyUrl, {
90
118
  headers: {
91
119
  Authorization: `Bearer ${tokens.accessToken}`,
@@ -124,7 +152,7 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
124
152
  tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);
125
153
  // For self-hosted mode, verify the token works with /oauth/verify immediately
126
154
  try {
127
- const verifyUrl = `${baseUrl}/oauth/verify`;
155
+ const verifyUrl = `${serverBaseUrl}/oauth/verify`;
128
156
  const verifyResponse = await fetch(verifyUrl, {
129
157
  headers: {
130
158
  Authorization: `Bearer ${tokens.accessToken}`,
@@ -151,12 +179,12 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
151
179
  this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');
152
180
  return tokens;
153
181
  }
154
- /** Handles authentication for external (non-self-hosted) OAuth providers. */ async ensureAuthenticatedExternal(baseUrl, capabilities) {
182
+ /** Handles authentication for external (non-self-hosted) OAuth providers. */ async ensureAuthenticatedExternal(mcpServerUrl, capabilities) {
155
183
  // See ensureAuthenticatedSelfHosted - same loopback trust rule.
156
- const allowLoopback = isLoopbackUrl(baseUrl);
184
+ const allowLoopback = isLoopbackUrl(mcpServerUrl);
157
185
  const issuer = requireIssuer(capabilities);
158
- const resource = normalizeUrl(baseUrl);
159
- const tokenKey = `tokens:${issuer}:${resource}`;
186
+ const { resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);
187
+ const tokenKey = `tokens:${issuer}:${storeKey}`;
160
188
  // 1. Check for existing tokens
161
189
  let tokens = await this.loadTokens(tokenKey, issuer);
162
190
  if (tokens) {
@@ -223,9 +251,14 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
223
251
  }
224
252
  /**
225
253
  * Deletes both stored token families for a server, across every issuer they were bound to.
254
+ *
255
+ * Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}
256
+ * was given - keys are built from the configured URL, never from the discovered
257
+ * RFC 8707 resource, precisely so this can find them without doing discovery.
258
+ *
226
259
  * @throws CredentialBindingError if the configured store cannot enumerate keys.
227
- */ async deleteTokens(baseUrl) {
228
- const suffix = `:${normalizeUrl(baseUrl)}`;
260
+ */ async deleteTokens(mcpServerUrl) {
261
+ const suffix = `:${normalizeUrl(mcpServerUrl)}`;
229
262
  if (!this.tokenStore.iterator) {
230
263
  throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');
231
264
  }
@@ -234,7 +267,7 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
234
267
  await this.tokenStore.delete(key);
235
268
  }
236
269
  }
237
- this.logger.debug(`🗑️ Deleted tokens for ${baseUrl}`);
270
+ this.logger.debug(`🗑️ Deleted tokens for ${mcpServerUrl}`);
238
271
  }
239
272
  /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */ async loadTokens(key, issuer) {
240
273
  const tokens = await this.tokenStore.get(key);
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dcr-authenticator.ts"],"sourcesContent":["/**\n * DCR Authenticator\n * Consolidates DCR and OAuth flow logic for MCP HTTP servers\n */\n\nimport path from 'node:path';\nimport * as fs from 'fs';\nimport Keyv from 'keyv';\nimport { KeyvFile } from 'keyv-file';\nimport { isLoopbackUrl } from '../auth/discovery-fetch.ts';\nimport { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.ts';\nimport type { AuthCapabilities, OAuthFlowOptions, TokenSet } from '../auth/types.ts';\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { DynamicClientRegistrar } from './dynamic-client-registrar.ts';\n\n/**\n * DcrAuthenticator configuration options\n */\nexport interface DcrAuthenticatorOptions {\n /** Custom Keyv store (for testing) - if not provided, uses default ~/.mcpeasy/tokens.json */\n tokenStore?: Keyv;\n /** Headless mode (don't open browser) */\n headless?: boolean;\n /** Required redirect URI for OAuth callback */\n redirectUri: string;\n /** Optional logger for debug output (defaults to singleton logger) */\n logger?: Logger;\n}\n\n/**\n * Buffer time before token expiry to trigger proactive refresh (5 minutes)\n */\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/** Raised when a credential cannot be bound to, or looked up by, an issuer. */\nclass CredentialBindingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CredentialBindingError';\n }\n}\n\n/**\n * The issuer credentials are keyed by, so they can never be presented to a\n * different authorization server even when the resource keeps its URL (SEP-2352).\n */\nfunction requireIssuer(capabilities: AuthCapabilities): string {\n if (!capabilities.issuer) {\n throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');\n }\n return capabilities.issuer;\n}\n\n/**\n * DcrAuthenticator manages authentication for MCP HTTP servers\n * Handles DCR registration, OAuth flows, and token management\n */\nexport class DcrAuthenticator {\n private tokenStore: Keyv;\n private dcrClient: DynamicClientRegistrar;\n private oauthFlow: InteractiveOAuthFlow;\n private headless: boolean;\n private redirectUri: string;\n private logger: Logger;\n\n constructor(options: DcrAuthenticatorOptions) {\n if (options.tokenStore) {\n this.tokenStore = options.tokenStore;\n } else {\n // Default CLI store in .mcp-z directory (per-project)\n const storePath = path.join(process.cwd(), '.mcp-z', 'tokens.json');\n\n // Ensure directory exists before creating store\n fs.mkdirSync(path.dirname(storePath), { recursive: true });\n\n this.tokenStore = new Keyv({\n store: new KeyvFile({ filename: storePath }),\n });\n }\n this.dcrClient = new DynamicClientRegistrar();\n this.oauthFlow = new InteractiveOAuthFlow();\n this.headless = options.headless || false;\n this.redirectUri = options.redirectUri;\n this.logger = options.logger ?? defaultLogger;\n }\n\n /**\n * Detect if server is self-hosted DCR (vs external OAuth provider)\n * Self-hosted servers have their own OAuth endpoints and manage token storage\n */\n private async detectSelfHostedMode(baseUrl: string): Promise<boolean> {\n try {\n // Self-hosted DCR servers typically run their own OAuth server\n // Check if this is a self-hosted instance by testing OAuth metadata\n // For now, assume self-hosted if baseUrl matches common localhost patterns\n // TODO: Implement proper self-hosted detection logic\n return baseUrl.includes('localhost') || baseUrl.includes('127.0.0.1');\n } catch (_error) {\n return false; // Assume external mode if detection fails\n }\n }\n\n /**\n * Ensure server is authenticated, performing DCR and OAuth if needed\n * Proactively refreshes tokens if they're within 5 minutes of expiry\n *\n * @param baseUrl - Base URL of the server (e.g., https://example.com)\n * @param capabilities - Auth capabilities from .well-known endpoint\n * @returns Valid token set ready to use\n *\n * @throws Error if authentication fails\n *\n * @example\n * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });\n * const tokens = await authenticator.ensureAuthenticated(\n * 'https://example.com',\n * capabilities\n * );\n */\n async ensureAuthenticated(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Auto-detect server mode\n const isSelfHosted = await this.detectSelfHostedMode(baseUrl);\n\n if (isSelfHosted) {\n return this.ensureAuthenticatedSelfHosted(baseUrl, capabilities);\n }\n return this.ensureAuthenticatedExternal(baseUrl, capabilities);\n }\n\n /**\n * Handle authentication for self-hosted DCR servers\n * Self-hosted servers manage their own token storage via /oauth/verify\n */\n private async ensureAuthenticatedSelfHosted(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Loopback trust for every discovery-derived fetch below, computed from\n // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).\n const allowLoopback = isLoopbackUrl(baseUrl);\n const issuer = requireIssuer(capabilities);\n const resource = normalizeUrl(baseUrl);\n const dcrTokenKey = `dcr-tokens:${issuer}:${resource}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = await this.loadTokens(dcrTokenKey, issuer);\n\n if (tokens) {\n // 2. Verify token is still valid by calling /oauth/verify\n try {\n const verifyUrl = `${baseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (verifyResponse.ok) {\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token === tokens.accessToken) {\n // Token is still valid with the self-hosted server\n return tokens;\n }\n }\n } catch (_error) {\n // Token verification failed - need to re-authenticate\n }\n\n // Token is expired or invalid\n await this.tokenStore.delete(dcrTokenKey);\n tokens = undefined;\n }\n\n // 3. No valid tokens - perform full DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting self-hosted DCR authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client with self-hosted server...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // For self-hosted mode, verify the token works with /oauth/verify immediately\n try {\n const verifyUrl = `${baseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (!verifyResponse.ok) {\n throw new Error(`DCR token verification failed after authentication: ${verifyResponse.status}`);\n }\n\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token !== tokens.accessToken) {\n throw new Error('DCR server returned different token in verification');\n }\n\n this.logger.debug('✅ DCR token verified with self-hosted server');\n } catch (error) {\n this.logger.error('❌ DCR token verification failed:', error instanceof Error ? error.message : String(error));\n throw new Error('Self-hosted DCR authentication completed but token verification failed');\n }\n\n // Save tokens for future use\n await this.tokenStore.set(dcrTokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');\n\n return tokens;\n }\n\n /** Handles authentication for external (non-self-hosted) OAuth providers. */\n private async ensureAuthenticatedExternal(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // See ensureAuthenticatedSelfHosted - same loopback trust rule.\n const allowLoopback = isLoopbackUrl(baseUrl);\n const issuer = requireIssuer(capabilities);\n const resource = normalizeUrl(baseUrl);\n const tokenKey = `tokens:${issuer}:${resource}`;\n\n // 1. Check for existing tokens\n let tokens = await this.loadTokens(tokenKey, issuer);\n\n if (tokens) {\n // 2. Proactive refresh if token expires within 5 minutes\n if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {\n this.logger.debug('🔄 Refreshing access token...');\n\n try {\n tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback);\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Token refreshed successfully');\n } catch (_error) {\n // Refresh failed - clear tokens and re-authenticate\n this.logger.warn('⚠️ Token refresh failed, re-authenticating...');\n await this.tokenStore.delete(tokenKey);\n tokens = undefined;\n }\n }\n\n if (tokens) {\n return tokens;\n }\n }\n\n // 3. No valid tokens - perform DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting external OAuth authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // Save tokens for future use\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Refreshes an access token using a refresh token.\n * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).\n * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.\n */\n private async refreshTokens(tokens: TokenSet, tokenEndpoint: string | undefined, resource: string, allowLoopback = false): Promise<TokenSet> {\n if (!tokenEndpoint) {\n throw new Error('Token endpoint not available for refresh');\n }\n\n if (!tokens.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n if (!tokens.clientId || !tokens.clientSecret) {\n throw new Error('Client credentials not available for refresh');\n }\n\n return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback);\n }\n\n /**\n * Deletes both stored token families for a server, across every issuer they were bound to.\n * @throws CredentialBindingError if the configured store cannot enumerate keys.\n */\n async deleteTokens(baseUrl: string): Promise<void> {\n const suffix = `:${normalizeUrl(baseUrl)}`;\n if (!this.tokenStore.iterator) {\n throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');\n }\n\n for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)) {\n if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {\n await this.tokenStore.delete(key);\n }\n }\n this.logger.debug(`🗑️ Deleted tokens for ${baseUrl}`);\n }\n\n /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */\n private async loadTokens(key: string, issuer: string): Promise<TokenSet | undefined> {\n const tokens = (await this.tokenStore.get(key)) as TokenSet | undefined;\n if (!tokens) return undefined;\n if (tokens.issuer === issuer) return tokens;\n\n this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');\n await this.tokenStore.delete(key);\n return undefined;\n }\n\n private buildFlowOptions(port: number, capabilities: AuthCapabilities, issuer: string, resource: string, allowLoopback: boolean): OAuthFlowOptions {\n const flowOptions: OAuthFlowOptions = {\n port,\n issuer,\n resource,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n authorizationResponseIssSupported: capabilities.authorizationResponseIssSupported ?? false,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n return flowOptions;\n }\n}\n"],"names":["path","fs","Keyv","KeyvFile","isLoopbackUrl","InteractiveOAuthFlow","normalizeUrl","logger","defaultLogger","DynamicClientRegistrar","REFRESH_BUFFER_MS","CredentialBindingError","Error","message","name","requireIssuer","capabilities","issuer","DcrAuthenticator","detectSelfHostedMode","baseUrl","includes","_error","ensureAuthenticated","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","allowLoopback","resource","dcrTokenKey","tokens","loadTokens","verifyUrl","verifyResponse","fetch","headers","Authorization","accessToken","Connection","ok","verifyData","json","token","tokenStore","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","port","parseInt","URL","redirectUri","startsWith","client","dcrClient","registerClient","flowOptions","buildFlowOptions","oauthFlow","performAuthFlow","clientId","clientSecret","status","error","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","iterator","key","namespace","endsWith","get","headless","pkce","authorizationResponseIssSupported","scopes","options","storePath","join","process","cwd","mkdirSync","dirname","recursive","store","filename"],"mappings":"AAAA;;;CAGC,GAED,OAAOA,UAAU,YAAY;AAC7B,YAAYC,QAAQ,KAAK;AACzB,OAAOC,UAAU,OAAO;AACxB,SAASC,QAAQ,QAAQ,YAAY;AACrC,SAASC,aAA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C,OAAO;YACL,sDAAsD;YACtD,MAAM4C,YAAYvF,KAAKwF,IAAI,CAACC,QAAQC,GAAG,IAAI,UAAU;YAErD,gDAAgD;YAChDzF,GAAG0F,SAAS,CAAC3F,KAAK4F,OAAO,CAACL,YAAY;gBAAEM,WAAW;YAAK;YAExD,IAAI,CAAClD,UAAU,GAAG,IAAIzC,KAAK;gBACzB4F,OAAO,IAAI3F,SAAS;oBAAE4F,UAAUR;gBAAU;YAC5C;QACF;QACA,IAAI,CAAC/B,SAAS,GAAG,IAAI/C;QACrB,IAAI,CAACmD,SAAS,GAAG,IAAIvD;QACrB,IAAI,CAAC6E,QAAQ,GAAGI,QAAQJ,QAAQ,IAAI;QACpC,IAAI,CAAC7B,WAAW,GAAGiC,QAAQjC,WAAW;QACtC,IAAI,CAAC9C,MAAM,IAAG+E,kBAAAA,QAAQ/E,MAAM,cAAd+E,6BAAAA,kBAAkB9E;IAClC;AAwQF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dcr-authenticator.ts"],"sourcesContent":["/**\n * DCR Authenticator\n * Consolidates DCR and OAuth flow logic for MCP HTTP servers\n */\n\nimport path from 'node:path';\nimport * as fs from 'fs';\nimport Keyv from 'keyv';\nimport { KeyvFile } from 'keyv-file';\nimport { isLoopbackUrl } from '../auth/discovery-fetch.ts';\nimport { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.ts';\nimport type { AuthCapabilities, OAuthFlowOptions, TokenSet } from '../auth/types.ts';\nimport { extractBaseUrl, normalizeUrl } from '../lib/url-utils.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { DynamicClientRegistrar } from './dynamic-client-registrar.ts';\n\n/**\n * DcrAuthenticator configuration options\n */\nexport interface DcrAuthenticatorOptions {\n /** Custom Keyv store (for testing) - if not provided, uses default ~/.mcpeasy/tokens.json */\n tokenStore?: Keyv;\n /** Headless mode (don't open browser) */\n headless?: boolean;\n /** Required redirect URI for OAuth callback */\n redirectUri: string;\n /** Optional logger for debug output (defaults to singleton logger) */\n logger?: Logger;\n}\n\n/**\n * Buffer time before token expiry to trigger proactive refresh (5 minutes)\n */\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/** Raised when a credential cannot be bound to, or looked up by, an issuer. */\nclass CredentialBindingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CredentialBindingError';\n }\n}\n\n/**\n * The issuer credentials are keyed by, so they can never be presented to a\n * different authorization server even when the resource keeps its URL (SEP-2352).\n */\nfunction requireIssuer(capabilities: AuthCapabilities): string {\n if (!capabilities.issuer) {\n throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');\n }\n return capabilities.issuer;\n}\n\n/**\n * DcrAuthenticator manages authentication for MCP HTTP servers\n * Handles DCR registration, OAuth flows, and token management\n */\nexport class DcrAuthenticator {\n private tokenStore: Keyv;\n private dcrClient: DynamicClientRegistrar;\n private oauthFlow: InteractiveOAuthFlow;\n private headless: boolean;\n private redirectUri: string;\n private logger: Logger;\n\n constructor(options: DcrAuthenticatorOptions) {\n if (options.tokenStore) {\n this.tokenStore = options.tokenStore;\n } else {\n // Default CLI store in .mcp-z directory (per-project)\n const storePath = path.join(process.cwd(), '.mcp-z', 'tokens.json');\n\n // Ensure directory exists before creating store\n fs.mkdirSync(path.dirname(storePath), { recursive: true });\n\n this.tokenStore = new Keyv({\n store: new KeyvFile({ filename: storePath }),\n });\n }\n this.dcrClient = new DynamicClientRegistrar();\n this.oauthFlow = new InteractiveOAuthFlow();\n this.headless = options.headless || false;\n this.redirectUri = options.redirectUri;\n this.logger = options.logger ?? defaultLogger;\n }\n\n /**\n * Detect if server is self-hosted DCR (vs external OAuth provider)\n * Self-hosted servers have their own OAuth endpoints and manage token storage\n */\n private async detectSelfHostedMode(mcpServerUrl: string): Promise<boolean> {\n try {\n // Self-hosted DCR servers typically run their own OAuth server\n // Check if this is a self-hosted instance by testing OAuth metadata\n // For now, assume self-hosted if the URL matches common localhost patterns\n // TODO: Implement proper self-hosted detection logic\n return mcpServerUrl.includes('localhost') || mcpServerUrl.includes('127.0.0.1');\n } catch (_error) {\n return false; // Assume external mode if detection fails\n }\n }\n\n /**\n * Ensure server is authenticated, performing DCR and OAuth if needed\n * Proactively refreshes tokens if they're within 5 minutes of expiry\n *\n * @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,\n * with its path intact (`https://example.com/mcp`). Not a deployment root:\n * the path is what identifies the resource an issued token is bound to.\n * @param capabilities - Auth capabilities from .well-known endpoint\n * @returns Valid token set ready to use\n *\n * @throws Error if authentication fails\n *\n * @example\n * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });\n * const tokens = await authenticator.ensureAuthenticated(\n * 'https://example.com/mcp',\n * capabilities\n * );\n */\n async ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Auto-detect server mode\n const isSelfHosted = await this.detectSelfHostedMode(mcpServerUrl);\n\n if (isSelfHosted) {\n return this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities);\n }\n return this.ensureAuthenticatedExternal(mcpServerUrl, capabilities);\n }\n\n /**\n * The three things a server URL is used for here, kept apart on purpose.\n *\n * They were one value once, and collapsing them is what sent an authorization\n * server the wrong audience: `resource` was derived from the deployment root,\n * so a server at `https://host/mcp` was asked to mint a token for\n * `https://host`, and any server that validates the indicator answered\n * `invalid_target`.\n *\n * - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a\n * trailing `/mcp` comes off.\n * - `resource` is the RFC 8707 audience. The resource server names itself in\n * its RFC 9728 metadata; that name wins. Only when no such document exists\n * do we fall back to the URL we were configured with.\n * - `storeKey` identifies the credential locally. It stays the configured URL\n * rather than the discovered `resource`, so it can be computed without a\n * network round trip - `deleteTokens` has only the URL to work from.\n */\n private resolveUrls(mcpServerUrl: string, capabilities: AuthCapabilities): { serverBaseUrl: string; resource: string; storeKey: string } {\n const storeKey = normalizeUrl(mcpServerUrl);\n return { serverBaseUrl: extractBaseUrl(mcpServerUrl), resource: capabilities.resource ?? storeKey, storeKey };\n }\n\n /**\n * Handle authentication for self-hosted DCR servers\n * Self-hosted servers manage their own token storage via /oauth/verify\n */\n private async ensureAuthenticatedSelfHosted(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Loopback trust for every discovery-derived fetch below, computed from\n // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { serverBaseUrl, resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const dcrTokenKey = `dcr-tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = await this.loadTokens(dcrTokenKey, issuer);\n\n if (tokens) {\n // 2. Verify token is still valid by calling /oauth/verify\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (verifyResponse.ok) {\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token === tokens.accessToken) {\n // Token is still valid with the self-hosted server\n return tokens;\n }\n }\n } catch (_error) {\n // Token verification failed - need to re-authenticate\n }\n\n // Token is expired or invalid\n await this.tokenStore.delete(dcrTokenKey);\n tokens = undefined;\n }\n\n // 3. No valid tokens - perform full DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting self-hosted DCR authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client with self-hosted server...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // For self-hosted mode, verify the token works with /oauth/verify immediately\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (!verifyResponse.ok) {\n throw new Error(`DCR token verification failed after authentication: ${verifyResponse.status}`);\n }\n\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token !== tokens.accessToken) {\n throw new Error('DCR server returned different token in verification');\n }\n\n this.logger.debug('✅ DCR token verified with self-hosted server');\n } catch (error) {\n this.logger.error('❌ DCR token verification failed:', error instanceof Error ? error.message : String(error));\n throw new Error('Self-hosted DCR authentication completed but token verification failed');\n }\n\n // Save tokens for future use\n await this.tokenStore.set(dcrTokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');\n\n return tokens;\n }\n\n /** Handles authentication for external (non-self-hosted) OAuth providers. */\n private async ensureAuthenticatedExternal(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // See ensureAuthenticatedSelfHosted - same loopback trust rule.\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const tokenKey = `tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing tokens\n let tokens = await this.loadTokens(tokenKey, issuer);\n\n if (tokens) {\n // 2. Proactive refresh if token expires within 5 minutes\n if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {\n this.logger.debug('🔄 Refreshing access token...');\n\n try {\n tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback);\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Token refreshed successfully');\n } catch (_error) {\n // Refresh failed - clear tokens and re-authenticate\n this.logger.warn('⚠️ Token refresh failed, re-authenticating...');\n await this.tokenStore.delete(tokenKey);\n tokens = undefined;\n }\n }\n\n if (tokens) {\n return tokens;\n }\n }\n\n // 3. No valid tokens - perform DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting external OAuth authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // Save tokens for future use\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Refreshes an access token using a refresh token.\n * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).\n * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.\n */\n private async refreshTokens(tokens: TokenSet, tokenEndpoint: string | undefined, resource: string, allowLoopback = false): Promise<TokenSet> {\n if (!tokenEndpoint) {\n throw new Error('Token endpoint not available for refresh');\n }\n\n if (!tokens.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n if (!tokens.clientId || !tokens.clientSecret) {\n throw new Error('Client credentials not available for refresh');\n }\n\n return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback);\n }\n\n /**\n * Deletes both stored token families for a server, across every issuer they were bound to.\n *\n * Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}\n * was given - keys are built from the configured URL, never from the discovered\n * RFC 8707 resource, precisely so this can find them without doing discovery.\n *\n * @throws CredentialBindingError if the configured store cannot enumerate keys.\n */\n async deleteTokens(mcpServerUrl: string): Promise<void> {\n const suffix = `:${normalizeUrl(mcpServerUrl)}`;\n if (!this.tokenStore.iterator) {\n throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');\n }\n\n for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)) {\n if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {\n await this.tokenStore.delete(key);\n }\n }\n this.logger.debug(`🗑️ Deleted tokens for ${mcpServerUrl}`);\n }\n\n /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */\n private async loadTokens(key: string, issuer: string): Promise<TokenSet | undefined> {\n const tokens = (await this.tokenStore.get(key)) as TokenSet | undefined;\n if (!tokens) return undefined;\n if (tokens.issuer === issuer) return tokens;\n\n this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');\n await this.tokenStore.delete(key);\n return undefined;\n }\n\n private buildFlowOptions(port: number, capabilities: AuthCapabilities, issuer: string, resource: string, allowLoopback: boolean): OAuthFlowOptions {\n const flowOptions: OAuthFlowOptions = {\n port,\n issuer,\n resource,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n authorizationResponseIssSupported: capabilities.authorizationResponseIssSupported ?? false,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n return flowOptions;\n }\n}\n"],"names":["path","fs","Keyv","KeyvFile","isLoopbackUrl","InteractiveOAuthFlow","extractBaseUrl","normalizeUrl","logger","defaultLogger","DynamicClientRegistrar","REFRESH_BUFFER_MS","CredentialBindingError","Error","message","name","requireIssuer","capabilities","issuer","DcrAuthenticator","detectSelfHostedMode","mcpServerUrl","includes","_error","ensureAuthenticated","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","resolveUrls","storeKey","serverBaseUrl","resource","allowLoopback","dcrTokenKey","tokens","loadTokens","verifyUrl","verifyResponse","fetch","headers","Authorization","accessToken","Connection","ok","verifyData","json","token","tokenStore","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","port","parseInt","URL","redirectUri","startsWith","client","dcrClient","registerClient","flowOptions","buildFlowOptions","oauthFlow","performAuthFlow","clientId","clientSecret","status","error","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","iterator","key","namespace","endsWith","get","headless","pkce","authorizationResponseIssSupported","scopes","options","storePath","join","process","cwd","mkdirSync","dirname","recursive","store","filename"],"mappings":"AAAA;;;CAGC,GAED,OAAOA,UAAU,YAAY;AAC7B,YAAYC,QAAQ,KAAK;AACzB,OAAOC,UAAU,OAAO;AACxB,SAASC,QAAQ,QAAQ,YAAY;AACrC,SAASC,aAAa,QAAQ,6BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,oCAAoC;AAEzE,SAASC,cAAc,EAAEC,YAAY,QAAQ,sBAAsB;AACnE,SAASC,UAAUC,aAAa,QAAqB,qBAAqB;AAC1E,SAASC,sBAAsB,QAAQ,gCAAgC;AAgBvE;;CAEC,GACD,MAAMC,oBAAoB,IAAI,KAAK;AAEnC,6EAA6E,GAC7E,IAAA,AAAMC,yBAAN,MAAMA,+BAA+BC;IACnC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA;QACN,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA;;;CAGC,GACD,SAASC,cAAcC,YAA8B;IAC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YAAY3F,KAAK4F,IAAI,CAACC,QAAQC,GAAG,IAAI,UAAU;YAErD,gDAAgD;YAChD7F,GAAG8F,SAAS,CAAC/F,KAAKgG,OAAO,CAACL,YAAY;gBAAEM,WAAW;YAAK;YAExD,IAAI,CAAClD,UAAU,GAAG,IAAI7C,KAAK;gBACzBgG,OAAO,IAAI/F,SAAS;oBAAEgG,UAAUR;gBAAU;YAC5C;QACF;QACA,IAAI,CAAC/B,SAAS,GAAG,IAAIlD;QACrB,IAAI,CAACsD,SAAS,GAAG,IAAI3D;QACrB,IAAI,CAACiF,QAAQ,GAAGI,QAAQJ,QAAQ,IAAI;QACpC,IAAI,CAAC7B,WAAW,GAAGiC,QAAQjC,WAAW;QACtC,IAAI,CAACjD,MAAM,IAAGkF,kBAAAA,QAAQlF,MAAM,cAAdkF,6BAAAA,kBAAkBjF;IAClC;AAsSF"}
@@ -1,2 +1,19 @@
1
1
  export declare function normalizeUrl(input: string): string;
2
2
  export declare function joinWellKnown(baseUrl: string, suffix: string): string;
3
+ /**
4
+ * Extract the "server base" - where a server's own endpoints live, NOT its identity.
5
+ *
6
+ * The `/mcp` segment names the protocol endpoint; everything before it is the
7
+ * deployment root that `/oauth/verify` and friends hang off. Stripping it is
8
+ * right for building those URLs and wrong for anything that identifies the
9
+ * server: an RFC 8707 `resource` indicator or a credential store key must use
10
+ * the full URL, because the stripped form names a different resource (or none).
11
+ *
12
+ * Original shape by removing a trailing `/mcp` path segment if present.
13
+ * Examples:
14
+ * - https://example.com/mcp -> https://example.com
15
+ * - https://example.com/sheets/mcp -> https://example.com/sheets
16
+ * - https://example.com/sheets/mcp/ -> https://example.com/sheets
17
+ * - https://example.com/sheets -> https://example.com/sheets
18
+ */
19
+ export declare function extractBaseUrl(mcpUrl: string): string;
@@ -12,3 +12,35 @@ export function normalizeUrl(input) {
12
12
  export function joinWellKnown(baseUrl, suffix) {
13
13
  return `${normalizeUrl(baseUrl)}${suffix}`;
14
14
  }
15
+ /**
16
+ * Extract the "server base" - where a server's own endpoints live, NOT its identity.
17
+ *
18
+ * The `/mcp` segment names the protocol endpoint; everything before it is the
19
+ * deployment root that `/oauth/verify` and friends hang off. Stripping it is
20
+ * right for building those URLs and wrong for anything that identifies the
21
+ * server: an RFC 8707 `resource` indicator or a credential store key must use
22
+ * the full URL, because the stripped form names a different resource (or none).
23
+ *
24
+ * Original shape by removing a trailing `/mcp` path segment if present.
25
+ * Examples:
26
+ * - https://example.com/mcp -> https://example.com
27
+ * - https://example.com/sheets/mcp -> https://example.com/sheets
28
+ * - https://example.com/sheets/mcp/ -> https://example.com/sheets
29
+ * - https://example.com/sheets -> https://example.com/sheets
30
+ */ export function extractBaseUrl(mcpUrl) {
31
+ const url = new URL(mcpUrl);
32
+ // Ignore query/hash for base URL purposes
33
+ url.search = '';
34
+ url.hash = '';
35
+ // Normalize path segments (removes empty segments from leading/trailing slashes)
36
+ const segments = url.pathname.split('/').filter(Boolean);
37
+ // If last segment is exactly "mcp", drop it
38
+ if (segments[segments.length - 1] === 'mcp') {
39
+ segments.pop();
40
+ }
41
+ // Rebuild pathname; empty means root
42
+ url.pathname = segments.length ? `/${segments.join('/')}` : '';
43
+ // Return without trailing slash (except root origin)
44
+ const out = url.origin + url.pathname;
45
+ return out === url.origin ? out : out.replace(/\/+$/, '');
46
+ }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/lib/url-utils.ts"],"sourcesContent":["export function normalizeUrl(input: string): string {\n try {\n const url = new URL(input);\n url.search = '';\n url.hash = '';\n // Strip after joining: assigning an empty pathname puts the '/' straight back.\n return (url.origin + url.pathname).replace(/\\/+$/, '');\n } catch {\n return input.replace(/\\/+$/, '');\n }\n}\n\nexport function joinWellKnown(baseUrl: string, suffix: string): string {\n return `${normalizeUrl(baseUrl)}${suffix}`;\n}\n"],"names":["normalizeUrl","input","url","URL","search","hash","origin","pathname","replace","joinWellKnown","baseUrl","suffix"],"mappings":"AAAA,OAAO,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,MAAMC,MAAM,IAAIC,IAAIF;QACpBC,IAAIE,MAAM,GAAG;QACbF,IAAIG,IAAI,GAAG;QACX,+EAA+E;QAC/E,OAAO,AAACH,CAAAA,IAAII,MAAM,GAAGJ,IAAIK,QAAQ,AAAD,EAAGC,OAAO,CAAC,QAAQ;IACrD,EAAE,OAAM;QACN,OAAOP,MAAMO,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEA,OAAO,SAASC,cAAcC,OAAe,EAAEC,MAAc;IAC3D,OAAO,GAAGX,aAAaU,WAAWC,QAAQ;AAC5C"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/lib/url-utils.ts"],"sourcesContent":["export function normalizeUrl(input: string): string {\n try {\n const url = new URL(input);\n url.search = '';\n url.hash = '';\n // Strip after joining: assigning an empty pathname puts the '/' straight back.\n return (url.origin + url.pathname).replace(/\\/+$/, '');\n } catch {\n return input.replace(/\\/+$/, '');\n }\n}\n\nexport function joinWellKnown(baseUrl: string, suffix: string): string {\n return `${normalizeUrl(baseUrl)}${suffix}`;\n}\n\n/**\n * Extract the \"server base\" - where a server's own endpoints live, NOT its identity.\n *\n * The `/mcp` segment names the protocol endpoint; everything before it is the\n * deployment root that `/oauth/verify` and friends hang off. Stripping it is\n * right for building those URLs and wrong for anything that identifies the\n * server: an RFC 8707 `resource` indicator or a credential store key must use\n * the full URL, because the stripped form names a different resource (or none).\n *\n * Original shape by removing a trailing `/mcp` path segment if present.\n * Examples:\n * - https://example.com/mcp -> https://example.com\n * - https://example.com/sheets/mcp -> https://example.com/sheets\n * - https://example.com/sheets/mcp/ -> https://example.com/sheets\n * - https://example.com/sheets -> https://example.com/sheets\n */\nexport function extractBaseUrl(mcpUrl: string): string {\n const url = new URL(mcpUrl);\n\n // Ignore query/hash for base URL purposes\n url.search = '';\n url.hash = '';\n\n // Normalize path segments (removes empty segments from leading/trailing slashes)\n const segments = url.pathname.split('/').filter(Boolean);\n\n // If last segment is exactly \"mcp\", drop it\n if (segments[segments.length - 1] === 'mcp') {\n segments.pop();\n }\n\n // Rebuild pathname; empty means root\n url.pathname = segments.length ? `/${segments.join('/')}` : '';\n\n // Return without trailing slash (except root origin)\n const out = url.origin + url.pathname;\n return out === url.origin ? out : out.replace(/\\/+$/, '');\n}\n"],"names":["normalizeUrl","input","url","URL","search","hash","origin","pathname","replace","joinWellKnown","baseUrl","suffix","extractBaseUrl","mcpUrl","segments","split","filter","Boolean","length","pop","join","out"],"mappings":"AAAA,OAAO,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,MAAMC,MAAM,IAAIC,IAAIF;QACpBC,IAAIE,MAAM,GAAG;QACbF,IAAIG,IAAI,GAAG;QACX,+EAA+E;QAC/E,OAAO,AAACH,CAAAA,IAAII,MAAM,GAAGJ,IAAIK,QAAQ,AAAD,EAAGC,OAAO,CAAC,QAAQ;IACrD,EAAE,OAAM;QACN,OAAOP,MAAMO,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEA,OAAO,SAASC,cAAcC,OAAe,EAAEC,MAAc;IAC3D,OAAO,GAAGX,aAAaU,WAAWC,QAAQ;AAC5C;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,eAAeC,MAAc;IAC3C,MAAMX,MAAM,IAAIC,IAAIU;IAEpB,0CAA0C;IAC1CX,IAAIE,MAAM,GAAG;IACbF,IAAIG,IAAI,GAAG;IAEX,iFAAiF;IACjF,MAAMS,WAAWZ,IAAIK,QAAQ,CAACQ,KAAK,CAAC,KAAKC,MAAM,CAACC;IAEhD,4CAA4C;IAC5C,IAAIH,QAAQ,CAACA,SAASI,MAAM,GAAG,EAAE,KAAK,OAAO;QAC3CJ,SAASK,GAAG;IACd;IAEA,qCAAqC;IACrCjB,IAAIK,QAAQ,GAAGO,SAASI,MAAM,GAAG,CAAC,CAAC,EAAEJ,SAASM,IAAI,CAAC,MAAM,GAAG;IAE5D,qDAAqD;IACrD,MAAMC,MAAMnB,IAAII,MAAM,GAAGJ,IAAIK,QAAQ;IACrC,OAAOc,QAAQnB,IAAII,MAAM,GAAGe,MAAMA,IAAIb,OAAO,CAAC,QAAQ;AACxD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcp-z/client",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "Programmatic MCP client library for Node.js - connect, discover, and call tools on Model Context Protocol servers.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -73,7 +73,6 @@
73
73
  "@types/express": "^5.0.6",
74
74
  "@types/mocha": "^10.0.10",
75
75
  "@types/node": "^26.2.0",
76
- "dotenv": "^17.2.3",
77
76
  "express": "^5.0.0",
78
77
  "json-schema-to-typescript": "^16.0.0",
79
78
  "node-version-use": "^2.4.7",