@mcp-z/client 1.2.0 → 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.
- package/README.md +22 -0
- package/dist/cjs/auth/capability-discovery.js +16 -6
- package/dist/cjs/auth/capability-discovery.js.map +1 -1
- package/dist/cjs/auth/discovery-fetch.d.cts +22 -2
- package/dist/cjs/auth/discovery-fetch.d.ts +22 -2
- package/dist/cjs/auth/discovery-fetch.js +440 -124
- package/dist/cjs/auth/discovery-fetch.js.map +1 -1
- package/dist/cjs/auth/interactive-oauth-flow.d.cts +9 -2
- package/dist/cjs/auth/interactive-oauth-flow.d.ts +9 -2
- package/dist/cjs/auth/interactive-oauth-flow.js +29 -11
- package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
- package/dist/cjs/auth/oauth-callback-listener.js +4 -0
- package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
- package/dist/cjs/auth/types.d.cts +29 -4
- package/dist/cjs/auth/types.d.ts +29 -4
- package/dist/cjs/auth/types.js.map +1 -1
- package/dist/cjs/client-helpers.d.cts +5 -6
- package/dist/cjs/client-helpers.d.ts +5 -6
- package/dist/cjs/client-helpers.js +8 -8
- package/dist/cjs/client-helpers.js.map +1 -1
- package/dist/cjs/connection/connect-client.d.cts +12 -11
- package/dist/cjs/connection/connect-client.d.ts +12 -11
- package/dist/cjs/connection/connect-client.js +31 -47
- package/dist/cjs/connection/connect-client.js.map +1 -1
- package/dist/cjs/connection/existing-process-transport.d.cts +1 -2
- package/dist/cjs/connection/existing-process-transport.d.ts +1 -2
- package/dist/cjs/connection/existing-process-transport.js +3 -3
- package/dist/cjs/connection/existing-process-transport.js.map +1 -1
- package/dist/cjs/dcr/dcr-authenticator.d.cts +36 -5
- package/dist/cjs/dcr/dcr-authenticator.d.ts +36 -5
- package/dist/cjs/dcr/dcr-authenticator.js +473 -57
- package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
- package/dist/cjs/dcr/dynamic-client-registrar.d.cts +2 -2
- package/dist/cjs/dcr/dynamic-client-registrar.d.ts +2 -2
- package/dist/cjs/dcr/dynamic-client-registrar.js +10 -11
- package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
- package/dist/cjs/index.d.cts +2 -0
- package/dist/cjs/index.d.ts +2 -0
- package/dist/cjs/index.js +8 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/lib/url-utils.d.cts +17 -0
- package/dist/cjs/lib/url-utils.d.ts +17 -0
- package/dist/cjs/lib/url-utils.js +22 -2
- package/dist/cjs/lib/url-utils.js.map +1 -1
- package/dist/cjs/response-wrappers.d.cts +1 -1
- package/dist/cjs/response-wrappers.d.ts +1 -1
- package/dist/cjs/response-wrappers.js.map +1 -1
- package/dist/cjs/search/search.d.cts +1 -1
- package/dist/cjs/search/search.d.ts +1 -1
- package/dist/cjs/search/search.js.map +1 -1
- package/dist/esm/auth/capability-discovery.js +16 -6
- package/dist/esm/auth/capability-discovery.js.map +1 -1
- package/dist/esm/auth/discovery-fetch.d.ts +22 -2
- package/dist/esm/auth/discovery-fetch.js +234 -54
- package/dist/esm/auth/discovery-fetch.js.map +1 -1
- package/dist/esm/auth/interactive-oauth-flow.d.ts +9 -2
- package/dist/esm/auth/interactive-oauth-flow.js +28 -10
- package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
- package/dist/esm/auth/oauth-callback-listener.js +4 -0
- package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
- package/dist/esm/auth/types.d.ts +29 -4
- package/dist/esm/auth/types.js.map +1 -1
- package/dist/esm/client-helpers.d.ts +5 -6
- package/dist/esm/client-helpers.js +8 -8
- package/dist/esm/client-helpers.js.map +1 -1
- package/dist/esm/connection/connect-client.d.ts +12 -11
- package/dist/esm/connection/connect-client.js +32 -38
- package/dist/esm/connection/connect-client.js.map +1 -1
- package/dist/esm/connection/existing-process-transport.d.ts +1 -2
- package/dist/esm/connection/existing-process-transport.js +1 -1
- package/dist/esm/connection/existing-process-transport.js.map +1 -1
- package/dist/esm/dcr/dcr-authenticator.d.ts +36 -5
- package/dist/esm/dcr/dcr-authenticator.js +129 -52
- package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
- package/dist/esm/dcr/dynamic-client-registrar.d.ts +2 -2
- package/dist/esm/dcr/dynamic-client-registrar.js +7 -6
- package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +4 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lib/url-utils.d.ts +17 -0
- package/dist/esm/lib/url-utils.js +34 -2
- package/dist/esm/lib/url-utils.js.map +1 -1
- package/dist/esm/response-wrappers.d.ts +1 -1
- package/dist/esm/response-wrappers.js.map +1 -1
- package/dist/esm/search/search.d.ts +1 -1
- package/dist/esm/search/search.js.map +1 -1
- package/package.json +4 -4
- package/dist/cjs/monkey-patches.d.cts +0 -6
- package/dist/cjs/monkey-patches.d.ts +0 -6
- package/dist/cjs/monkey-patches.js +0 -233
- package/dist/cjs/monkey-patches.js.map +0 -1
- package/dist/esm/monkey-patches.d.ts +0 -6
- package/dist/esm/monkey-patches.js +0 -32
- package/dist/esm/monkey-patches.js.map +0 -1
|
@@ -7,11 +7,27 @@ import Keyv from 'keyv';
|
|
|
7
7
|
import { KeyvFile } from 'keyv-file';
|
|
8
8
|
import { isLoopbackUrl } from '../auth/discovery-fetch.js';
|
|
9
9
|
import { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.js';
|
|
10
|
+
import { extractBaseUrl, normalizeUrl } from '../lib/url-utils.js';
|
|
10
11
|
import { logger as defaultLogger } from '../utils/logger.js';
|
|
11
12
|
import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
12
13
|
/**
|
|
13
14
|
* Buffer time before token expiry to trigger proactive refresh (5 minutes)
|
|
14
15
|
*/ const REFRESH_BUFFER_MS = 5 * 60 * 1000;
|
|
16
|
+
/** Raised when a credential cannot be bound to, or looked up by, an issuer. */ let CredentialBindingError = class CredentialBindingError extends Error {
|
|
17
|
+
constructor(message){
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'CredentialBindingError';
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The issuer credentials are keyed by, so they can never be presented to a
|
|
24
|
+
* different authorization server even when the resource keeps its URL (SEP-2352).
|
|
25
|
+
*/ function requireIssuer(capabilities) {
|
|
26
|
+
if (!capabilities.issuer) {
|
|
27
|
+
throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');
|
|
28
|
+
}
|
|
29
|
+
return capabilities.issuer;
|
|
30
|
+
}
|
|
15
31
|
/**
|
|
16
32
|
* DcrAuthenticator manages authentication for MCP HTTP servers
|
|
17
33
|
* Handles DCR registration, OAuth flows, and token management
|
|
@@ -19,13 +35,13 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
|
19
35
|
/**
|
|
20
36
|
* Detect if server is self-hosted DCR (vs external OAuth provider)
|
|
21
37
|
* Self-hosted servers have their own OAuth endpoints and manage token storage
|
|
22
|
-
*/ async detectSelfHostedMode(
|
|
38
|
+
*/ async detectSelfHostedMode(mcpServerUrl) {
|
|
23
39
|
try {
|
|
24
40
|
// Self-hosted DCR servers typically run their own OAuth server
|
|
25
41
|
// Check if this is a self-hosted instance by testing OAuth metadata
|
|
26
|
-
// For now, assume self-hosted if
|
|
42
|
+
// For now, assume self-hosted if the URL matches common localhost patterns
|
|
27
43
|
// TODO: Implement proper self-hosted detection logic
|
|
28
|
-
return
|
|
44
|
+
return mcpServerUrl.includes('localhost') || mcpServerUrl.includes('127.0.0.1');
|
|
29
45
|
} catch (_error) {
|
|
30
46
|
return false; // Assume external mode if detection fails
|
|
31
47
|
}
|
|
@@ -34,7 +50,9 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
|
34
50
|
* Ensure server is authenticated, performing DCR and OAuth if needed
|
|
35
51
|
* Proactively refreshes tokens if they're within 5 minutes of expiry
|
|
36
52
|
*
|
|
37
|
-
* @param
|
|
53
|
+
* @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,
|
|
54
|
+
* with its path intact (`https://example.com/mcp`). Not a deployment root:
|
|
55
|
+
* the path is what identifies the resource an issued token is bound to.
|
|
38
56
|
* @param capabilities - Auth capabilities from .well-known endpoint
|
|
39
57
|
* @returns Valid token set ready to use
|
|
40
58
|
*
|
|
@@ -43,31 +61,59 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
|
43
61
|
* @example
|
|
44
62
|
* const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });
|
|
45
63
|
* const tokens = await authenticator.ensureAuthenticated(
|
|
46
|
-
* 'https://example.com',
|
|
64
|
+
* 'https://example.com/mcp',
|
|
47
65
|
* capabilities
|
|
48
66
|
* );
|
|
49
|
-
*/ async ensureAuthenticated(
|
|
67
|
+
*/ async ensureAuthenticated(mcpServerUrl, capabilities) {
|
|
50
68
|
// Auto-detect server mode
|
|
51
|
-
const isSelfHosted = await this.detectSelfHostedMode(
|
|
69
|
+
const isSelfHosted = await this.detectSelfHostedMode(mcpServerUrl);
|
|
52
70
|
if (isSelfHosted) {
|
|
53
|
-
return this.ensureAuthenticatedSelfHosted(
|
|
71
|
+
return this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities);
|
|
54
72
|
}
|
|
55
|
-
return this.ensureAuthenticatedExternal(
|
|
73
|
+
return this.ensureAuthenticatedExternal(mcpServerUrl, capabilities);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The three things a server URL is used for here, kept apart on purpose.
|
|
77
|
+
*
|
|
78
|
+
* They were one value once, and collapsing them is what sent an authorization
|
|
79
|
+
* server the wrong audience: `resource` was derived from the deployment root,
|
|
80
|
+
* so a server at `https://host/mcp` was asked to mint a token for
|
|
81
|
+
* `https://host`, and any server that validates the indicator answered
|
|
82
|
+
* `invalid_target`.
|
|
83
|
+
*
|
|
84
|
+
* - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a
|
|
85
|
+
* trailing `/mcp` comes off.
|
|
86
|
+
* - `resource` is the RFC 8707 audience. The resource server names itself in
|
|
87
|
+
* its RFC 9728 metadata; that name wins. Only when no such document exists
|
|
88
|
+
* do we fall back to the URL we were configured with.
|
|
89
|
+
* - `storeKey` identifies the credential locally. It stays the configured URL
|
|
90
|
+
* rather than the discovered `resource`, so it can be computed without a
|
|
91
|
+
* network round trip - `deleteTokens` has only the URL to work from.
|
|
92
|
+
*/ resolveUrls(mcpServerUrl, capabilities) {
|
|
93
|
+
var _capabilities_resource;
|
|
94
|
+
const storeKey = normalizeUrl(mcpServerUrl);
|
|
95
|
+
return {
|
|
96
|
+
serverBaseUrl: extractBaseUrl(mcpServerUrl),
|
|
97
|
+
resource: (_capabilities_resource = capabilities.resource) !== null && _capabilities_resource !== void 0 ? _capabilities_resource : storeKey,
|
|
98
|
+
storeKey
|
|
99
|
+
};
|
|
56
100
|
}
|
|
57
101
|
/**
|
|
58
102
|
* Handle authentication for self-hosted DCR servers
|
|
59
103
|
* Self-hosted servers manage their own token storage via /oauth/verify
|
|
60
|
-
*/ async ensureAuthenticatedSelfHosted(
|
|
104
|
+
*/ async ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities) {
|
|
61
105
|
// Loopback trust for every discovery-derived fetch below, computed from
|
|
62
106
|
// the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).
|
|
63
|
-
const allowLoopback = isLoopbackUrl(
|
|
64
|
-
const
|
|
107
|
+
const allowLoopback = isLoopbackUrl(mcpServerUrl);
|
|
108
|
+
const issuer = requireIssuer(capabilities);
|
|
109
|
+
const { serverBaseUrl, resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);
|
|
110
|
+
const dcrTokenKey = `dcr-tokens:${issuer}:${storeKey}`;
|
|
65
111
|
// 1. Check for existing DCR tokens (different from external tokens)
|
|
66
|
-
let tokens = await this.
|
|
112
|
+
let tokens = await this.loadTokens(dcrTokenKey, issuer);
|
|
67
113
|
if (tokens) {
|
|
68
114
|
// 2. Verify token is still valid by calling /oauth/verify
|
|
69
115
|
try {
|
|
70
|
-
const verifyUrl = `${
|
|
116
|
+
const verifyUrl = `${serverBaseUrl}/oauth/verify`;
|
|
71
117
|
const verifyResponse = await fetch(verifyUrl, {
|
|
72
118
|
headers: {
|
|
73
119
|
Authorization: `Bearer ${tokens.accessToken}`,
|
|
@@ -102,21 +148,11 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
|
102
148
|
allowLoopback
|
|
103
149
|
});
|
|
104
150
|
// Perform OAuth authorization flow with PKCE (RFC 7636)
|
|
105
|
-
const flowOptions =
|
|
106
|
-
port,
|
|
107
|
-
headless: this.headless,
|
|
108
|
-
redirectUri: this.redirectUri,
|
|
109
|
-
pkce: true,
|
|
110
|
-
logger: this.logger,
|
|
111
|
-
allowLoopback
|
|
112
|
-
};
|
|
113
|
-
if (capabilities.scopes) {
|
|
114
|
-
flowOptions.scopes = capabilities.scopes;
|
|
115
|
-
}
|
|
151
|
+
const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
|
|
116
152
|
tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);
|
|
117
153
|
// For self-hosted mode, verify the token works with /oauth/verify immediately
|
|
118
154
|
try {
|
|
119
|
-
const verifyUrl = `${
|
|
155
|
+
const verifyUrl = `${serverBaseUrl}/oauth/verify`;
|
|
120
156
|
const verifyResponse = await fetch(verifyUrl, {
|
|
121
157
|
headers: {
|
|
122
158
|
Authorization: `Bearer ${tokens.accessToken}`,
|
|
@@ -136,23 +172,31 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
|
136
172
|
throw new Error('Self-hosted DCR authentication completed but token verification failed');
|
|
137
173
|
}
|
|
138
174
|
// Save tokens for future use
|
|
139
|
-
await this.tokenStore.set(dcrTokenKey,
|
|
175
|
+
await this.tokenStore.set(dcrTokenKey, {
|
|
176
|
+
...tokens,
|
|
177
|
+
issuer
|
|
178
|
+
});
|
|
140
179
|
this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');
|
|
141
180
|
return tokens;
|
|
142
181
|
}
|
|
143
|
-
/** Handles authentication for external (non-self-hosted) OAuth providers. */ async ensureAuthenticatedExternal(
|
|
182
|
+
/** Handles authentication for external (non-self-hosted) OAuth providers. */ async ensureAuthenticatedExternal(mcpServerUrl, capabilities) {
|
|
144
183
|
// See ensureAuthenticatedSelfHosted - same loopback trust rule.
|
|
145
|
-
const allowLoopback = isLoopbackUrl(
|
|
146
|
-
const
|
|
184
|
+
const allowLoopback = isLoopbackUrl(mcpServerUrl);
|
|
185
|
+
const issuer = requireIssuer(capabilities);
|
|
186
|
+
const { resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);
|
|
187
|
+
const tokenKey = `tokens:${issuer}:${storeKey}`;
|
|
147
188
|
// 1. Check for existing tokens
|
|
148
|
-
let tokens = await this.
|
|
189
|
+
let tokens = await this.loadTokens(tokenKey, issuer);
|
|
149
190
|
if (tokens) {
|
|
150
191
|
// 2. Proactive refresh if token expires within 5 minutes
|
|
151
192
|
if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {
|
|
152
193
|
this.logger.debug('🔄 Refreshing access token...');
|
|
153
194
|
try {
|
|
154
|
-
tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, allowLoopback);
|
|
155
|
-
await this.tokenStore.set(tokenKey,
|
|
195
|
+
tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback);
|
|
196
|
+
await this.tokenStore.set(tokenKey, {
|
|
197
|
+
...tokens,
|
|
198
|
+
issuer
|
|
199
|
+
});
|
|
156
200
|
this.logger.debug('✅ Token refreshed successfully');
|
|
157
201
|
} catch (_error) {
|
|
158
202
|
// Refresh failed - clear tokens and re-authenticate
|
|
@@ -179,27 +223,21 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
|
179
223
|
allowLoopback
|
|
180
224
|
});
|
|
181
225
|
// Perform OAuth authorization flow with PKCE (RFC 7636)
|
|
182
|
-
const flowOptions =
|
|
183
|
-
port,
|
|
184
|
-
headless: this.headless,
|
|
185
|
-
redirectUri: this.redirectUri,
|
|
186
|
-
pkce: true,
|
|
187
|
-
logger: this.logger,
|
|
188
|
-
allowLoopback
|
|
189
|
-
};
|
|
190
|
-
if (capabilities.scopes) {
|
|
191
|
-
flowOptions.scopes = capabilities.scopes;
|
|
192
|
-
}
|
|
226
|
+
const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
|
|
193
227
|
tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);
|
|
194
228
|
// Save tokens for future use
|
|
195
|
-
await this.tokenStore.set(tokenKey,
|
|
229
|
+
await this.tokenStore.set(tokenKey, {
|
|
230
|
+
...tokens,
|
|
231
|
+
issuer
|
|
232
|
+
});
|
|
196
233
|
this.logger.debug('✅ Authentication successful, tokens saved');
|
|
197
234
|
return tokens;
|
|
198
235
|
}
|
|
199
236
|
/**
|
|
200
237
|
* Refreshes an access token using a refresh token.
|
|
238
|
+
* @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
|
|
201
239
|
* @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.
|
|
202
|
-
*/ async refreshTokens(tokens, tokenEndpoint, allowLoopback = false) {
|
|
240
|
+
*/ async refreshTokens(tokens, tokenEndpoint, resource, allowLoopback = false) {
|
|
203
241
|
if (!tokenEndpoint) {
|
|
204
242
|
throw new Error('Token endpoint not available for refresh');
|
|
205
243
|
}
|
|
@@ -209,14 +247,53 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
|
|
|
209
247
|
if (!tokens.clientId || !tokens.clientSecret) {
|
|
210
248
|
throw new Error('Client credentials not available for refresh');
|
|
211
249
|
}
|
|
212
|
-
return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, allowLoopback);
|
|
250
|
+
return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback);
|
|
213
251
|
}
|
|
214
252
|
/**
|
|
215
|
-
*
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
253
|
+
* Deletes both stored token families for a server, across every issuer they were bound to.
|
|
254
|
+
*
|
|
255
|
+
* Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}
|
|
256
|
+
* was given - keys are built from the configured URL, never from the discovered
|
|
257
|
+
* RFC 8707 resource, precisely so this can find them without doing discovery.
|
|
258
|
+
*
|
|
259
|
+
* @throws CredentialBindingError if the configured store cannot enumerate keys.
|
|
260
|
+
*/ async deleteTokens(mcpServerUrl) {
|
|
261
|
+
const suffix = `:${normalizeUrl(mcpServerUrl)}`;
|
|
262
|
+
if (!this.tokenStore.iterator) {
|
|
263
|
+
throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');
|
|
264
|
+
}
|
|
265
|
+
for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)){
|
|
266
|
+
if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {
|
|
267
|
+
await this.tokenStore.delete(key);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
this.logger.debug(`🗑️ Deleted tokens for ${mcpServerUrl}`);
|
|
271
|
+
}
|
|
272
|
+
/** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */ async loadTokens(key, issuer) {
|
|
273
|
+
const tokens = await this.tokenStore.get(key);
|
|
274
|
+
if (!tokens) return undefined;
|
|
275
|
+
if (tokens.issuer === issuer) return tokens;
|
|
276
|
+
this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');
|
|
277
|
+
await this.tokenStore.delete(key);
|
|
278
|
+
return undefined;
|
|
279
|
+
}
|
|
280
|
+
buildFlowOptions(port, capabilities, issuer, resource, allowLoopback) {
|
|
281
|
+
var _capabilities_authorizationResponseIssSupported;
|
|
282
|
+
const flowOptions = {
|
|
283
|
+
port,
|
|
284
|
+
issuer,
|
|
285
|
+
resource,
|
|
286
|
+
headless: this.headless,
|
|
287
|
+
redirectUri: this.redirectUri,
|
|
288
|
+
pkce: true,
|
|
289
|
+
logger: this.logger,
|
|
290
|
+
allowLoopback,
|
|
291
|
+
authorizationResponseIssSupported: (_capabilities_authorizationResponseIssSupported = capabilities.authorizationResponseIssSupported) !== null && _capabilities_authorizationResponseIssSupported !== void 0 ? _capabilities_authorizationResponseIssSupported : false
|
|
292
|
+
};
|
|
293
|
+
if (capabilities.scopes) {
|
|
294
|
+
flowOptions.scopes = capabilities.scopes;
|
|
295
|
+
}
|
|
296
|
+
return flowOptions;
|
|
220
297
|
}
|
|
221
298
|
constructor(options){
|
|
222
299
|
var _options_logger;
|
|
@@ -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 const tokenKey = `tokens:${baseUrl}`;\n await this.tokenStore.delete(tokenKey);\n this.logger.debug(`🗑️ Deleted tokens for ${baseUrl}`);\n }\n}\n"],"names":["path","fs","Keyv","KeyvFile","isLoopbackUrl","InteractiveOAuthFlow","logger","defaultLogger","DynamicClientRegistrar","REFRESH_BUFFER_MS","DcrAuthenticator","detectSelfHostedMode","baseUrl","includes","_error","ensureAuthenticated","capabilities","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","allowLoopback","dcrTokenKey","tokens","tokenStore","get","verifyUrl","verifyResponse","fetch","headers","Authorization","accessToken","Connection","ok","verifyData","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","Error","debug","port","parseInt","URL","redirectUri","startsWith","client","dcrClient","registerClient","flowOptions","headless","pkce","scopes","oauthFlow","performAuthFlow","clientId","clientSecret","status","error","message","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","options","storePath","join","process","cwd","mkdirSync","dirname","recursive","store","filename"],"mappings":"AAAA;;;CAGC,GAED,OA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ChD3E,GAAG4E,SAAS,CAAC7E,KAAK8E,OAAO,CAACL,YAAY;gBAAEM,WAAW;YAAK;YAExD,IAAI,CAACxD,UAAU,GAAG,IAAIrB,KAAK;gBACzB8E,OAAO,IAAI7E,SAAS;oBAAE8E,UAAUR;gBAAU;YAC5C;QACF;QACA,IAAI,CAACxB,SAAS,GAAG,IAAIzC;QACrB,IAAI,CAAC+C,SAAS,GAAG,IAAIlD;QACrB,IAAI,CAAC+C,QAAQ,GAAGoB,QAAQpB,QAAQ,IAAI;QACpC,IAAI,CAACN,WAAW,GAAG0B,QAAQ1B,WAAW;QACtC,IAAI,CAACxC,MAAM,IAAGkE,kBAAAA,QAAQlE,MAAM,cAAdkE,6BAAAA,kBAAkBjE;IAClC;AAiPF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dcr-authenticator.ts"],"sourcesContent":["/**\n * DCR Authenticator\n * Consolidates DCR and OAuth flow logic for MCP HTTP servers\n */\n\nimport path from 'node:path';\nimport * as fs from 'fs';\nimport Keyv from 'keyv';\nimport { KeyvFile } from 'keyv-file';\nimport { isLoopbackUrl } from '../auth/discovery-fetch.ts';\nimport { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.ts';\nimport type { AuthCapabilities, OAuthFlowOptions, TokenSet } from '../auth/types.ts';\nimport { extractBaseUrl, normalizeUrl } from '../lib/url-utils.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { DynamicClientRegistrar } from './dynamic-client-registrar.ts';\n\n/**\n * DcrAuthenticator configuration options\n */\nexport interface DcrAuthenticatorOptions {\n /** Custom Keyv store (for testing) - if not provided, uses default ~/.mcpeasy/tokens.json */\n tokenStore?: Keyv;\n /** Headless mode (don't open browser) */\n headless?: boolean;\n /** Required redirect URI for OAuth callback */\n redirectUri: string;\n /** Optional logger for debug output (defaults to singleton logger) */\n logger?: Logger;\n}\n\n/**\n * Buffer time before token expiry to trigger proactive refresh (5 minutes)\n */\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/** Raised when a credential cannot be bound to, or looked up by, an issuer. */\nclass CredentialBindingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CredentialBindingError';\n }\n}\n\n/**\n * The issuer credentials are keyed by, so they can never be presented to a\n * different authorization server even when the resource keeps its URL (SEP-2352).\n */\nfunction requireIssuer(capabilities: AuthCapabilities): string {\n if (!capabilities.issuer) {\n throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');\n }\n return capabilities.issuer;\n}\n\n/**\n * DcrAuthenticator manages authentication for MCP HTTP servers\n * Handles DCR registration, OAuth flows, and token management\n */\nexport class DcrAuthenticator {\n private tokenStore: Keyv;\n private dcrClient: DynamicClientRegistrar;\n private oauthFlow: InteractiveOAuthFlow;\n private headless: boolean;\n private redirectUri: string;\n private logger: Logger;\n\n constructor(options: DcrAuthenticatorOptions) {\n if (options.tokenStore) {\n this.tokenStore = options.tokenStore;\n } else {\n // Default CLI store in .mcp-z directory (per-project)\n const storePath = path.join(process.cwd(), '.mcp-z', 'tokens.json');\n\n // Ensure directory exists before creating store\n fs.mkdirSync(path.dirname(storePath), { recursive: true });\n\n this.tokenStore = new Keyv({\n store: new KeyvFile({ filename: storePath }),\n });\n }\n this.dcrClient = new DynamicClientRegistrar();\n this.oauthFlow = new InteractiveOAuthFlow();\n this.headless = options.headless || false;\n this.redirectUri = options.redirectUri;\n this.logger = options.logger ?? defaultLogger;\n }\n\n /**\n * Detect if server is self-hosted DCR (vs external OAuth provider)\n * Self-hosted servers have their own OAuth endpoints and manage token storage\n */\n private async detectSelfHostedMode(mcpServerUrl: string): Promise<boolean> {\n try {\n // Self-hosted DCR servers typically run their own OAuth server\n // Check if this is a self-hosted instance by testing OAuth metadata\n // For now, assume self-hosted if the URL matches common localhost patterns\n // TODO: Implement proper self-hosted detection logic\n return mcpServerUrl.includes('localhost') || mcpServerUrl.includes('127.0.0.1');\n } catch (_error) {\n return false; // Assume external mode if detection fails\n }\n }\n\n /**\n * Ensure server is authenticated, performing DCR and OAuth if needed\n * Proactively refreshes tokens if they're within 5 minutes of expiry\n *\n * @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,\n * with its path intact (`https://example.com/mcp`). Not a deployment root:\n * the path is what identifies the resource an issued token is bound to.\n * @param capabilities - Auth capabilities from .well-known endpoint\n * @returns Valid token set ready to use\n *\n * @throws Error if authentication fails\n *\n * @example\n * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });\n * const tokens = await authenticator.ensureAuthenticated(\n * 'https://example.com/mcp',\n * capabilities\n * );\n */\n async ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Auto-detect server mode\n const isSelfHosted = await this.detectSelfHostedMode(mcpServerUrl);\n\n if (isSelfHosted) {\n return this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities);\n }\n return this.ensureAuthenticatedExternal(mcpServerUrl, capabilities);\n }\n\n /**\n * The three things a server URL is used for here, kept apart on purpose.\n *\n * They were one value once, and collapsing them is what sent an authorization\n * server the wrong audience: `resource` was derived from the deployment root,\n * so a server at `https://host/mcp` was asked to mint a token for\n * `https://host`, and any server that validates the indicator answered\n * `invalid_target`.\n *\n * - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a\n * trailing `/mcp` comes off.\n * - `resource` is the RFC 8707 audience. The resource server names itself in\n * its RFC 9728 metadata; that name wins. Only when no such document exists\n * do we fall back to the URL we were configured with.\n * - `storeKey` identifies the credential locally. It stays the configured URL\n * rather than the discovered `resource`, so it can be computed without a\n * network round trip - `deleteTokens` has only the URL to work from.\n */\n private resolveUrls(mcpServerUrl: string, capabilities: AuthCapabilities): { serverBaseUrl: string; resource: string; storeKey: string } {\n const storeKey = normalizeUrl(mcpServerUrl);\n return { serverBaseUrl: extractBaseUrl(mcpServerUrl), resource: capabilities.resource ?? storeKey, storeKey };\n }\n\n /**\n * Handle authentication for self-hosted DCR servers\n * Self-hosted servers manage their own token storage via /oauth/verify\n */\n private async ensureAuthenticatedSelfHosted(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Loopback trust for every discovery-derived fetch below, computed from\n // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { serverBaseUrl, resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const dcrTokenKey = `dcr-tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = await this.loadTokens(dcrTokenKey, issuer);\n\n if (tokens) {\n // 2. Verify token is still valid by calling /oauth/verify\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (verifyResponse.ok) {\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token === tokens.accessToken) {\n // Token is still valid with the self-hosted server\n return tokens;\n }\n }\n } catch (_error) {\n // Token verification failed - need to re-authenticate\n }\n\n // Token is expired or invalid\n await this.tokenStore.delete(dcrTokenKey);\n tokens = undefined;\n }\n\n // 3. No valid tokens - perform full DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting self-hosted DCR authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client with self-hosted server...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // For self-hosted mode, verify the token works with /oauth/verify immediately\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (!verifyResponse.ok) {\n throw new Error(`DCR token verification failed after authentication: ${verifyResponse.status}`);\n }\n\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token !== tokens.accessToken) {\n throw new Error('DCR server returned different token in verification');\n }\n\n this.logger.debug('✅ DCR token verified with self-hosted server');\n } catch (error) {\n this.logger.error('❌ DCR token verification failed:', error instanceof Error ? error.message : String(error));\n throw new Error('Self-hosted DCR authentication completed but token verification failed');\n }\n\n // Save tokens for future use\n await this.tokenStore.set(dcrTokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');\n\n return tokens;\n }\n\n /** Handles authentication for external (non-self-hosted) OAuth providers. */\n private async ensureAuthenticatedExternal(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // See ensureAuthenticatedSelfHosted - same loopback trust rule.\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const tokenKey = `tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing tokens\n let tokens = await this.loadTokens(tokenKey, issuer);\n\n if (tokens) {\n // 2. Proactive refresh if token expires within 5 minutes\n if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {\n this.logger.debug('🔄 Refreshing access token...');\n\n try {\n tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback);\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Token refreshed successfully');\n } catch (_error) {\n // Refresh failed - clear tokens and re-authenticate\n this.logger.warn('⚠️ Token refresh failed, re-authenticating...');\n await this.tokenStore.delete(tokenKey);\n tokens = undefined;\n }\n }\n\n if (tokens) {\n return tokens;\n }\n }\n\n // 3. No valid tokens - perform DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting external OAuth authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // Save tokens for future use\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Refreshes an access token using a refresh token.\n * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).\n * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.\n */\n private async refreshTokens(tokens: TokenSet, tokenEndpoint: string | undefined, resource: string, allowLoopback = false): Promise<TokenSet> {\n if (!tokenEndpoint) {\n throw new Error('Token endpoint not available for refresh');\n }\n\n if (!tokens.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n if (!tokens.clientId || !tokens.clientSecret) {\n throw new Error('Client credentials not available for refresh');\n }\n\n return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback);\n }\n\n /**\n * Deletes both stored token families for a server, across every issuer they were bound to.\n *\n * Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}\n * was given - keys are built from the configured URL, never from the discovered\n * RFC 8707 resource, precisely so this can find them without doing discovery.\n *\n * @throws CredentialBindingError if the configured store cannot enumerate keys.\n */\n async deleteTokens(mcpServerUrl: string): Promise<void> {\n const suffix = `:${normalizeUrl(mcpServerUrl)}`;\n if (!this.tokenStore.iterator) {\n throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');\n }\n\n for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)) {\n if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {\n await this.tokenStore.delete(key);\n }\n }\n this.logger.debug(`🗑️ Deleted tokens for ${mcpServerUrl}`);\n }\n\n /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */\n private async loadTokens(key: string, issuer: string): Promise<TokenSet | undefined> {\n const tokens = (await this.tokenStore.get(key)) as TokenSet | undefined;\n if (!tokens) return undefined;\n if (tokens.issuer === issuer) return tokens;\n\n this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');\n await this.tokenStore.delete(key);\n return undefined;\n }\n\n private buildFlowOptions(port: number, capabilities: AuthCapabilities, issuer: string, resource: string, allowLoopback: boolean): OAuthFlowOptions {\n const flowOptions: OAuthFlowOptions = {\n port,\n issuer,\n resource,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n authorizationResponseIssSupported: capabilities.authorizationResponseIssSupported ?? false,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n return flowOptions;\n }\n}\n"],"names":["path","fs","Keyv","KeyvFile","isLoopbackUrl","InteractiveOAuthFlow","extractBaseUrl","normalizeUrl","logger","defaultLogger","DynamicClientRegistrar","REFRESH_BUFFER_MS","CredentialBindingError","Error","message","name","requireIssuer","capabilities","issuer","DcrAuthenticator","detectSelfHostedMode","mcpServerUrl","includes","_error","ensureAuthenticated","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","resolveUrls","storeKey","serverBaseUrl","resource","allowLoopback","dcrTokenKey","tokens","loadTokens","verifyUrl","verifyResponse","fetch","headers","Authorization","accessToken","Connection","ok","verifyData","json","token","tokenStore","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","port","parseInt","URL","redirectUri","startsWith","client","dcrClient","registerClient","flowOptions","buildFlowOptions","oauthFlow","performAuthFlow","clientId","clientSecret","status","error","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","iterator","key","namespace","endsWith","get","headless","pkce","authorizationResponseIssSupported","scopes","options","storePath","join","process","cwd","mkdirSync","dirname","recursive","store","filename"],"mappings":"AAAA;;;CAGC,GAED,OAAOA,UAAU,YAAY;AAC7B,YAAYC,QAAQ,KAAK;AACzB,OAAOC,UAAU,OAAO;AACxB,SAASC,QAAQ,QAAQ,YAAY;AACrC,SAASC,aAAa,QAAQ,6BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,oCAAoC;AAEzE,SAASC,cAAc,EAAEC,YAAY,QAAQ,sBAAsB;AACnE,SAASC,UAAUC,aAAa,QAAqB,qBAAqB;AAC1E,SAASC,sBAAsB,QAAQ,gCAAgC;AAgBvE;;CAEC,GACD,MAAMC,oBAAoB,IAAI,KAAK;AAEnC,6EAA6E,GAC7E,IAAA,AAAMC,yBAAN,MAAMA,+BAA+BC;IACnC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA;QACN,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA;;;CAGC,GACD,SAASC,cAAcC,YAA8B;IACnD,IAAI,CAACA,aAAaC,MAAM,EAAE;QACxB,MAAM,IAAIN,uBAAuB;IACnC;IACA,OAAOK,aAAaC,MAAM;AAC5B;A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AKgG,OAAO,CAACL,YAAY;gBAAEM,WAAW;YAAK;YAExD,IAAI,CAAClD,UAAU,GAAG,IAAI7C,KAAK;gBACzBgG,OAAO,IAAI/F,SAAS;oBAAEgG,UAAUR;gBAAU;YAC5C;QACF;QACA,IAAI,CAAC/B,SAAS,GAAG,IAAIlD;QACrB,IAAI,CAACsD,SAAS,GAAG,IAAI3D;QACrB,IAAI,CAACiF,QAAQ,GAAGI,QAAQJ,QAAQ,IAAI;QACpC,IAAI,CAAC7B,WAAW,GAAGiC,QAAQjC,WAAW;QACtC,IAAI,CAACjD,MAAM,IAAGkF,kBAAAA,QAAQlF,MAAM,cAAdkF,6BAAAA,kBAAkBjF;IAClC;AAsSF"}
|
|
@@ -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 (
|
|
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
|
|
16
|
+
registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials>;
|
|
17
17
|
}
|
|
@@ -7,17 +7,15 @@
|
|
|
7
7
|
* Registers a new OAuth client with the authorization server (RFC 7591).
|
|
8
8
|
*
|
|
9
9
|
* @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
|
|
10
|
-
* @param options - Registration options (
|
|
10
|
+
* @param options - Registration options (redirect URI, client name, loopback trust).
|
|
11
11
|
* @returns Client credentials (client ID and secret).
|
|
12
12
|
* @throws Error if registration fails or the server returns an error.
|
|
13
|
-
*/ async registerClient(registrationEndpoint, options
|
|
13
|
+
*/ async registerClient(registrationEndpoint, options) {
|
|
14
14
|
var _options_allowLoopback;
|
|
15
15
|
const requestBody = {
|
|
16
16
|
client_name: options.clientName || '@mcp-z/client',
|
|
17
|
-
redirect_uris:
|
|
17
|
+
redirect_uris: [
|
|
18
18
|
options.redirectUri
|
|
19
|
-
] : [
|
|
20
|
-
'http://localhost:3000/callback'
|
|
21
19
|
],
|
|
22
20
|
grant_types: [
|
|
23
21
|
'authorization_code',
|
|
@@ -26,7 +24,10 @@
|
|
|
26
24
|
response_types: [
|
|
27
25
|
'code'
|
|
28
26
|
],
|
|
29
|
-
token_endpoint_auth_method: 'client_secret_basic'
|
|
27
|
+
token_endpoint_auth_method: 'client_secret_basic',
|
|
28
|
+
// The callback listener always binds an OS-assigned loopback port, so the
|
|
29
|
+
// redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).
|
|
30
|
+
application_type: 'native'
|
|
30
31
|
};
|
|
31
32
|
// registrationEndpoint is remote-controlled discovery data; allowLoopback
|
|
32
33
|
// must come from the caller's own trust, never from registrationEndpoint.
|
|
@@ -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 (
|
|
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":["discoveryFetch","DynamicClientRegistrar","registerClient","registrationEndpoint","options","requestBody","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","application_type","response","method","headers","Accept","Connection","body","JSON","stringify","allowLoopback","ok","errorText","text","Error","status","data","json","client_id","credentials","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC,GAED,SAASA,cAAc,QAAQ,6BAA6B;AAqB5D,4DAA4D,GAC5D,OAAO,MAAMC;IACX;;;;;;;GAOC,GACD,MAAMC,eAAeC,oBAA4B,EAAEC,OAA+B,EAA8B;YA0B3FA;QAzBnB,MAAMC,cAAsC;YAC1CC,aAAaF,QAAQG,UAAU,IAAI;YACnCC,eAAe;gBAACJ,QAAQK,WAAW;aAAC;YACpCC,aAAa;gBAAC;gBAAsB;aAAgB;YACpDC,gBAAgB;gBAAC;aAAO;YACxBC,4BAA4B;YAC5B,0EAA0E;YAC1E,4FAA4F;YAC5FC,kBAAkB;QACpB;QAEA,0EAA0E;QAC1E,0EAA0E;QAC1E,MAAMC,WAAW,MAAMd,eACrBG,sBACA;YACEY,QAAQ;YACRC,SAAS;gBACP,gBAAgB;gBAChBC,QAAQ;gBACRC,YAAY;YACd;YACAC,MAAMC,KAAKC,SAAS,CAAChB;QACvB,GACA,yBACA;YAAEiB,aAAa,GAAElB,yBAAAA,QAAQkB,aAAa,cAArBlB,oCAAAA,yBAAyB;QAAM;QAGlD,IAAI,CAACU,SAASS,EAAE,EAAE;YAChB,MAAMC,YAAY,MAAMV,SAASW,IAAI;YACrC,MAAM,IAAIC,MAAM,CAAC,yBAAyB,EAAEZ,SAASa,MAAM,CAAC,GAAG,EAAEH,WAAW;QAC9E;QAEA,MAAMI,OAAQ,MAAMd,SAASe,IAAI;QAEjC,IAAI,CAACD,KAAKE,SAAS,EAAE;YACnB,MAAM,IAAIJ,MAAM;QAClB;QAEA,MAAMK,cAAiC;YACrCC,UAAUJ,KAAKE,SAAS;YACxBG,cAAcL,KAAKM,aAAa,IAAI;QACtC;QAEA,IAAIN,KAAKO,mBAAmB,EAAE;YAC5BJ,YAAYK,QAAQ,GAAGR,KAAKO,mBAAmB;QACjD;QAEA,OAAOJ;IACT;AACF"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -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/esm/index.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @mcp-z/client - MCP Client Library
|
|
3
|
-
*/ //
|
|
3
|
+
*/ // SDK re-exports for protocol version negotiation: the connect-option type and the typed
|
|
4
|
+
// errors a negotiation can fail with, so callers can handle era mismatch without
|
|
5
|
+
// depending on the SDK themselves.
|
|
6
|
+
export { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
|
|
4
7
|
// Auth - OAuth utilities
|
|
5
8
|
export { probeAuthCapabilities } from './auth/capability-discovery.js';
|
|
6
9
|
export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
|
package/dist/esm/index.js.map
CHANGED
|
@@ -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":["probeAuthCapabilities","DiscoveryFetchError","isLoopbackUrl","InteractiveOAuthFlow","OAuthCallbackListener","decorateClient","validateServers","DcrAuthenticator","DynamicClientRegistrar","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","search","searchCapabilities","createServerRegistry","getLogLevel","logger","setLogLevel","resolveArgsPaths","resolvePath"],"mappings":"AAAA;;CAEC,
|
|
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":["SdkError","SdkErrorCode","probeAuthCapabilities","DiscoveryFetchError","isLoopbackUrl","InteractiveOAuthFlow","OAuthCallbackListener","decorateClient","validateServers","DcrAuthenticator","DynamicClientRegistrar","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","search","searchCapabilities","createServerRegistry","getLogLevel","logger","setLogLevel","resolveArgsPaths","resolvePath"],"mappings":"AAAA;;CAEC,GAGD,yFAAyF;AACzF,iFAAiF;AACjF,mCAAmC;AACnC,SAASA,QAAQ,EAAEC,YAAY,QAAQ,+BAA+B;AAGtE,yBAAyB;AACzB,SAASC,qBAAqB,QAAQ,iCAAiC;AACvE,SAASC,mBAAmB,EAAEC,aAAa,QAAQ,4BAA4B;AAE/E,SAASC,oBAAoB,QAAQ,mCAAmC;AACxE,SAASC,qBAAqB,QAAQ,oCAAoC;AAC1E,2CAA2C;AAC3C,SAASC,cAAc,QAA2I,sBAAsB;AACxL,oCAAoC;AACpC,SAAgCC,eAAe,QAAQ,8BAA8B;AAGrF,8CAA8C;AAC9C,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,sBAAsB,QAAQ,oCAAoC;AAE3E,SAKEC,mBAAmB,EACnBC,qBAAqB,EACrBC,qBAAqB,EACrBC,uBAAuB,EACvBC,iBAAiB,EACjBC,mBAAmB,QACd,yBAAyB;AAEhC,gCAAgC;AAChC,SAASC,oBAAoB,EAAEC,MAAM,EAAEC,kBAAkB,QAAQ,oBAAoB;AACrF,mCAAmC;AACnC,SAA6DC,oBAAoB,QAA+D,2BAA2B;AAE3K,2BAA2B;AAC3B,SAASC,WAAW,EAA8BC,MAAM,EAAEC,WAAW,QAAQ,oBAAoB;AACjG,SAASC,gBAAgB,EAAEC,WAAW,QAAQ,wBAAwB"}
|
|
@@ -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;
|
|
@@ -3,8 +3,8 @@ export function normalizeUrl(input) {
|
|
|
3
3
|
const url = new URL(input);
|
|
4
4
|
url.search = '';
|
|
5
5
|
url.hash = '';
|
|
6
|
-
|
|
7
|
-
return url.origin + url.pathname;
|
|
6
|
+
// Strip after joining: assigning an empty pathname puts the '/' straight back.
|
|
7
|
+
return (url.origin + url.pathname).replace(/\/+$/, '');
|
|
8
8
|
} catch {
|
|
9
9
|
return input.replace(/\/+$/, '');
|
|
10
10
|
}
|
|
@@ -12,3 +12,35 @@ export function normalizeUrl(input) {
|
|
|
12
12
|
export function joinWellKnown(baseUrl, suffix) {
|
|
13
13
|
return `${normalizeUrl(baseUrl)}${suffix}`;
|
|
14
14
|
}
|
|
15
|
+
/**
|
|
16
|
+
* Extract the "server base" - where a server's own endpoints live, NOT its identity.
|
|
17
|
+
*
|
|
18
|
+
* The `/mcp` segment names the protocol endpoint; everything before it is the
|
|
19
|
+
* deployment root that `/oauth/verify` and friends hang off. Stripping it is
|
|
20
|
+
* right for building those URLs and wrong for anything that identifies the
|
|
21
|
+
* server: an RFC 8707 `resource` indicator or a credential store key must use
|
|
22
|
+
* the full URL, because the stripped form names a different resource (or none).
|
|
23
|
+
*
|
|
24
|
+
* Original shape by removing a trailing `/mcp` path segment if present.
|
|
25
|
+
* Examples:
|
|
26
|
+
* - https://example.com/mcp -> https://example.com
|
|
27
|
+
* - https://example.com/sheets/mcp -> https://example.com/sheets
|
|
28
|
+
* - https://example.com/sheets/mcp/ -> https://example.com/sheets
|
|
29
|
+
* - https://example.com/sheets -> https://example.com/sheets
|
|
30
|
+
*/ export function extractBaseUrl(mcpUrl) {
|
|
31
|
+
const url = new URL(mcpUrl);
|
|
32
|
+
// Ignore query/hash for base URL purposes
|
|
33
|
+
url.search = '';
|
|
34
|
+
url.hash = '';
|
|
35
|
+
// Normalize path segments (removes empty segments from leading/trailing slashes)
|
|
36
|
+
const segments = url.pathname.split('/').filter(Boolean);
|
|
37
|
+
// If last segment is exactly "mcp", drop it
|
|
38
|
+
if (segments[segments.length - 1] === 'mcp') {
|
|
39
|
+
segments.pop();
|
|
40
|
+
}
|
|
41
|
+
// Rebuild pathname; empty means root
|
|
42
|
+
url.pathname = segments.length ? `/${segments.join('/')}` : '';
|
|
43
|
+
// Return without trailing slash (except root origin)
|
|
44
|
+
const out = url.origin + url.pathname;
|
|
45
|
+
return out === url.origin ? out : out.replace(/\/+$/, '');
|
|
46
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/lib/url-utils.ts"],"sourcesContent":["export function normalizeUrl(input: string): string {\n try {\n const url = new URL(input);\n url.search = '';\n url.hash = '';\n
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/lib/url-utils.ts"],"sourcesContent":["export function normalizeUrl(input: string): string {\n try {\n const url = new URL(input);\n url.search = '';\n url.hash = '';\n // Strip after joining: assigning an empty pathname puts the '/' straight back.\n return (url.origin + url.pathname).replace(/\\/+$/, '');\n } catch {\n return input.replace(/\\/+$/, '');\n }\n}\n\nexport function joinWellKnown(baseUrl: string, suffix: string): string {\n return `${normalizeUrl(baseUrl)}${suffix}`;\n}\n\n/**\n * Extract the \"server base\" - where a server's own endpoints live, NOT its identity.\n *\n * The `/mcp` segment names the protocol endpoint; everything before it is the\n * deployment root that `/oauth/verify` and friends hang off. Stripping it is\n * right for building those URLs and wrong for anything that identifies the\n * server: an RFC 8707 `resource` indicator or a credential store key must use\n * the full URL, because the stripped form names a different resource (or none).\n *\n * Original shape by removing a trailing `/mcp` path segment if present.\n * Examples:\n * - https://example.com/mcp -> https://example.com\n * - https://example.com/sheets/mcp -> https://example.com/sheets\n * - https://example.com/sheets/mcp/ -> https://example.com/sheets\n * - https://example.com/sheets -> https://example.com/sheets\n */\nexport function extractBaseUrl(mcpUrl: string): string {\n const url = new URL(mcpUrl);\n\n // Ignore query/hash for base URL purposes\n url.search = '';\n url.hash = '';\n\n // Normalize path segments (removes empty segments from leading/trailing slashes)\n const segments = url.pathname.split('/').filter(Boolean);\n\n // If last segment is exactly \"mcp\", drop it\n if (segments[segments.length - 1] === 'mcp') {\n segments.pop();\n }\n\n // Rebuild pathname; empty means root\n url.pathname = segments.length ? `/${segments.join('/')}` : '';\n\n // Return without trailing slash (except root origin)\n const out = url.origin + url.pathname;\n return out === url.origin ? out : out.replace(/\\/+$/, '');\n}\n"],"names":["normalizeUrl","input","url","URL","search","hash","origin","pathname","replace","joinWellKnown","baseUrl","suffix","extractBaseUrl","mcpUrl","segments","split","filter","Boolean","length","pop","join","out"],"mappings":"AAAA,OAAO,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,MAAMC,MAAM,IAAIC,IAAIF;QACpBC,IAAIE,MAAM,GAAG;QACbF,IAAIG,IAAI,GAAG;QACX,+EAA+E;QAC/E,OAAO,AAACH,CAAAA,IAAII,MAAM,GAAGJ,IAAIK,QAAQ,AAAD,EAAGC,OAAO,CAAC,QAAQ;IACrD,EAAE,OAAM;QACN,OAAOP,MAAMO,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEA,OAAO,SAASC,cAAcC,OAAe,EAAEC,MAAc;IAC3D,OAAO,GAAGX,aAAaU,WAAWC,QAAQ;AAC5C;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,eAAeC,MAAc;IAC3C,MAAMX,MAAM,IAAIC,IAAIU;IAEpB,0CAA0C;IAC1CX,IAAIE,MAAM,GAAG;IACbF,IAAIG,IAAI,GAAG;IAEX,iFAAiF;IACjF,MAAMS,WAAWZ,IAAIK,QAAQ,CAACQ,KAAK,CAAC,KAAKC,MAAM,CAACC;IAEhD,4CAA4C;IAC5C,IAAIH,QAAQ,CAACA,SAASI,MAAM,GAAG,EAAE,KAAK,OAAO;QAC3CJ,SAASK,GAAG;IACd;IAEA,qCAAqC;IACrCjB,IAAIK,QAAQ,GAAGO,SAASI,MAAM,GAAG,CAAC,CAAC,EAAEJ,SAASM,IAAI,CAAC,MAAM,GAAG;IAE5D,qDAAqD;IACrD,MAAMC,MAAMnB,IAAII,MAAM,GAAGJ,IAAIK,QAAQ;IACrC,OAAOc,QAAQnB,IAAII,MAAM,GAAGe,MAAMA,IAAIb,OAAO,CAAC,QAAQ;AACxD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Client } from '@modelcontextprotocol/
|
|
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']>>;
|