@mcp-z/client 1.2.1 → 1.3.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 (95) hide show
  1. package/README.md +22 -0
  2. package/dist/cjs/auth/capability-discovery.js +16 -6
  3. package/dist/cjs/auth/capability-discovery.js.map +1 -1
  4. package/dist/cjs/auth/discovery-fetch.d.cts +22 -2
  5. package/dist/cjs/auth/discovery-fetch.d.ts +22 -2
  6. package/dist/cjs/auth/discovery-fetch.js +440 -124
  7. package/dist/cjs/auth/discovery-fetch.js.map +1 -1
  8. package/dist/cjs/auth/interactive-oauth-flow.d.cts +9 -2
  9. package/dist/cjs/auth/interactive-oauth-flow.d.ts +9 -2
  10. package/dist/cjs/auth/interactive-oauth-flow.js +29 -11
  11. package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
  12. package/dist/cjs/auth/oauth-callback-listener.js +4 -0
  13. package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
  14. package/dist/cjs/auth/types.d.cts +29 -4
  15. package/dist/cjs/auth/types.d.ts +29 -4
  16. package/dist/cjs/auth/types.js.map +1 -1
  17. package/dist/cjs/client-helpers.d.cts +5 -6
  18. package/dist/cjs/client-helpers.d.ts +5 -6
  19. package/dist/cjs/client-helpers.js +8 -8
  20. package/dist/cjs/client-helpers.js.map +1 -1
  21. package/dist/cjs/connection/connect-client.d.cts +12 -11
  22. package/dist/cjs/connection/connect-client.d.ts +12 -11
  23. package/dist/cjs/connection/connect-client.js +31 -47
  24. package/dist/cjs/connection/connect-client.js.map +1 -1
  25. package/dist/cjs/connection/existing-process-transport.d.cts +1 -2
  26. package/dist/cjs/connection/existing-process-transport.d.ts +1 -2
  27. package/dist/cjs/connection/existing-process-transport.js +3 -3
  28. package/dist/cjs/connection/existing-process-transport.js.map +1 -1
  29. package/dist/cjs/dcr/dcr-authenticator.d.cts +36 -5
  30. package/dist/cjs/dcr/dcr-authenticator.d.ts +36 -5
  31. package/dist/cjs/dcr/dcr-authenticator.js +473 -62
  32. package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
  33. package/dist/cjs/dcr/dynamic-client-registrar.d.cts +2 -2
  34. package/dist/cjs/dcr/dynamic-client-registrar.d.ts +2 -2
  35. package/dist/cjs/dcr/dynamic-client-registrar.js +10 -11
  36. package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
  37. package/dist/cjs/index.d.cts +2 -0
  38. package/dist/cjs/index.d.ts +2 -0
  39. package/dist/cjs/index.js +8 -2
  40. package/dist/cjs/index.js.map +1 -1
  41. package/dist/cjs/lib/url-utils.d.cts +17 -0
  42. package/dist/cjs/lib/url-utils.d.ts +17 -0
  43. package/dist/cjs/lib/url-utils.js +22 -2
  44. package/dist/cjs/lib/url-utils.js.map +1 -1
  45. package/dist/cjs/response-wrappers.d.cts +1 -1
  46. package/dist/cjs/response-wrappers.d.ts +1 -1
  47. package/dist/cjs/response-wrappers.js.map +1 -1
  48. package/dist/cjs/search/search.d.cts +1 -1
  49. package/dist/cjs/search/search.d.ts +1 -1
  50. package/dist/cjs/search/search.js.map +1 -1
  51. package/dist/esm/auth/capability-discovery.js +16 -6
  52. package/dist/esm/auth/capability-discovery.js.map +1 -1
  53. package/dist/esm/auth/discovery-fetch.d.ts +22 -2
  54. package/dist/esm/auth/discovery-fetch.js +234 -54
  55. package/dist/esm/auth/discovery-fetch.js.map +1 -1
  56. package/dist/esm/auth/interactive-oauth-flow.d.ts +9 -2
  57. package/dist/esm/auth/interactive-oauth-flow.js +28 -10
  58. package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
  59. package/dist/esm/auth/oauth-callback-listener.js +4 -0
  60. package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
  61. package/dist/esm/auth/types.d.ts +29 -4
  62. package/dist/esm/auth/types.js.map +1 -1
  63. package/dist/esm/client-helpers.d.ts +5 -6
  64. package/dist/esm/client-helpers.js +8 -8
  65. package/dist/esm/client-helpers.js.map +1 -1
  66. package/dist/esm/connection/connect-client.d.ts +12 -11
  67. package/dist/esm/connection/connect-client.js +32 -38
  68. package/dist/esm/connection/connect-client.js.map +1 -1
  69. package/dist/esm/connection/existing-process-transport.d.ts +1 -2
  70. package/dist/esm/connection/existing-process-transport.js +1 -1
  71. package/dist/esm/connection/existing-process-transport.js.map +1 -1
  72. package/dist/esm/dcr/dcr-authenticator.d.ts +36 -5
  73. package/dist/esm/dcr/dcr-authenticator.js +129 -58
  74. package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
  75. package/dist/esm/dcr/dynamic-client-registrar.d.ts +2 -2
  76. package/dist/esm/dcr/dynamic-client-registrar.js +7 -6
  77. package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
  78. package/dist/esm/index.d.ts +2 -0
  79. package/dist/esm/index.js +4 -1
  80. package/dist/esm/index.js.map +1 -1
  81. package/dist/esm/lib/url-utils.d.ts +17 -0
  82. package/dist/esm/lib/url-utils.js +34 -2
  83. package/dist/esm/lib/url-utils.js.map +1 -1
  84. package/dist/esm/response-wrappers.d.ts +1 -1
  85. package/dist/esm/response-wrappers.js.map +1 -1
  86. package/dist/esm/search/search.d.ts +1 -1
  87. package/dist/esm/search/search.js.map +1 -1
  88. package/package.json +13 -13
  89. package/dist/cjs/monkey-patches.d.cts +0 -6
  90. package/dist/cjs/monkey-patches.d.ts +0 -6
  91. package/dist/cjs/monkey-patches.js +0 -233
  92. package/dist/cjs/monkey-patches.js.map +0 -1
  93. package/dist/esm/monkey-patches.d.ts +0 -6
  94. package/dist/esm/monkey-patches.js +0 -32
  95. package/dist/esm/monkey-patches.js.map +0 -1
@@ -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, TokenSet } from '../auth/types.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/**\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 dcrTokenKey = `dcr-tokens:${baseUrl}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = (await this.tokenStore.get(dcrTokenKey)) as TokenSet | undefined;\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: { port: number; headless: boolean; scopes?: string[]; redirectUri: string; pkce: boolean; logger: Logger; allowLoopback: boolean } = {\n port,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\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);\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 tokenKey = `tokens:${baseUrl}`;\n\n // 1. Check for existing tokens\n let tokens = (await this.tokenStore.get(tokenKey)) as TokenSet | undefined;\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, allowLoopback);\n await this.tokenStore.set(tokenKey, tokens);\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: { port: number; headless: boolean; scopes?: string[]; redirectUri: string; pkce: boolean; logger: Logger; allowLoopback: boolean } = {\n port,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\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);\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 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, 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, allowLoopback);\n }\n\n /**\n * Delete stored tokens for a server\n */\n async deleteTokens(baseUrl: string): Promise<void> {\n // Both families this class writes: `tokens:` from the external OAuth path\n // (line ~213) and `dcr-tokens:` from the self-hosted DCR path (line ~119).\n // Deleting only one leaves a usable credential behind for a caller that\n // believes it revoked them.\n await Promise.all([this.tokenStore.delete(`tokens:${baseUrl}`), this.tokenStore.delete(`dcr-tokens:${baseUrl}`)]);\n this.logger.debug(`🗑️ Deleted tokens for ${baseUrl}`);\n }\n}\n"],"names":["DcrAuthenticator","REFRESH_BUFFER_MS","options","tokenStore","storePath","path","join","process","cwd","fs","mkdirSync","dirname","recursive","Keyv","store","KeyvFile","filename","dcrClient","DynamicClientRegistrar","oauthFlow","InteractiveOAuthFlow","headless","redirectUri","logger","defaultLogger","detectSelfHostedMode","baseUrl","includes","_error","ensureAuthenticated","capabilities","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","allowLoopback","dcrTokenKey","tokens","verifyUrl","verifyResponse","verifyData","port","client","flowOptions","error","isLoopbackUrl","get","fetch","headers","Authorization","accessToken","Connection","ok","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","Error","debug","parseInt","URL","startsWith","registerClient","pkce","scopes","performAuthFlow","clientId","clientSecret","status","message","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","Promise","all"],"mappings":"AAAA;;;CAGC;;;;+BAmCYA;;;eAAAA;;;+DAjCI;0DACG;2DACH;wBACQ;gCACK;sCACO;wBAEgB;wCACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBvC;;CAEC,GACD,IAAMC,oBAAoB,IAAI,KAAK;AAM5B,IAAA,AAAMD,iCAAN;;aAAMA,iBAQCE,OAAgC;gCARjCF;YA0BKE;QAjBd,IAAIA,QAAQC,UAAU,EAAE;YACtB,IAAI,CAACA,UAAU,GAAGD,QAAQC,UAAU;QACtC,OAAO;YACL,sDAAsD;YACtD,IAAMC,YAAYC,iBAAI,CAACC,IAAI,CAACC,QAAQC,GAAG,IAAI,UAAU;YAErD,gDAAgD;YAChDC,IAAGC,SAAS,CAACL,iBAAI,CAACM,OAAO,CAACP,YAAY;gBAAEQ,WAAW;YAAK;YAExD,IAAI,CAACT,UAAU,GAAG,IAAIU,aAAI,CAAC;gBACzBC,OAAO,IAAIC,kBAAQ,CAAC;oBAAEC,UAAUZ;gBAAU;YAC5C;QACF;QACA,IAA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;;;;QACT;;IAEA;;GAEC,GACD,OAAM+C,YAOL,GAPD,SAAMA,aAAavD,OAAe;;;;;wBAChC,0EAA0E;wBAC1E,2EAA2E;wBAC3E,wEAAwE;wBACxE,4BAA4B;wBAC5B;;4BAAMwD,QAAQC,GAAG;gCAAE,IAAI,CAAChF,UAAU,CAACmD,MAAM,CAAC,AAAC,UAAiB,OAAR5B;gCAAY,IAAI,CAACvB,UAAU,CAACmD,MAAM,CAAC,AAAC,cAAqB,OAAR5B;;;;wBAArG;wBACA,IAAI,CAACH,MAAM,CAACqC,KAAK,CAAC,AAAC,qCAAkC,OAARlC;;;;;;QAC/C;;WA9QW1B"}
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":["DcrAuthenticator","REFRESH_BUFFER_MS","CredentialBindingError","message","name","Error","requireIssuer","capabilities","issuer","options","tokenStore","storePath","path","join","process","cwd","fs","mkdirSync","dirname","recursive","Keyv","store","KeyvFile","filename","dcrClient","DynamicClientRegistrar","oauthFlow","InteractiveOAuthFlow","headless","redirectUri","logger","defaultLogger","detectSelfHostedMode","mcpServerUrl","includes","_error","ensureAuthenticated","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","resolveUrls","storeKey","normalizeUrl","serverBaseUrl","extractBaseUrl","resource","allowLoopback","dcrTokenKey","tokens","verifyUrl","verifyResponse","verifyData","port","client","flowOptions","error","isLoopbackUrl","loadTokens","fetch","headers","Authorization","accessToken","Connection","ok","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","parseInt","URL","startsWith","registerClient","buildFlowOptions","performAuthFlow","clientId","clientSecret","status","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","key","iterator","namespace","endsWith","get","pkce","authorizationResponseIssSupported","scopes"],"mappings":"AAAA;;;CAGC;;;;+BAuDYA;;;eAAAA;;;+DArDI;0DACG;2DACH;wBACQ;gCACK;sCACO;0BAEQ;wBACQ;wCACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBvC;;CAEC,GACD,IAAMC,oBAAoB,IAAI,KAAK;AAEnC,6EAA6E,GAC7E,IAAA,AAAMC,uCAAN;;cAAMA;aAAAA,uBACQC,OAAe;gCADvBD;;gBAEF,kBAFEA;YAE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;YACvBC,aAAa,IAAI,CAACA,WAAW;YAC7BoE,MAAM;YACNnE,QAAQ,IAAI,CAACA,MAAM;YACnBgB,eAAAA;YACAoD,iCAAiC,GAAE3F,kDAAAA,aAAa2F,iCAAiC,cAA9C3F,6DAAAA,kDAAkD;QACvF;QACA,IAAIA,aAAa4F,MAAM,EAAE;YACvB7C,YAAY6C,MAAM,GAAG5F,aAAa4F,MAAM;QAC1C;QACA,OAAO7C;IACT;WAhUWtD"}
@@ -9,9 +9,9 @@ export declare class DynamicClientRegistrar {
9
9
  * Registers a new OAuth client with the authorization server (RFC 7591).
10
10
  *
11
11
  * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
12
- * @param options - Registration options (client name, redirect URI, loopback trust).
12
+ * @param options - Registration options (redirect URI, client name, loopback trust).
13
13
  * @returns Client credentials (client ID and secret).
14
14
  * @throws Error if registration fails or the server returns an error.
15
15
  */
16
- registerClient(registrationEndpoint: string, options?: DcrRegistrationOptions): Promise<ClientCredentials>;
16
+ registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials>;
17
17
  }
@@ -9,9 +9,9 @@ export declare class DynamicClientRegistrar {
9
9
  * Registers a new OAuth client with the authorization server (RFC 7591).
10
10
  *
11
11
  * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
12
- * @param options - Registration options (client name, redirect URI, loopback trust).
12
+ * @param options - Registration options (redirect URI, client name, loopback trust).
13
13
  * @returns Client credentials (client ID and secret).
14
14
  * @throws Error if registration fails or the server returns an error.
15
15
  */
16
- registerClient(registrationEndpoint: string, options?: DcrRegistrationOptions): Promise<ClientCredentials>;
16
+ registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials>;
17
17
  }
@@ -150,23 +150,19 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
150
150
  * Registers a new OAuth client with the authorization server (RFC 7591).
151
151
  *
152
152
  * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
153
- * @param options - Registration options (client name, redirect URI, loopback trust).
153
+ * @param options - Registration options (redirect URI, client name, loopback trust).
154
154
  * @returns Client credentials (client ID and secret).
155
155
  * @throws Error if registration fails or the server returns an error.
156
- */ _proto.registerClient = function registerClient(_0) {
157
- return _async_to_generator(function(registrationEndpoint) {
158
- var options, _options_allowLoopback, requestBody, response, errorText, data, credentials;
159
- var _arguments = arguments;
156
+ */ _proto.registerClient = function registerClient(registrationEndpoint, options) {
157
+ return _async_to_generator(function() {
158
+ var _options_allowLoopback, requestBody, response, errorText, data, credentials;
160
159
  return _ts_generator(this, function(_state) {
161
160
  switch(_state.label){
162
161
  case 0:
163
- options = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : {};
164
162
  requestBody = {
165
163
  client_name: options.clientName || '@mcp-z/client',
166
- redirect_uris: options.redirectUri ? [
164
+ redirect_uris: [
167
165
  options.redirectUri
168
- ] : [
169
- 'http://localhost:3000/callback'
170
166
  ],
171
167
  grant_types: [
172
168
  'authorization_code',
@@ -175,7 +171,10 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
175
171
  response_types: [
176
172
  'code'
177
173
  ],
178
- token_endpoint_auth_method: 'client_secret_basic'
174
+ token_endpoint_auth_method: 'client_secret_basic',
175
+ // The callback listener always binds an OS-assigned loopback port, so the
176
+ // redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).
177
+ application_type: 'native'
179
178
  };
180
179
  return [
181
180
  4,
@@ -227,7 +226,7 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
227
226
  ];
228
227
  }
229
228
  });
230
- }).apply(this, arguments);
229
+ })();
231
230
  };
232
231
  return DynamicClientRegistrar;
233
232
  }();
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dynamic-client-registrar.ts"],"sourcesContent":["/**\n * Dynamic Client Registration (DCR) Client\n * Implements RFC 7591 for OAuth client registration\n */\n\nimport { discoveryFetch } from '../auth/discovery-fetch.ts';\nimport type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.ts';\n\n/** DCR Registration Request (RFC 7591) */\ninterface DcrRegistrationRequest {\n client_name?: string;\n redirect_uris?: string[];\n grant_types?: string[];\n response_types?: string[];\n token_endpoint_auth_method?: string;\n}\n\n/** DCR Registration Response (RFC 7591) */\ninterface DcrRegistrationResponse {\n client_id: string;\n client_secret?: string;\n client_id_issued_at?: number;\n client_secret_expires_at?: number;\n}\n\n/** Handles Dynamic Client Registration with OAuth servers. */\nexport class DynamicClientRegistrar {\n /**\n * Registers a new OAuth client with the authorization server (RFC 7591).\n *\n * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.\n * @param options - Registration options (client name, redirect URI, loopback trust).\n * @returns Client credentials (client ID and secret).\n * @throws Error if registration fails or the server returns an error.\n */\n async registerClient(registrationEndpoint: string, options: DcrRegistrationOptions = {}): Promise<ClientCredentials> {\n const requestBody: DcrRegistrationRequest = {\n client_name: options.clientName || '@mcp-z/client',\n redirect_uris: options.redirectUri ? [options.redirectUri] : ['http://localhost:3000/callback'],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n };\n\n // registrationEndpoint is remote-controlled discovery data; allowLoopback\n // must come from the caller's own trust, never from registrationEndpoint.\n const response = await discoveryFetch(\n registrationEndpoint,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Connection: 'close',\n },\n body: JSON.stringify(requestBody),\n },\n 'registration endpoint',\n { allowLoopback: options.allowLoopback ?? false }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`DCR registration failed (${response.status}): ${errorText}`);\n }\n\n const data = (await response.json()) as DcrRegistrationResponse;\n\n if (!data.client_id) {\n throw new Error('DCR registration response missing client_id');\n }\n\n const credentials: ClientCredentials = {\n clientId: data.client_id,\n clientSecret: data.client_secret || '',\n };\n\n if (data.client_id_issued_at) {\n credentials.issuedAt = data.client_id_issued_at;\n }\n\n return credentials;\n }\n}\n"],"names":["DynamicClientRegistrar","registerClient","registrationEndpoint","options","requestBody","response","errorText","data","credentials","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","discoveryFetch","method","headers","Accept","Connection","body","JSON","stringify","allowLoopback","ok","text","Error","status","json","client_id","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC;;;;+BAuBYA;;;eAAAA;;;gCArBkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBxB,IAAA,AAAMA,uCAAN;;aAAMA;gCAAAA;;iBAAAA;IACX;;;;;;;GAOC,GACD,OAAMC,cA+CL,GA/CD,SAAMA;4CAAeC,oBAA4B;gBAAEC,SAuB9BA,wBAtBbC,aAUAC,UAgBEC,WAIFC,MAMAC;;;;;wBArC2CL,UAAAA,oEAAkC,CAAC;wBAC9EC,cAAsC;4BAC1CK,aAAaN,QAAQO,UAAU,IAAI;4BACnCC,eAAeR,QAAQS,WAAW;gCAAIT,QAAQS,WAAW;;gCAAK;;4BAC9DC,WAAW;gCAAG;gCAAsB;;4BACpCC,cAAc;gCAAG;;4BACjBC,4BAA4B;wBAC9B;wBAIiB;;4BAAMC,IAAAA,gCAAc,EACnCd,sBACA;gCACEe,QAAQ;gCACRC,SAAS;oCACP,gBAAgB;oCAChBC,QAAQ;oCACRC,YAAY;gCACd;gCACAC,MAAMC,KAAKC,SAAS,CAACnB;4BACvB,GACA,yBACA;gCAAEoB,aAAa,GAAErB,yBAAAA,QAAQqB,aAAa,cAArBrB,oCAAAA,yBAAyB;4BAAM;;;wBAZ5CE,WAAW;6BAeb,CAACA,SAASoB,EAAE,EAAZ;;;;wBACgB;;4BAAMpB,SAASqB,IAAI;;;wBAA/BpB,YAAY;wBAClB,MAAM,IAAIqB,MAAM,AAAC,4BAAgDrB,OAArBD,SAASuB,MAAM,EAAC,OAAe,OAAVtB;;wBAGrD;;4BAAMD,SAASwB,IAAI;;;wBAA3BtB,OAAQ;wBAEd,IAAI,CAACA,KAAKuB,SAAS,EAAE;4BACnB,MAAM,IAAIH,MAAM;wBAClB;wBAEMnB,cAAiC;4BACrCuB,UAAUxB,KAAKuB,SAAS;4BACxBE,cAAczB,KAAK0B,aAAa,IAAI;wBACtC;wBAEA,IAAI1B,KAAK2B,mBAAmB,EAAE;4BAC5B1B,YAAY2B,QAAQ,GAAG5B,KAAK2B,mBAAmB;wBACjD;wBAEA;;4BAAO1B;;;;QACT;;WAxDWR"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dynamic-client-registrar.ts"],"sourcesContent":["/**\n * Dynamic Client Registration (DCR) Client\n * Implements RFC 7591 for OAuth client registration\n */\n\nimport { discoveryFetch } from '../auth/discovery-fetch.ts';\nimport type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.ts';\n\n/** DCR Registration Request (RFC 7591) */\ninterface DcrRegistrationRequest {\n client_name?: string;\n redirect_uris?: string[];\n grant_types?: string[];\n response_types?: string[];\n token_endpoint_auth_method?: string;\n application_type?: string;\n}\n\n/** DCR Registration Response (RFC 7591) */\ninterface DcrRegistrationResponse {\n client_id: string;\n client_secret?: string;\n client_id_issued_at?: number;\n client_secret_expires_at?: number;\n}\n\n/** Handles Dynamic Client Registration with OAuth servers. */\nexport class DynamicClientRegistrar {\n /**\n * Registers a new OAuth client with the authorization server (RFC 7591).\n *\n * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.\n * @param options - Registration options (redirect URI, client name, loopback trust).\n * @returns Client credentials (client ID and secret).\n * @throws Error if registration fails or the server returns an error.\n */\n async registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials> {\n const requestBody: DcrRegistrationRequest = {\n client_name: options.clientName || '@mcp-z/client',\n redirect_uris: [options.redirectUri],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n // The callback listener always binds an OS-assigned loopback port, so the\n // redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).\n application_type: 'native',\n };\n\n // registrationEndpoint is remote-controlled discovery data; allowLoopback\n // must come from the caller's own trust, never from registrationEndpoint.\n const response = await discoveryFetch(\n registrationEndpoint,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Connection: 'close',\n },\n body: JSON.stringify(requestBody),\n },\n 'registration endpoint',\n { allowLoopback: options.allowLoopback ?? false }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`DCR registration failed (${response.status}): ${errorText}`);\n }\n\n const data = (await response.json()) as DcrRegistrationResponse;\n\n if (!data.client_id) {\n throw new Error('DCR registration response missing client_id');\n }\n\n const credentials: ClientCredentials = {\n clientId: data.client_id,\n clientSecret: data.client_secret || '',\n };\n\n if (data.client_id_issued_at) {\n credentials.issuedAt = data.client_id_issued_at;\n }\n\n return credentials;\n }\n}\n"],"names":["DynamicClientRegistrar","registerClient","registrationEndpoint","options","requestBody","response","errorText","data","credentials","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","application_type","discoveryFetch","method","headers","Accept","Connection","body","JSON","stringify","allowLoopback","ok","text","Error","status","json","client_id","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC;;;;+BAwBYA;;;eAAAA;;;gCAtBkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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B;;;;QACT;;WA3DWR"}
@@ -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,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;
@@ -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;
@@ -9,6 +9,9 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
+ get extractBaseUrl () {
13
+ return extractBaseUrl;
14
+ },
12
15
  get joinWellKnown () {
13
16
  return joinWellKnown;
14
17
  },
@@ -21,8 +24,8 @@ function normalizeUrl(input) {
21
24
  var url = new URL(input);
22
25
  url.search = '';
23
26
  url.hash = '';
24
- url.pathname = url.pathname.replace(/\/+$/, '');
25
- return url.origin + url.pathname;
27
+ // Strip after joining: assigning an empty pathname puts the '/' straight back.
28
+ return (url.origin + url.pathname).replace(/\/+$/, '');
26
29
  } catch (unused) {
27
30
  return input.replace(/\/+$/, '');
28
31
  }
@@ -30,4 +33,21 @@ function normalizeUrl(input) {
30
33
  function joinWellKnown(baseUrl, suffix) {
31
34
  return "".concat(normalizeUrl(baseUrl)).concat(suffix);
32
35
  }
36
+ function extractBaseUrl(mcpUrl) {
37
+ var url = new URL(mcpUrl);
38
+ // Ignore query/hash for base URL purposes
39
+ url.search = '';
40
+ url.hash = '';
41
+ // Normalize path segments (removes empty segments from leading/trailing slashes)
42
+ var segments = url.pathname.split('/').filter(Boolean);
43
+ // If last segment is exactly "mcp", drop it
44
+ if (segments[segments.length - 1] === 'mcp') {
45
+ segments.pop();
46
+ }
47
+ // Rebuild pathname; empty means root
48
+ url.pathname = segments.length ? "/".concat(segments.join('/')) : '';
49
+ // Return without trailing slash (except root origin)
50
+ var out = url.origin + url.pathname;
51
+ return out === url.origin ? out : out.replace(/\/+$/, '');
52
+ }
33
53
  /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
@@ -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 url.pathname = url.pathname.replace(/\\/+$/, '');\n return url.origin + url.pathname;\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":["joinWellKnown","normalizeUrl","input","url","URL","search","hash","pathname","replace","origin","baseUrl","suffix"],"mappings":";;;;;;;;;;;QAYgBA;eAAAA;;QAZAC;eAAAA;;;AAAT,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,IAAMC,MAAM,IAAIC,IAAIF;QACpBC,IAAIE,MAAM,GAAG;QACbF,IAAIG,IAAI,GAAG;QACXH,IAAII,QAAQ,GAAGJ,IAAII,QAAQ,CAACC,OAAO,CAAC,QAAQ;QAC5C,OAAOL,IAAIM,MAAM,GAAGN,IAAII,QAAQ;IAClC,EAAE,eAAM;QACN,OAAOL,MAAMM,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEO,SAASR,cAAcU,OAAe,EAAEC,MAAc;IAC3D,OAAO,AAAC,GAA0BA,OAAxBV,aAAaS,UAAkB,OAAPC;AACpC"}
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":["extractBaseUrl","joinWellKnown","normalizeUrl","input","url","URL","search","hash","origin","pathname","replace","baseUrl","suffix","mcpUrl","segments","split","filter","Boolean","length","pop","join","out"],"mappings":";;;;;;;;;;;QAgCgBA;eAAAA;;QApBAC;eAAAA;;QAZAC;eAAAA;;;AAAT,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,IAAMC,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,eAAM;QACN,OAAOP,MAAMO,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEO,SAAST,cAAcU,OAAe,EAAEC,MAAc;IAC3D,OAAO,AAAC,GAA0BA,OAAxBV,aAAaS,UAAkB,OAAPC;AACpC;AAkBO,SAASZ,eAAea,MAAc;IAC3C,IAAMT,MAAM,IAAIC,IAAIQ;IAEpB,0CAA0C;IAC1CT,IAAIE,MAAM,GAAG;IACbF,IAAIG,IAAI,GAAG;IAEX,iFAAiF;IACjF,IAAMO,WAAWV,IAAIK,QAAQ,CAACM,KAAK,CAAC,KAAKC,MAAM,CAACC;IAEhD,4CAA4C;IAC5C,IAAIH,QAAQ,CAACA,SAASI,MAAM,GAAG,EAAE,KAAK,OAAO;QAC3CJ,SAASK,GAAG;IACd;IAEA,qCAAqC;IACrCf,IAAIK,QAAQ,GAAGK,SAASI,MAAM,GAAG,AAAC,IAAsB,OAAnBJ,SAASM,IAAI,CAAC,QAAS;IAE5D,qDAAqD;IACrD,IAAMC,MAAMjB,IAAII,MAAM,GAAGJ,IAAIK,QAAQ;IACrC,OAAOY,QAAQjB,IAAII,MAAM,GAAGa,MAAMA,IAAIX,OAAO,CAAC,QAAQ;AACxD"}
@@ -1,4 +1,4 @@
1
- import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
1
+ import type { Client } from '@modelcontextprotocol/client';
2
2
  export type NativeCallToolResponse = Awaited<ReturnType<Client['callTool']>>;
3
3
  export type NativeGetPromptResponse = Awaited<ReturnType<Client['getPrompt']>>;
4
4
  export type NativeReadResourceResponse = Awaited<ReturnType<Client['readResource']>>;
@@ -1,4 +1,4 @@
1
- import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
1
+ import type { Client } from '@modelcontextprotocol/client';
2
2
  export type NativeCallToolResponse = Awaited<ReturnType<Client['callTool']>>;
3
3
  export type NativeGetPromptResponse = Awaited<ReturnType<Client['getPrompt']>>;
4
4
  export type NativeReadResourceResponse = Awaited<ReturnType<Client['readResource']>>;
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/response-wrappers.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { ContentBlock, PromptMessage, TextContent } from '@modelcontextprotocol/sdk/types.js';\n\nexport type NativeCallToolResponse = Awaited<ReturnType<Client['callTool']>>;\nexport type NativeGetPromptResponse = Awaited<ReturnType<Client['getPrompt']>>;\nexport type NativeReadResourceResponse = Awaited<ReturnType<Client['readResource']>>;\n\nexport type JsonValidator<T> = (value: unknown) => asserts value is T;\n\nexport class ToolResponseError extends Error {\n readonly response: NativeCallToolResponse;\n\n constructor(message: string, response: NativeCallToolResponse) {\n super(message);\n this.name = 'ToolResponseError';\n this.response = response;\n }\n}\n\nexport class ToolResponseWrapper {\n private readonly payload: NativeCallToolResponse;\n\n constructor(payload: NativeCallToolResponse) {\n this.payload = payload;\n }\n\n raw(): NativeCallToolResponse {\n return this.payload;\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const value = this.resolveJsonPayload();\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(value);\n }\n return value as T;\n }\n\n text(): string {\n if (isCompatibilityResult(this.payload)) {\n if (typeof this.payload.toolResult === 'string') {\n return this.payload.toolResult;\n }\n throw new ToolResponseError('Compatibility tool result is not text', this.payload);\n }\n\n this.throwIfError();\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include text content', this.payload);\n }\n\n return textBlock.text;\n }\n\n private resolveJsonPayload(): unknown {\n if (isCompatibilityResult(this.payload)) {\n return this.payload.toolResult;\n }\n\n this.throwIfError();\n\n if (hasStructuredContent(this.payload)) {\n return this.payload.structuredContent;\n }\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include structuredContent or text content', this.payload);\n }\n\n try {\n return JSON.parse(textBlock.text) as unknown;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ToolResponseError(`Failed to parse tool text content as JSON: ${reason}`, this.payload);\n }\n }\n\n private throwIfError(): void {\n if ('isError' in this.payload && this.payload.isError) {\n let detail = typeof this.payload.error === 'object' && this.payload.error && 'message' in this.payload.error ? String((this.payload.error as { message?: unknown }).message ?? '') : '';\n if (!detail) {\n const textBlock = findFirstTextBlock((this.payload.content ?? []) as ContentBlock[]);\n if (textBlock?.text) {\n detail = textBlock.text;\n }\n }\n const message = detail ? `Tool invocation returned an error result: ${detail}` : 'Tool invocation returned an error result';\n throw new ToolResponseError(message, this.payload);\n }\n }\n}\n\nexport class PromptResponseError extends Error {\n readonly response: NativeGetPromptResponse;\n\n constructor(message: string, response: NativeGetPromptResponse) {\n super(message);\n this.name = 'PromptResponseError';\n this.response = response;\n }\n}\n\nexport class PromptResponseWrapper {\n private readonly payload: NativeGetPromptResponse;\n\n constructor(payload: NativeGetPromptResponse) {\n this.payload = payload;\n }\n\n raw(): NativeGetPromptResponse {\n return this.payload;\n }\n\n text(): string {\n const segments = collectPromptText(this.payload.messages);\n if (!segments.length) {\n throw new PromptResponseError('Prompt response did not include text content', this.payload);\n }\n return segments.join('\\n\\n');\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new PromptResponseError(`Failed to parse prompt text as JSON: ${reason}`, this.payload);\n }\n }\n}\n\nexport class ResourceResponseError extends Error {\n readonly response: NativeReadResourceResponse;\n\n constructor(message: string, response: NativeReadResourceResponse) {\n super(message);\n this.name = 'ResourceResponseError';\n this.response = response;\n }\n}\n\nexport class ResourceResponseWrapper {\n private readonly payload: NativeReadResourceResponse;\n\n constructor(payload: NativeReadResourceResponse) {\n this.payload = payload;\n }\n\n raw(): NativeReadResourceResponse {\n return this.payload;\n }\n\n text(): string {\n const entry = this.firstEntry();\n if ('text' in entry && typeof entry.text === 'string') {\n return entry.text;\n }\n if ('blob' in entry && typeof entry.blob === 'string') {\n try {\n return Buffer.from(entry.blob, 'base64').toString('utf8');\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to decode resource blob as UTF-8 text: ${reason}`, this.payload);\n }\n }\n throw new ResourceResponseError('Resource content does not include text or blob data', this.payload);\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to parse resource text as JSON: ${reason}`, this.payload);\n }\n }\n\n private firstEntry(): NativeReadResourceResponse['contents'][number] {\n const [entry] = this.payload.contents ?? [];\n if (!entry) {\n throw new ResourceResponseError('Resource response did not include any contents', this.payload);\n }\n return entry;\n }\n}\n\nfunction hasStructuredContent(response: NativeCallToolResponse): response is NativeCallToolResponse & { structuredContent: Record<string, unknown> } {\n return Boolean((response as { structuredContent?: unknown }).structuredContent);\n}\n\nfunction isCompatibilityResult(response: NativeCallToolResponse): response is NativeCallToolResponse & { toolResult: unknown } {\n return hasOwn(response, 'toolResult');\n}\n\nfunction findFirstTextBlock(blocks: ContentBlock[] | undefined): TextContent | undefined {\n if (!Array.isArray(blocks)) {\n return undefined;\n }\n return blocks.find(isTextContent);\n}\n\nfunction collectPromptText(messages: PromptMessage[]): string[] {\n const segments: string[] = [];\n for (const message of messages) {\n const textBlock = isTextContent(message.content) ? message.content : undefined;\n if (textBlock) {\n segments.push(textBlock.text);\n }\n }\n return segments;\n}\n\nfunction isTextContent(block: unknown): block is TextContent {\n return Boolean(block) && typeof block === 'object' && (block as { type?: string }).type === 'text';\n}\n\nconst protoHasOwn = Object.prototype.hasOwnProperty;\n\nfunction hasOwn(target: object, key: PropertyKey): boolean {\n return protoHasOwn.call(target, key);\n}\n\nfunction formatErrorReason(error: unknown): string {\n if (error instanceof Error && typeof error.message === 'string') {\n return error.message;\n }\n if (typeof error === 'string') {\n return error;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n"],"names":["PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","message","response","name","Error","payload","raw","json","validator","value","resolveJsonPayload","assertValid","text","isCompatibilityResult","toolResult","throwIfError","textBlock","findFirstTextBlock","content","hasStructuredContent","structuredContent","JSON","parse","error","reason","formatErrorReason","isError","detail","String","segments","collectPromptText","messages","length","join","textValue","parsed","entry","firstEntry","blob","Buffer","from","toString","contents","Boolean","hasOwn","blocks","Array","isArray","undefined","find","isTextContent","push","block","type","protoHasOwn","Object","prototype","hasOwnProperty","target","key","call","stringify"],"mappings":";;;;;;;;;;;QAiGaA;eAAAA;;QAUAC;eAAAA;;QAmCAC;eAAAA;;QAUAC;eAAAA;;QA9IAC;eAAAA;;QAUAC;eAAAA;;;0BApBU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUhB,IAAA,AAAMD,kCAAN;;cAAMA;aAAAA,kBAGCE,OAAe,EAAEC,QAAgC;gCAHlDH;;gBAIT,kBAJSA;YAIHE;;QACN,MAAKE,IAAI,GAAG;QACZ,MAAKD,QAAQ,GAAGA;;;WANPH;qBAA0BK;AAUhC,IAAA,AAAMJ,oCAAN;;aAAMA,oBAGCK,OAA+B;gCAHhCL;QAIT,IAAI,CAACK,OAAO,GAAGA;;iBAJNL;IAOXM,OAAAA,GAEC,GAFDA,SAAAA;QACE,OAAO,IAAI,CAACD,OAAO;IACrB;IAEAE,OAAAA,IAOC,GAPDA,SAAAA,KAAkBC,SAA4B;QAC5C,IAAMC,QAAQ,IAAI,CAACC,kBAAkB;QACrC,IAAIF,WAAW;YACb,IAAMG,cAAgCH;YACtCG,YAAYF;QACd;QACA,OAAOA;IACT;IAEAG,OAAAA,IAgBC,GAhBDA,SAAAA;YAUuC;QATrC,IAAIC,sBAAsB,IAAI,CAACR,OAAO,GAAG;YACvC,IAAI,OAAO,IAAI,CAACA,OAA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,YAAY,AAACA,MAA4BC,IAAI,KAAK;AAC9F;AAEA,IAAMC,cAAcC,OAAOC,SAAS,CAACC,cAAc;AAEnD,SAASb,OAAOc,MAAc,EAAEC,GAAgB;IAC9C,OAAOL,YAAYM,IAAI,CAACF,QAAQC;AAClC;AAEA,SAASlC,kBAAkBF,KAAc;IACvC,IAAIA,AAAK,YAALA,OAAiBnB,UAAS,OAAOmB,MAAMtB,OAAO,KAAK,UAAU;QAC/D,OAAOsB,MAAMtB,OAAO;IACtB;IACA,IAAI,OAAOsB,UAAU,UAAU;QAC7B,OAAOA;IACT;IACA,IAAI;QACF,OAAOF,KAAKwC,SAAS,CAACtC;IACxB,EAAE,eAAM;QACN,OAAOK,OAAOL;IAChB;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/response-wrappers.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { Client, ContentBlock, PromptMessage, TextContent } from '@modelcontextprotocol/client';\n\nexport type NativeCallToolResponse = Awaited<ReturnType<Client['callTool']>>;\nexport type NativeGetPromptResponse = Awaited<ReturnType<Client['getPrompt']>>;\nexport type NativeReadResourceResponse = Awaited<ReturnType<Client['readResource']>>;\n\nexport type JsonValidator<T> = (value: unknown) => asserts value is T;\n\nexport class ToolResponseError extends Error {\n readonly response: NativeCallToolResponse;\n\n constructor(message: string, response: NativeCallToolResponse) {\n super(message);\n this.name = 'ToolResponseError';\n this.response = response;\n }\n}\n\nexport class ToolResponseWrapper {\n private readonly payload: NativeCallToolResponse;\n\n constructor(payload: NativeCallToolResponse) {\n this.payload = payload;\n }\n\n raw(): NativeCallToolResponse {\n return this.payload;\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const value = this.resolveJsonPayload();\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(value);\n }\n return value as T;\n }\n\n text(): string {\n if (isCompatibilityResult(this.payload)) {\n if (typeof this.payload.toolResult === 'string') {\n return this.payload.toolResult;\n }\n throw new ToolResponseError('Compatibility tool result is not text', this.payload);\n }\n\n this.throwIfError();\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include text content', this.payload);\n }\n\n return textBlock.text;\n }\n\n private resolveJsonPayload(): unknown {\n if (isCompatibilityResult(this.payload)) {\n return this.payload.toolResult;\n }\n\n this.throwIfError();\n\n if (hasStructuredContent(this.payload)) {\n return this.payload.structuredContent;\n }\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include structuredContent or text content', this.payload);\n }\n\n try {\n return JSON.parse(textBlock.text) as unknown;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ToolResponseError(`Failed to parse tool text content as JSON: ${reason}`, this.payload);\n }\n }\n\n private throwIfError(): void {\n if ('isError' in this.payload && this.payload.isError) {\n let detail = typeof this.payload.error === 'object' && this.payload.error && 'message' in this.payload.error ? String((this.payload.error as { message?: unknown }).message ?? '') : '';\n if (!detail) {\n const textBlock = findFirstTextBlock((this.payload.content ?? []) as ContentBlock[]);\n if (textBlock?.text) {\n detail = textBlock.text;\n }\n }\n const message = detail ? `Tool invocation returned an error result: ${detail}` : 'Tool invocation returned an error result';\n throw new ToolResponseError(message, this.payload);\n }\n }\n}\n\nexport class PromptResponseError extends Error {\n readonly response: NativeGetPromptResponse;\n\n constructor(message: string, response: NativeGetPromptResponse) {\n super(message);\n this.name = 'PromptResponseError';\n this.response = response;\n }\n}\n\nexport class PromptResponseWrapper {\n private readonly payload: NativeGetPromptResponse;\n\n constructor(payload: NativeGetPromptResponse) {\n this.payload = payload;\n }\n\n raw(): NativeGetPromptResponse {\n return this.payload;\n }\n\n text(): string {\n const segments = collectPromptText(this.payload.messages);\n if (!segments.length) {\n throw new PromptResponseError('Prompt response did not include text content', this.payload);\n }\n return segments.join('\\n\\n');\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new PromptResponseError(`Failed to parse prompt text as JSON: ${reason}`, this.payload);\n }\n }\n}\n\nexport class ResourceResponseError extends Error {\n readonly response: NativeReadResourceResponse;\n\n constructor(message: string, response: NativeReadResourceResponse) {\n super(message);\n this.name = 'ResourceResponseError';\n this.response = response;\n }\n}\n\nexport class ResourceResponseWrapper {\n private readonly payload: NativeReadResourceResponse;\n\n constructor(payload: NativeReadResourceResponse) {\n this.payload = payload;\n }\n\n raw(): NativeReadResourceResponse {\n return this.payload;\n }\n\n text(): string {\n const entry = this.firstEntry();\n if ('text' in entry && typeof entry.text === 'string') {\n return entry.text;\n }\n if ('blob' in entry && typeof entry.blob === 'string') {\n try {\n return Buffer.from(entry.blob, 'base64').toString('utf8');\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to decode resource blob as UTF-8 text: ${reason}`, this.payload);\n }\n }\n throw new ResourceResponseError('Resource content does not include text or blob data', this.payload);\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to parse resource text as JSON: ${reason}`, this.payload);\n }\n }\n\n private firstEntry(): NativeReadResourceResponse['contents'][number] {\n const [entry] = this.payload.contents ?? [];\n if (!entry) {\n throw new ResourceResponseError('Resource response did not include any contents', this.payload);\n }\n return entry;\n }\n}\n\nfunction hasStructuredContent(response: NativeCallToolResponse): response is NativeCallToolResponse & { structuredContent: Record<string, unknown> } {\n return Boolean((response as { structuredContent?: unknown }).structuredContent);\n}\n\nfunction isCompatibilityResult(response: NativeCallToolResponse): response is NativeCallToolResponse & { toolResult: unknown } {\n return hasOwn(response, 'toolResult');\n}\n\nfunction findFirstTextBlock(blocks: ContentBlock[] | undefined): TextContent | undefined {\n if (!Array.isArray(blocks)) {\n return undefined;\n }\n return blocks.find(isTextContent);\n}\n\nfunction collectPromptText(messages: PromptMessage[]): string[] {\n const segments: string[] = [];\n for (const message of messages) {\n const textBlock = isTextContent(message.content) ? message.content : undefined;\n if (textBlock) {\n segments.push(textBlock.text);\n }\n }\n return segments;\n}\n\nfunction isTextContent(block: unknown): block is TextContent {\n return Boolean(block) && typeof block === 'object' && (block as { type?: string }).type === 'text';\n}\n\nconst protoHasOwn = Object.prototype.hasOwnProperty;\n\nfunction hasOwn(target: object, key: PropertyKey): boolean {\n return protoHasOwn.call(target, key);\n}\n\nfunction formatErrorReason(error: unknown): string {\n if (error instanceof Error && typeof error.message === 'string') {\n return error.message;\n }\n if (typeof error === 'string') {\n return error;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n"],"names":["PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","message","response","name","Error","payload","raw","json","validator","value","resolveJsonPayload","assertValid","text","isCompatibilityResult","toolResult","throwIfError","textBlock","findFirstTextBlock","content","hasStructuredContent","structuredContent","JSON","parse","error","reason","formatErrorReason","isError","detail","String","segments","collectPromptText","messages","length","join","textValue","parsed","entry","firstEntry","blob","Buffer","from","toString","contents","Boolean","hasOwn","blocks","Array","isArray","undefined","find","isTextContent","push","block","type","protoHasOwn","Object","prototype","hasOwnProperty","target","key","call","stringify"],"mappings":";;;;;;;;;;;QAgGaA;eAAAA;;QAUAC;eAAAA;;QAmCAC;eAAAA;;QAUAC;eAAAA;;QA9IAC;eAAAA;;QAUAC;eAAAA;;;0BAnBU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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B;AAChF;AAEA,SAASP,sBAAsBX,QAAgC;IAC7D,OAAO0C,OAAO1C,UAAU;AAC1B;AAEA,SAASe,mBAAmB4B,MAAkC;IAC5D,IAAI,CAACC,MAAMC,OAAO,CAACF,SAAS;QAC1B,OAAOG;IACT;IACA,OAAOH,OAAOI,IAAI,CAACC;AACrB;AAEA,SAASpB,kBAAkBC,QAAyB;IAClD,IAAMF,WAAqB,EAAE;QACxB,kCAAA,2BAAA;;QAAL,QAAK,YAAiBE,6BAAjB,SAAA,6BAAA,QAAA,yBAAA,iCAA2B;YAA3B,IAAM9B,UAAN;YACH,IAAMe,YAAYkC,cAAcjD,QAAQiB,OAAO,IAAIjB,QAAQiB,OAAO,GAAG8B;YACrE,IAAIhC,WAAW;gBACba,SAASsB,IAAI,CAACnC,UAAUJ,IAAI;YAC9B;QACF;;QALK;QAAA;;;iBAAA,6BAAA;gBAAA;;;gBAAA;sBAAA;;;;IAML,OAAOiB;AACT;AAEA,SAASqB,cAAcE,KAAc;IACnC,OAAOT,QAAQS,UAAU,CAAA,OAAOA,sCAAP,SAAOA,MAAI,MAAM,YAAY,AAACA,MAA4BC,IAAI,KAAK;AAC9F;AAEA,IAAMC,cAAcC,OAAOC,SAAS,CAACC,cAAc;AAEnD,SAASb,OAAOc,MAAc,EAAEC,GAAgB;IAC9C,OAAOL,YAAYM,IAAI,CAACF,QAAQC;AAClC;AAEA,SAASlC,kBAAkBF,KAAc;IACvC,IAAIA,AAAK,YAALA,OAAiBnB,UAAS,OAAOmB,MAAMtB,OAAO,KAAK,UAAU;QAC/D,OAAOsB,MAAMtB,OAAO;IACtB;IACA,IAAI,OAAOsB,UAAU,UAAU;QAC7B,OAAOA;IACT;IACA,IAAI;QACF,OAAOF,KAAKwC,SAAS,CAACtC;IACxB,EAAE,eAAM;QACN,OAAOK,OAAOL;IAChB;AACF"}
@@ -4,7 +4,7 @@
4
4
  * Provides text-based search across tools, prompts, and resources
5
5
  * from connected MCP servers.
6
6
  */
7
- import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
7
+ import type { Client } from '@modelcontextprotocol/client';
8
8
  import type { CapabilityIndex, SearchOptions, SearchResponse } from './types.js';
9
9
  export type CapabilityClient = Pick<Client, 'listTools' | 'listPrompts' | 'listResources'>;
10
10
  /**
@@ -4,7 +4,7 @@
4
4
  * Provides text-based search across tools, prompts, and resources
5
5
  * from connected MCP servers.
6
6
  */
7
- import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
7
+ import type { Client } from '@modelcontextprotocol/client';
8
8
  import type { CapabilityIndex, SearchOptions, SearchResponse } from './types.js';
9
9
  export type CapabilityClient = Pick<Client, 'listTools' | 'listPrompts' | 'listResources'>;
10
10
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/search/search.ts"],"sourcesContent":["/**\n * Search implementation for MCP capability discovery\n *\n * Provides text-based search across tools, prompts, and resources\n * from connected MCP servers.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { PromptArgument } from '../connection/types.ts';\nimport type { CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './types.ts';\n\nexport type CapabilityClient = Pick<Client, 'listTools' | 'listPrompts' | 'listResources'>;\n\nconst DEFAULT_LIMIT = 20;\nconst DEFAULT_THRESHOLD = 0;\nconst DEFAULT_TYPES: CapabilityType[] = ['tool', 'prompt', 'resource'];\nconst DEFAULT_SEARCH_FIELDS: SearchField[] = ['name', 'description', 'schema'];\n\n/**\n * Extract searchable text from a JSON Schema's property descriptions\n */\nfunction extractSchemaText(inputSchema: unknown): string {\n if (!inputSchema || typeof inputSchema !== 'object') {\n return '';\n }\n\n const schema = inputSchema as {\n properties?: Record<string, { description?: string; name?: string }>;\n description?: string;\n };\n\n const parts: string[] = [];\n\n // Add schema-level description if present\n if (schema.description) {\n parts.push(schema.description);\n }\n\n // Add property names and descriptions\n if (schema.properties) {\n for (const [propName, prop] of Object.entries(schema.properties)) {\n parts.push(propName);\n if (prop && typeof prop === 'object' && prop.description) {\n parts.push(prop.description);\n }\n }\n }\n\n return parts.join(' ');\n}\n\n/**\n * Extract searchable text from prompt arguments\n */\nfunction extractArgumentsText(args: PromptArgument[] | undefined): string {\n if (!args || !Array.isArray(args)) {\n return '';\n }\n\n return args\n .map((arg) => {\n const parts = [arg.name];\n if (arg.description) {\n parts.push(arg.description);\n }\n return parts.join(' ');\n })\n .join(' ');\n}\n\n/**\n * Build an index of capabilities from connected MCP clients\n */\nexport async function buildCapabilityIndex(clients: Map<string, CapabilityClient>): Promise<CapabilityIndex> {\n const capabilities: IndexedCapability[] = [];\n const servers: string[] = [];\n\n for (const [serverName, client] of clients) {\n servers.push(serverName);\n\n // Fetch all capabilities in parallel, handling errors gracefully\n const [toolsResult, promptsResult, resourcesResult] = await Promise.all([client.listTools().catch(() => null), client.listPrompts().catch(() => null), client.listResources().catch(() => null)]);\n\n // Index tools\n if (toolsResult?.tools) {\n for (const tool of toolsResult.tools) {\n capabilities.push({\n type: 'tool',\n server: serverName,\n name: tool.name,\n description: tool.description,\n schemaText: extractSchemaText(tool.inputSchema),\n } satisfies IndexedTool);\n }\n }\n\n // Index prompts\n if (promptsResult?.prompts) {\n for (const prompt of promptsResult.prompts) {\n capabilities.push({\n type: 'prompt',\n server: serverName,\n name: prompt.name,\n description: prompt.description,\n argumentsText: extractArgumentsText(prompt.arguments as PromptArgument[] | undefined),\n arguments: prompt.arguments as PromptArgument[] | undefined,\n } satisfies IndexedPrompt);\n }\n }\n\n // Index resources\n if (resourcesResult?.resources) {\n for (const resource of resourcesResult.resources) {\n capabilities.push({\n type: 'resource',\n server: serverName,\n name: resource.name,\n description: resource.description,\n uri: resource.uri,\n mimeType: resource.mimeType,\n } satisfies IndexedResource);\n }\n }\n }\n\n return {\n capabilities,\n servers,\n indexedAt: new Date(),\n };\n}\n\n/**\n * Calculate relevance score and matched fields for a capability against a query\n */\nfunction scoreCapability(capability: IndexedCapability, queryTerms: string[], searchFields: SearchField[]): { score: number; matchedOn: string[] } {\n const matchedOn: string[] = [];\n let totalScore = 0;\n\n // Weights for different match types\n const EXACT_NAME_WEIGHT = 1.0;\n const PARTIAL_NAME_WEIGHT = 0.8;\n const DESCRIPTION_WEIGHT = 0.6;\n const SCHEMA_WEIGHT = 0.4;\n const SERVER_WEIGHT = 0.3;\n\n const nameLower = capability.name.toLowerCase();\n const descLower = (capability.description || '').toLowerCase();\n const serverLower = capability.server.toLowerCase();\n\n // Get schema/arguments text based on type\n let schemaTextLower = '';\n if (capability.type === 'tool') {\n schemaTextLower = capability.schemaText.toLowerCase();\n } else if (capability.type === 'prompt') {\n schemaTextLower = capability.argumentsText.toLowerCase();\n } else if (capability.type === 'resource') {\n // For resources, include URI and mimeType in searchable text\n schemaTextLower = `${capability.uri} ${capability.mimeType || ''}`.toLowerCase();\n }\n\n for (const term of queryTerms) {\n const termLower = term.toLowerCase();\n\n // Check name matches\n if (searchFields.includes('name')) {\n if (nameLower === termLower) {\n totalScore += EXACT_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n } else if (nameLower.includes(termLower)) {\n totalScore += PARTIAL_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n }\n }\n\n // Check description matches\n if (searchFields.includes('description') && descLower.includes(termLower)) {\n totalScore += DESCRIPTION_WEIGHT;\n if (!matchedOn.includes('description')) matchedOn.push('description');\n }\n\n // Check schema/arguments matches\n if (searchFields.includes('schema') && schemaTextLower.includes(termLower)) {\n totalScore += SCHEMA_WEIGHT;\n const fieldName = capability.type === 'tool' ? 'inputSchema' : capability.type === 'prompt' ? 'arguments' : 'uri';\n if (!matchedOn.includes(fieldName)) matchedOn.push(fieldName);\n }\n\n // Check server name matches\n if (searchFields.includes('server') && serverLower.includes(termLower)) {\n totalScore += SERVER_WEIGHT;\n if (!matchedOn.includes('server')) matchedOn.push('server');\n }\n }\n\n // Normalize score to 0-1 range based on number of terms\n const normalizedScore = queryTerms.length > 0 ? Math.min(1, totalScore / queryTerms.length) : 0;\n\n return { score: normalizedScore, matchedOn };\n}\n\n/**\n * Search for capabilities matching a query string\n */\nexport function searchCapabilities(index: CapabilityIndex, query: string, options: SearchOptions = {}): SearchResponse {\n const { types = DEFAULT_TYPES, servers, searchFields = DEFAULT_SEARCH_FIELDS, limit = DEFAULT_LIMIT, threshold = DEFAULT_THRESHOLD } = options;\n\n // Tokenize query into search terms\n const queryTerms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0);\n\n // If empty query, return empty results\n if (queryTerms.length === 0) {\n return { query, results: [], total: 0 };\n }\n\n // Filter and score capabilities\n const scoredResults: Array<{ capability: IndexedCapability; score: number; matchedOn: string[] }> = [];\n\n for (const capability of index.capabilities) {\n // Filter by type\n if (!types.includes(capability.type)) {\n continue;\n }\n\n // Filter by server\n if (servers && servers.length > 0 && !servers.includes(capability.server)) {\n continue;\n }\n\n // Score the capability\n const { score, matchedOn } = scoreCapability(capability, queryTerms, searchFields);\n\n // Apply threshold filter\n if (score >= threshold && matchedOn.length > 0) {\n scoredResults.push({ capability, score, matchedOn });\n }\n }\n\n // Sort by score descending\n scoredResults.sort((a, b) => b.score - a.score);\n\n // Get total before limiting\n const total = scoredResults.length;\n\n // Apply limit and transform to SearchResult\n const results: SearchResult[] = scoredResults.slice(0, limit).map(({ capability, score, matchedOn }) => ({\n type: capability.type,\n server: capability.server,\n name: capability.name,\n description: capability.description,\n matchedOn,\n score,\n }));\n\n return { query, results, total };\n}\n\n/**\n * Convenience function to search directly from connected clients\n * Builds index and performs search in one call\n */\nexport async function search(clients: Map<string, CapabilityClient>, query: string, options: SearchOptions = {}): Promise<SearchResponse> {\n const index = await buildCapabilityIndex(clients);\n return searchCapabilities(index, query, options);\n}\n"],"names":["buildCapabilityIndex","search","searchCapabilities","DEFAULT_LIMIT","DEFAULT_THRESHOLD","DEFAULT_TYPES","DEFAULT_SEARCH_FIELDS","extractSchemaText","inputSchema","schema","parts","description","push","properties","Object","entries","propName","prop","join","extractArgumentsText","args","Array","isArray","map","arg","name","clients","capabilities","servers","serverName","client","toolsResult","promptsResult","resourcesResult","tool","prompt","resource","Promise","all","listTools","catch","listPrompts","listResources","tools","type","server","schemaText","prompts","argumentsText","arguments","resources","uri","mimeType","indexedAt","Date","scoreCapability","capability","queryTerms","searchFields","matchedOn","totalScore","EXACT_NAME_WEIGHT","PARTIAL_NAME_WEIGHT","DESCRIPTION_WEIGHT","SCHEMA_WEIGHT","SERVER_WEIGHT","nameLower","toLowerCase","descLower","serverLower","schemaTextLower","term","termLower","includes","fieldName","normalizedScore","length","Math","min","score","index","query","options","types","limit","threshold","split","filter","results","total","scoredResults","sort","a","b","slice"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QAoEqBA;eAAAA;;QA+LAC;eAAAA;;QA5DNC;eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA/LhB,IAAMC,gBAAgB;AACtB,IAAMC,oBAAoB;AAC1B,IAAMC,gBAAkC;IAAC;IAAQ;IAAU;CAAW;AACtE,IAAMC,wBAAuC;IAAC;IAAQ;IAAe;CAAS;AAE9E;;CAEC,GACD,SAASC,kBAAkBC,WAAoB;IAC7C,IAAI,CAACA,eAAe,CAAA,OAAOA,4CAAP,SAAOA,YAAU,MAAM,UAAU;QACnD,OAAO;IACT;IAEA,IAAMC,SAASD;IAKf,IAAME,QAAkB,EAAE;IAE1B,0CAA0C;IAC1C,IAAID,OAAOE,WAAW,EAAE;QACtBD,MAAME,IAAI,CAACH,OAAOE,WAAW;IAC/B;IAEA,sCAAsC;IACtC,IAAIF,OAAOI,UAAU,EAAE;YAChB,k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;QAAA;;;iBAAA,6BAAA;gBAAA;;;gBAAA;sBAAA;;;;IAoBL,2BAA2B;IAC3B+B,cAAcC,IAAI,CAAC,SAACC,GAAGC;eAAMA,EAAEd,KAAK,GAAGa,EAAEb,KAAK;;IAE9C,4BAA4B;IAC5B,IAAMU,QAAQC,cAAcd,MAAM;IAElC,4CAA4C;IAC5C,IAAMY,UAA0BE,cAAcI,KAAK,CAAC,GAAGV,OAAO7D,GAAG,CAAC;YAAGiC,mBAAAA,YAAYuB,cAAAA,OAAOpB,kBAAAA;eAAiB;YACvGf,MAAMY,WAAWZ,IAAI;YACrBC,QAAQW,WAAWX,MAAM;YACzBpB,MAAM+B,WAAW/B,IAAI;YACrBd,aAAa6C,WAAW7C,WAAW;YACnCgD,WAAAA;YACAoB,OAAAA;QACF;;IAEA,OAAO;QAAEE,OAAAA;QAAOO,SAAAA;QAASC,OAAAA;IAAM;AACjC;AAMO,SAAexF;wCAAOyB,OAAsC,EAAEuD,KAAa;YAAEC,SAC5EF;;;;;oBAD4EE,UAAAA,oEAAyB,CAAC;oBAC9F;;wBAAMlF,qBAAqB0B;;;oBAAnCsD,QAAQ;oBACd;;wBAAO9E,mBAAmB8E,OAAOC,OAAOC;;;;IAC1C"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/search/search.ts"],"sourcesContent":["/**\n * Search implementation for MCP capability discovery\n *\n * Provides text-based search across tools, prompts, and resources\n * from connected MCP servers.\n */\n\nimport type { Client } from '@modelcontextprotocol/client';\nimport type { PromptArgument } from '../connection/types.ts';\nimport type { CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './types.ts';\n\nexport type CapabilityClient = Pick<Client, 'listTools' | 'listPrompts' | 'listResources'>;\n\nconst DEFAULT_LIMIT = 20;\nconst DEFAULT_THRESHOLD = 0;\nconst DEFAULT_TYPES: CapabilityType[] = ['tool', 'prompt', 'resource'];\nconst DEFAULT_SEARCH_FIELDS: SearchField[] = ['name', 'description', 'schema'];\n\n/**\n * Extract searchable text from a JSON Schema's property descriptions\n */\nfunction extractSchemaText(inputSchema: unknown): string {\n if (!inputSchema || typeof inputSchema !== 'object') {\n return '';\n }\n\n const schema = inputSchema as {\n properties?: Record<string, { description?: string; name?: string }>;\n description?: string;\n };\n\n const parts: string[] = [];\n\n // Add schema-level description if present\n if (schema.description) {\n parts.push(schema.description);\n }\n\n // Add property names and descriptions\n if (schema.properties) {\n for (const [propName, prop] of Object.entries(schema.properties)) {\n parts.push(propName);\n if (prop && typeof prop === 'object' && prop.description) {\n parts.push(prop.description);\n }\n }\n }\n\n return parts.join(' ');\n}\n\n/**\n * Extract searchable text from prompt arguments\n */\nfunction extractArgumentsText(args: PromptArgument[] | undefined): string {\n if (!args || !Array.isArray(args)) {\n return '';\n }\n\n return args\n .map((arg) => {\n const parts = [arg.name];\n if (arg.description) {\n parts.push(arg.description);\n }\n return parts.join(' ');\n })\n .join(' ');\n}\n\n/**\n * Build an index of capabilities from connected MCP clients\n */\nexport async function buildCapabilityIndex(clients: Map<string, CapabilityClient>): Promise<CapabilityIndex> {\n const capabilities: IndexedCapability[] = [];\n const servers: string[] = [];\n\n for (const [serverName, client] of clients) {\n servers.push(serverName);\n\n // Fetch all capabilities in parallel, handling errors gracefully\n const [toolsResult, promptsResult, resourcesResult] = await Promise.all([client.listTools().catch(() => null), client.listPrompts().catch(() => null), client.listResources().catch(() => null)]);\n\n // Index tools\n if (toolsResult?.tools) {\n for (const tool of toolsResult.tools) {\n capabilities.push({\n type: 'tool',\n server: serverName,\n name: tool.name,\n description: tool.description,\n schemaText: extractSchemaText(tool.inputSchema),\n } satisfies IndexedTool);\n }\n }\n\n // Index prompts\n if (promptsResult?.prompts) {\n for (const prompt of promptsResult.prompts) {\n capabilities.push({\n type: 'prompt',\n server: serverName,\n name: prompt.name,\n description: prompt.description,\n argumentsText: extractArgumentsText(prompt.arguments as PromptArgument[] | undefined),\n arguments: prompt.arguments as PromptArgument[] | undefined,\n } satisfies IndexedPrompt);\n }\n }\n\n // Index resources\n if (resourcesResult?.resources) {\n for (const resource of resourcesResult.resources) {\n capabilities.push({\n type: 'resource',\n server: serverName,\n name: resource.name,\n description: resource.description,\n uri: resource.uri,\n mimeType: resource.mimeType,\n } satisfies IndexedResource);\n }\n }\n }\n\n return {\n capabilities,\n servers,\n indexedAt: new Date(),\n };\n}\n\n/**\n * Calculate relevance score and matched fields for a capability against a query\n */\nfunction scoreCapability(capability: IndexedCapability, queryTerms: string[], searchFields: SearchField[]): { score: number; matchedOn: string[] } {\n const matchedOn: string[] = [];\n let totalScore = 0;\n\n // Weights for different match types\n const EXACT_NAME_WEIGHT = 1.0;\n const PARTIAL_NAME_WEIGHT = 0.8;\n const DESCRIPTION_WEIGHT = 0.6;\n const SCHEMA_WEIGHT = 0.4;\n const SERVER_WEIGHT = 0.3;\n\n const nameLower = capability.name.toLowerCase();\n const descLower = (capability.description || '').toLowerCase();\n const serverLower = capability.server.toLowerCase();\n\n // Get schema/arguments text based on type\n let schemaTextLower = '';\n if (capability.type === 'tool') {\n schemaTextLower = capability.schemaText.toLowerCase();\n } else if (capability.type === 'prompt') {\n schemaTextLower = capability.argumentsText.toLowerCase();\n } else if (capability.type === 'resource') {\n // For resources, include URI and mimeType in searchable text\n schemaTextLower = `${capability.uri} ${capability.mimeType || ''}`.toLowerCase();\n }\n\n for (const term of queryTerms) {\n const termLower = term.toLowerCase();\n\n // Check name matches\n if (searchFields.includes('name')) {\n if (nameLower === termLower) {\n totalScore += EXACT_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n } else if (nameLower.includes(termLower)) {\n totalScore += PARTIAL_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n }\n }\n\n // Check description matches\n if (searchFields.includes('description') && descLower.includes(termLower)) {\n totalScore += DESCRIPTION_WEIGHT;\n if (!matchedOn.includes('description')) matchedOn.push('description');\n }\n\n // Check schema/arguments matches\n if (searchFields.includes('schema') && schemaTextLower.includes(termLower)) {\n totalScore += SCHEMA_WEIGHT;\n const fieldName = capability.type === 'tool' ? 'inputSchema' : capability.type === 'prompt' ? 'arguments' : 'uri';\n if (!matchedOn.includes(fieldName)) matchedOn.push(fieldName);\n }\n\n // Check server name matches\n if (searchFields.includes('server') && serverLower.includes(termLower)) {\n totalScore += SERVER_WEIGHT;\n if (!matchedOn.includes('server')) matchedOn.push('server');\n }\n }\n\n // Normalize score to 0-1 range based on number of terms\n const normalizedScore = queryTerms.length > 0 ? Math.min(1, totalScore / queryTerms.length) : 0;\n\n return { score: normalizedScore, matchedOn };\n}\n\n/**\n * Search for capabilities matching a query string\n */\nexport function searchCapabilities(index: CapabilityIndex, query: string, options: SearchOptions = {}): SearchResponse {\n const { types = DEFAULT_TYPES, servers, searchFields = DEFAULT_SEARCH_FIELDS, limit = DEFAULT_LIMIT, threshold = DEFAULT_THRESHOLD } = options;\n\n // Tokenize query into search terms\n const queryTerms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0);\n\n // If empty query, return empty results\n if (queryTerms.length === 0) {\n return { query, results: [], total: 0 };\n }\n\n // Filter and score capabilities\n const scoredResults: Array<{ capability: IndexedCapability; score: number; matchedOn: string[] }> = [];\n\n for (const capability of index.capabilities) {\n // Filter by type\n if (!types.includes(capability.type)) {\n continue;\n }\n\n // Filter by server\n if (servers && servers.length > 0 && !servers.includes(capability.server)) {\n continue;\n }\n\n // Score the capability\n const { score, matchedOn } = scoreCapability(capability, queryTerms, searchFields);\n\n // Apply threshold filter\n if (score >= threshold && matchedOn.length > 0) {\n scoredResults.push({ capability, score, matchedOn });\n }\n }\n\n // Sort by score descending\n scoredResults.sort((a, b) => b.score - a.score);\n\n // Get total before limiting\n const total = scoredResults.length;\n\n // Apply limit and transform to SearchResult\n const results: SearchResult[] = scoredResults.slice(0, limit).map(({ capability, score, matchedOn }) => ({\n type: capability.type,\n server: capability.server,\n name: capability.name,\n description: capability.description,\n matchedOn,\n score,\n }));\n\n return { query, results, total };\n}\n\n/**\n * Convenience function to search directly from connected clients\n * Builds index and performs search in one call\n */\nexport async function search(clients: Map<string, CapabilityClient>, query: string, options: SearchOptions = {}): Promise<SearchResponse> {\n const index = await buildCapabilityIndex(clients);\n return searchCapabilities(index, query, options);\n}\n"],"names":["buildCapabilityIndex","search","searchCapabilities","DEFAULT_LIMIT","DEFAULT_THRESHOLD","DEFAULT_TYPES","DEFAULT_SEARCH_FIELDS","extractSchemaText","inputSchema","schema","parts","description","push","properties","Object","entries","propName","prop","join","extractArgumentsText","args","Array","isArray","map","arg","name","clients","capabilities","servers","serverName","client","toolsResult","promptsResult","resourcesResult","tool","prompt","resource","Promise","all","listTools","catch","listPrompts","listResources","tools","type","server","schemaText","prompts","argumentsText","arguments","resources","uri","mimeType","indexedAt","Date","scoreCapability","capability","queryTerms","searchFields","matchedOn","totalScore","EXACT_NAME_WEIGHT","PARTIAL_NAME_WEIGHT","DESCRIPTION_WEIGHT","SCHEMA_WEIGHT","SERVER_WEIGHT","nameLower","toLowerCase","descLower","serverLower","schemaTextLower","term","termLower","includes","fieldName","normalizedScore","length","Math","min","score","index","query","options","types","limit","threshold","split","filter","results","total","scoredResults","sort","a","b","slice"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QAoEqBA;eAAAA;;QA+LAC;eAAAA;;QA5DNC;eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA/LhB,IAAMC,gBAAgB;AACtB,IAAMC,oBAAoB;AAC1B,IAAMC,gBAAkC;IAAC;IAAQ;IAAU;CAAW;AACtE,IAAMC,wBAAuC;IAAC;IAAQ;IAAe;CAAS;AAE9E;;CAE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