@lightdash-tools/mcp 0.16.1 → 0.17.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 (29) hide show
  1. package/README.md +13 -3
  2. package/dist/auth/oauth-broker/as-metadata.d.ts +6 -2
  3. package/dist/auth/oauth-broker/as-metadata.js +8 -4
  4. package/dist/auth/oauth-broker/invoke-origins.d.ts +16 -0
  5. package/dist/auth/oauth-broker/invoke-origins.js +112 -0
  6. package/dist/auth/oauth-broker/invoke-origins.test.d.ts +1 -0
  7. package/dist/auth/oauth-broker/invoke-origins.test.js +82 -0
  8. package/dist/auth/oauth-broker/routes.js +33 -9
  9. package/dist/auth/oauth-broker/routes.test.js +110 -3
  10. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +1 -1
  11. package/dist/auth/resource-server/lightdash-oauth-middleware.js +8 -5
  12. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +36 -2
  13. package/dist/auth/resource-server/oauth-protected-resource.d.ts +2 -2
  14. package/dist/auth/resource-server/oauth-protected-resource.js +8 -11
  15. package/dist/auth/resource-server/www-authenticate.test.js +3 -3
  16. package/dist/config/env.d.ts +5 -0
  17. package/dist/config/env.js +6 -1
  18. package/dist/config/load-mcp-config.d.ts +2 -0
  19. package/dist/config/load-mcp-config.js +18 -0
  20. package/dist/config/load-mcp-config.test.js +29 -0
  21. package/dist/config/test-mcp-http-config.js +1 -1
  22. package/dist/http.integration.helpers.d.ts +50 -0
  23. package/dist/http.integration.helpers.js +190 -0
  24. package/dist/http.integration.test.js +57 -198
  25. package/dist/http.invoke-origin.integration.test.d.ts +1 -0
  26. package/dist/http.invoke-origin.integration.test.js +108 -0
  27. package/dist/transports/streamable-http.js +3 -1
  28. package/dist/transports/streamable-http.test.js +8 -3
  29. package/package.json +3 -3
@@ -18,16 +18,14 @@ exports.OAUTH_PROTECTED_RESOURCE_ROOT = '/.well-known/oauth-protected-resource';
18
18
  * Builds MCP OAuth protected-resource metadata for a profile MCP path.
19
19
  * Callers must pass an explicit profile path (root PRM uses `config.mcpPath`).
20
20
  */
21
- function buildOAuthProtectedResourceMetadata(config, mcpPath) {
22
- const publicUrl = (0, public_url_js_1.requirePublicUrl)(config, OAUTH_PROTECTED_RESOURCE_CONTEXT);
21
+ function buildOAuthProtectedResourceMetadata(config, mcpPath, resourceOrigin) {
23
22
  const path = (0, normalize_url_js_1.normalizeMcpPath)(mcpPath);
24
- // Broker mode: authorization_servers is the MCP host (PUBLIC_URL). Clients discover
25
- // AS metadata at {PUBLIC_URL}/.well-known/oauth-authorization-server and never need
26
- // the Lightdash client secret. The broker issues its own access token bound to this
27
- // exact resource; the downstream Lightdash credential remains a separate OAuth leg.
23
+ // Broker mode: authorization_servers is the MCP host clients should use for AS
24
+ // discovery. On PUBLIC_URL that is the public origin. On an extra invoke origin
25
+ // it is that origin so private-network clients do not fetch public well-known.
28
26
  return {
29
- resource: `${publicUrl}${path}`,
30
- authorization_servers: [publicUrl],
27
+ resource: `${resourceOrigin}${path}`,
28
+ authorization_servers: [resourceOrigin],
31
29
  bearer_methods_supported: ['header'],
32
30
  scopes_supported: config.scopesSupported,
33
31
  };
@@ -36,10 +34,9 @@ function getProtectedResourceMetadataUrl(config) {
36
34
  return `${(0, public_url_js_1.requirePublicUrl)(config, OAUTH_PROTECTED_RESOURCE_CONTEXT)}${exports.OAUTH_PROTECTED_RESOURCE_ROOT}`;
37
35
  }
38
36
  /** Path-specific PRM URL for a profile MCP endpoint. */
39
- function getProtectedResourceMetadataPathUrl(config, mcpPath) {
40
- const publicUrl = (0, public_url_js_1.requirePublicUrl)(config, OAUTH_PROTECTED_RESOURCE_CONTEXT);
37
+ function getProtectedResourceMetadataPathUrl(config, mcpPath, resourceOrigin) {
41
38
  const resourcePath = (0, normalize_url_js_1.normalizeMcpPath)(mcpPath).replace(/^\//, '');
42
- return `${publicUrl}${exports.OAUTH_PROTECTED_RESOURCE_ROOT}/${resourcePath}`;
39
+ return `${resourceOrigin}${exports.OAUTH_PROTECTED_RESOURCE_ROOT}/${resourcePath}`;
43
40
  }
44
41
  /**
45
42
  * Resolves the profile MCP path for a PRM well-known request.
@@ -18,7 +18,7 @@ const baseConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
18
18
  });
19
19
  (0, vitest_1.describe)('buildOAuthProtectedResourceMetadata', () => {
20
20
  (0, vitest_1.it)('includes resource and MCP host as authorization_servers', () => {
21
- const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_3.SEMANTIC_LAYER_PROFILE_PATH);
21
+ const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_3.SEMANTIC_LAYER_PROFILE_PATH, 'https://mcp.example.com');
22
22
  (0, vitest_1.expect)(metadata).toEqual({
23
23
  resource: `https://mcp.example.com${index_js_3.SEMANTIC_LAYER_PROFILE_PATH}`,
24
24
  authorization_servers: ['https://mcp.example.com'],
@@ -28,12 +28,12 @@ const baseConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
28
28
  (0, vitest_1.expect)((0, oauth_protected_resource_js_1.getAuthorizationServerMetadataUrl)(metadata.authorization_servers[0])).toBe('https://mcp.example.com/.well-known/oauth-authorization-server');
29
29
  });
30
30
  (0, vitest_1.it)('builds profile-specific resource metadata for organization-audit', () => {
31
- const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_2.ORGANIZATION_AUDIT_PROFILE_PATH);
31
+ const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_2.ORGANIZATION_AUDIT_PROFILE_PATH, 'https://mcp.example.com');
32
32
  (0, vitest_1.expect)(metadata.resource).toBe(`https://mcp.example.com${index_js_2.ORGANIZATION_AUDIT_PROFILE_PATH}`);
33
33
  (0, vitest_1.expect)(metadata.authorization_servers).toEqual(['https://mcp.example.com']);
34
34
  });
35
35
  (0, vitest_1.it)('builds profile-specific resource metadata for content-reader', () => {
36
- const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_1.CONTENT_READER_PROFILE_PATH);
36
+ const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_1.CONTENT_READER_PROFILE_PATH, 'https://mcp.example.com');
37
37
  (0, vitest_1.expect)(metadata.resource).toBe(`https://mcp.example.com${index_js_1.CONTENT_READER_PROFILE_PATH}`);
38
38
  (0, vitest_1.expect)(metadata.authorization_servers).toEqual(['https://mcp.example.com']);
39
39
  });
@@ -7,6 +7,11 @@ export declare const ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = "LIGHTDASH_TOOLS_MCP_HT
7
7
  /** Platform listen port (Cloud Run / many PaaS). Used only when dedicated MCP port env is unset. */
8
8
  export declare const ENV_PLATFORM_PORT = "PORT";
9
9
  export declare const ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = "LIGHTDASH_TOOLS_MCP_PUBLIC_URL";
10
+ /**
11
+ * Optional comma-separated extra invoke origins (private load balancer, internal DNS).
12
+ * On a matching Host, PRM and token/DCR advertise that origin; issuer/authorize stay on PUBLIC_URL.
13
+ */
14
+ export declare const ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS = "LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS";
10
15
  /** Rejected at config load — MCP path is profile-owned (see profiles/). */
11
16
  export declare const ENV_LIGHTDASH_TOOLS_MCP_PATH = "LIGHTDASH_TOOLS_MCP_PATH";
12
17
  /** Optional HTTP mount allowlist (comma-separated ProfileIds). Unset/empty → all. Stdio ignores. */
@@ -4,12 +4,17 @@
4
4
  * Legacy `MCP_*` aliases are resolved in load-mcp-config.ts.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH = exports.OAUTH_REGISTER_PATH = exports.OAUTH_TOKEN_PATH = exports.OAUTH_AUTHORIZE_PATH = exports.OAUTH_CALLBACK_PATH = exports.ENV_MCP_MAX_BODY_BYTES = exports.ENV_MCP_ALLOWED_ORIGINS = exports.ENV_MCP_API_KEY = exports.ENV_MCP_AUTH_ENABLED = exports.ENV_MCP_PUBLIC_URL = exports.ENV_MCP_SERVER_PORT = exports.ENV_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOW_INSECURE_PUBLIC_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_EXPERIMENTAL_IDENTITY_OAUTH = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_ANY_ORIGIN = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_UNAUTHENTICATED = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_GRANT_ALL_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_SKIP_TOKEN_VALIDATION = exports.ENV_LIGHTDASH_TOOLS_MCP_INSECURE_DEV = exports.ENV_LIGHTDASH_TOOLS_MCP_REDIS_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_STORE = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_ID = exports.ENV_LIGHTDASH_TOOLS_MCP_TOKEN_VALIDATION_CACHE_TTL_MS = exports.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN = exports.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUIRED_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_MAX_BODY_BYTES = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOWED_ORIGINS = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUEST_STATE_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_SHARED_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_AUTH_MODE = exports.ENV_LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT = exports.ENV_LIGHTDASH_TOOLS_MCP_PROFILES = exports.ENV_LIGHTDASH_TOOLS_MCP_PATH = exports.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = exports.ENV_PLATFORM_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST = void 0;
7
+ exports.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH = exports.OAUTH_REGISTER_PATH = exports.OAUTH_TOKEN_PATH = exports.OAUTH_AUTHORIZE_PATH = exports.OAUTH_CALLBACK_PATH = exports.ENV_MCP_MAX_BODY_BYTES = exports.ENV_MCP_ALLOWED_ORIGINS = exports.ENV_MCP_API_KEY = exports.ENV_MCP_AUTH_ENABLED = exports.ENV_MCP_PUBLIC_URL = exports.ENV_MCP_SERVER_PORT = exports.ENV_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOW_INSECURE_PUBLIC_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_EXPERIMENTAL_IDENTITY_OAUTH = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_ANY_ORIGIN = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_UNAUTHENTICATED = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_GRANT_ALL_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_SKIP_TOKEN_VALIDATION = exports.ENV_LIGHTDASH_TOOLS_MCP_INSECURE_DEV = exports.ENV_LIGHTDASH_TOOLS_MCP_REDIS_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_STORE = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_ID = exports.ENV_LIGHTDASH_TOOLS_MCP_TOKEN_VALIDATION_CACHE_TTL_MS = exports.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN = exports.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUIRED_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_MAX_BODY_BYTES = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOWED_ORIGINS = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUEST_STATE_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_SHARED_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_AUTH_MODE = exports.ENV_LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT = exports.ENV_LIGHTDASH_TOOLS_MCP_PROFILES = exports.ENV_LIGHTDASH_TOOLS_MCP_PATH = exports.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS = exports.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = exports.ENV_PLATFORM_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST = void 0;
8
8
  exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST = 'LIGHTDASH_TOOLS_MCP_HTTP_HOST';
9
9
  exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = 'LIGHTDASH_TOOLS_MCP_HTTP_PORT';
10
10
  /** Platform listen port (Cloud Run / many PaaS). Used only when dedicated MCP port env is unset. */
11
11
  exports.ENV_PLATFORM_PORT = 'PORT';
12
12
  exports.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = 'LIGHTDASH_TOOLS_MCP_PUBLIC_URL';
13
+ /**
14
+ * Optional comma-separated extra invoke origins (private load balancer, internal DNS).
15
+ * On a matching Host, PRM and token/DCR advertise that origin; issuer/authorize stay on PUBLIC_URL.
16
+ */
17
+ exports.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS = 'LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS';
13
18
  /** Rejected at config load — MCP path is profile-owned (see profiles/). */
14
19
  exports.ENV_LIGHTDASH_TOOLS_MCP_PATH = 'LIGHTDASH_TOOLS_MCP_PATH';
15
20
  /** Optional HTTP mount allowlist (comma-separated ProfileIds). Unset/empty → all. Stdio ignores. */
@@ -8,6 +8,8 @@ export interface McpHttpConfig {
8
8
  host: string;
9
9
  port: number;
10
10
  publicUrl?: string;
11
+ /** Extra invoke origins. Parsed only in OAuth mode. */
12
+ invokeOrigins: URL[];
11
13
  mcpPath: string;
12
14
  /** HTTP mount allowlist. Unrestricted when LIGHTDASH_TOOLS_MCP_PROFILES is unset. */
13
15
  enabledProfiles: EnabledProfilesPolicy;
@@ -6,6 +6,7 @@ exports.requiresLightdashApiKey = requiresLightdashApiKey;
6
6
  exports.getOAuthCallbackUrl = getOAuthCallbackUrl;
7
7
  const client_1 = require("@lightdash-tools/client");
8
8
  const auth_mode_js_1 = require("../auth/auth-mode.js");
9
+ const invoke_origins_js_1 = require("../auth/oauth-broker/invoke-origins.js");
9
10
  const index_js_1 = require("../profiles/index.js");
10
11
  const enabled_profiles_js_1 = require("./enabled-profiles.js");
11
12
  const env_js_1 = require("./env.js");
@@ -154,6 +155,19 @@ function emitLightdashOAuthSecurityWarnings(config) {
154
155
  'but downstream Lightdash user/token validation is skipped. Use only for local development.');
155
156
  }
156
157
  emitNgrokFreeInterstitialWarning(config.publicUrl);
158
+ emitInvokeOriginWarnings(config);
159
+ }
160
+ function emitInvokeOriginWarnings(config) {
161
+ const cleartext = config.invokeOrigins.filter((origin) => origin.protocol === 'http:' && !(0, normalize_url_js_1.isLocalHttpOrigin)(origin.origin));
162
+ if (cleartext.length === 0) {
163
+ return;
164
+ }
165
+ const listed = cleartext.map((origin) => origin.origin).join(', ');
166
+ console.warn(`Warning: ${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS} includes non-loopback http origins (${listed}). ` +
167
+ 'On those Hosts, token/DCR and PRM advertise the invoke origin while issuer/authorize stay on ' +
168
+ `${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL}. This is an intentional RFC 8414 issuer split; ` +
169
+ '@modelcontextprotocol/client v2 will reject HTTP invoke origins. Point that SDK at public HTTPS. ' +
170
+ 'Do not serve extra origins as the public VIP Host.');
157
171
  }
158
172
  /** Free ngrok serves ERR_NGROK_6024 for browser-UA GETs; Cursor's post-callback rediscovery uses Mozilla UA. */
159
173
  function emitNgrokFreeInterstitialWarning(publicUrl) {
@@ -249,6 +263,9 @@ function loadMcpHttpConfig(env = process.env, options) {
249
263
  const mcpPath = (0, enabled_profiles_js_1.resolveRootMcpPath)(enabledProfiles);
250
264
  const publicUrl = publicUrlRaw ? (0, normalize_url_js_1.normalizePublicUrl)(publicUrlRaw, (0, index_js_1.listProfilePaths)()) : undefined;
251
265
  assertPublicUrlSecurity(authMode, publicUrl);
266
+ const invokeOrigins = authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH
267
+ ? (0, invoke_origins_js_1.parseInvokeOrigins)((0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS, env), publicUrl)
268
+ : [];
252
269
  const validateToken = parseBooleanEnv(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN, (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN, env), authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH);
253
270
  assertValidateTokenPolicy(authMode, validateToken, env);
254
271
  const requiredScopes = readScopeList(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_REQUIRED_SCOPES, []);
@@ -258,6 +275,7 @@ function loadMcpHttpConfig(env = process.env, options) {
258
275
  { name: env_js_1.ENV_MCP_HTTP_PORT, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT },
259
276
  { name: env_js_1.ENV_MCP_SERVER_PORT, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT },
260
277
  ], 3100, env_js_1.ENV_PLATFORM_PORT), publicUrl,
278
+ invokeOrigins,
261
279
  mcpPath,
262
280
  enabledProfiles,
263
281
  promptContextPolicy,
@@ -198,6 +198,35 @@ function setOAuthCreds() {
198
198
  const config = (0, load_mcp_config_js_1.loadMcpHttpConfig)();
199
199
  (0, vitest_1.expect)(config.publicUrl).toBe('http://127.0.0.1:3100');
200
200
  });
201
+ (0, vitest_1.it)('parses extra invoke origins in OAuth mode including non-loopback http', () => {
202
+ setOAuthCreds();
203
+ process.env[env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS] =
204
+ 'http://mcp.ilb.internal, https://mcp.example.com';
205
+ const config = (0, load_mcp_config_js_1.loadMcpHttpConfig)();
206
+ (0, vitest_1.expect)(config.invokeOrigins.map((origin) => origin.origin)).toEqual([
207
+ 'http://mcp.ilb.internal',
208
+ ]);
209
+ });
210
+ (0, vitest_1.it)('rejects invalid invoke origins in OAuth mode', () => {
211
+ setOAuthCreds();
212
+ process.env[env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS] = 'not-a-url';
213
+ (0, vitest_1.expect)(() => (0, load_mcp_config_js_1.loadMcpHttpConfig)()).toThrow(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS);
214
+ });
215
+ (0, vitest_1.it)('ignores invoke origins outside OAuth mode', () => {
216
+ process.env.LIGHTDASH_URL = 'https://app.lightdash.cloud';
217
+ process.env.NODE_ENV = 'development';
218
+ process.env[env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS] = 'not-a-url';
219
+ const config = (0, load_mcp_config_js_1.loadMcpHttpConfig)();
220
+ (0, vitest_1.expect)(config.authMode).toBe('none');
221
+ (0, vitest_1.expect)(config.invokeOrigins).toEqual([]);
222
+ });
223
+ (0, vitest_1.it)('warns for non-loopback http invoke origins', () => {
224
+ setOAuthCreds();
225
+ process.env[env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS] = 'http://mcp.ilb.internal';
226
+ const config = (0, load_mcp_config_js_1.loadMcpHttpConfig)();
227
+ (0, load_mcp_config_js_1.emitMcpHttpSecurityWarnings)(config);
228
+ (0, vitest_1.expect)(vitest_1.vi.mocked(console.warn).mock.calls.flat().join('\n')).toMatch(/non-loopback http origins/);
229
+ });
201
230
  (0, vitest_1.it)('rejects VALIDATE_TOKEN=false in production', () => {
202
231
  setOAuthCreds();
203
232
  process.env[env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN] = 'false';
@@ -6,5 +6,5 @@ const enabled_profiles_js_1 = require("./enabled-profiles.js");
6
6
  function makeTestMcpHttpConfig(overrides) {
7
7
  var _a;
8
8
  const enabledProfiles = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.enabledProfiles) !== null && _a !== void 0 ? _a : enabled_profiles_js_1.UNRESTRICTED_ENABLED_PROFILES;
9
- return Object.assign({ lightdashUrl: 'https://app.lightdash.cloud', host: '127.0.0.1', port: 3100, publicUrl: 'https://mcp.example.com', mcpPath: (0, enabled_profiles_js_1.resolveRootMcpPath)(enabledProfiles), enabledProfiles, promptContextPolicy: 'compact', authMode: 'lightdash-oauth', allowedOrigins: [], maxBodyBytes: 1024, requiredScopes: ['mcp:read'], scopesSupported: ['mcp:read', 'mcp:write'], validateToken: true, tokenValidationCacheTtlMs: 30000 }, overrides);
9
+ return Object.assign({ lightdashUrl: 'https://app.lightdash.cloud', host: '127.0.0.1', port: 3100, publicUrl: 'https://mcp.example.com', invokeOrigins: [], mcpPath: (0, enabled_profiles_js_1.resolveRootMcpPath)(enabledProfiles), enabledProfiles, promptContextPolicy: 'compact', authMode: 'lightdash-oauth', allowedOrigins: [], maxBodyBytes: 1024, requiredScopes: ['mcp:read'], scopesSupported: ['mcp:read', 'mcp:write'], validateToken: true, tokenValidationCacheTtlMs: 30000 }, overrides);
10
10
  }
@@ -0,0 +1,50 @@
1
+ import { type IncomingHttpHeaders, type Server } from 'node:http';
2
+ import type { McpHttpConfig } from './config/load-mcp-config.js';
3
+ export declare const TOKEN_A: string;
4
+ export declare const TOKEN_B: string;
5
+ export declare const TOKEN_READ_ONLY: string;
6
+ export declare const OPAQUE_TOKEN_A = "opaque-token-user-a";
7
+ export declare const INITIALIZE_BODY: {
8
+ jsonrpc: string;
9
+ method: string;
10
+ params: {
11
+ protocolVersion: string;
12
+ capabilities: {};
13
+ clientInfo: {
14
+ name: string;
15
+ version: string;
16
+ };
17
+ };
18
+ id: number;
19
+ };
20
+ export interface MockLightdashServer {
21
+ baseUrl: string;
22
+ authorizationHeaders: string[];
23
+ close: () => Promise<void>;
24
+ }
25
+ export interface McpHttpServer {
26
+ baseUrl: string;
27
+ close: () => Promise<void>;
28
+ }
29
+ export declare function listen(server: Server, port: number, host: string): Promise<void>;
30
+ export declare function startMockLightdashServer(): Promise<MockLightdashServer>;
31
+ export declare function baseOAuthConfig(lightdashUrl: string, overrides?: Partial<McpHttpConfig>): McpHttpConfig;
32
+ export declare function brokerAccessToken(mcpBaseUrl: string, lightdashAccessToken: string, options?: {
33
+ path?: string;
34
+ scope?: string;
35
+ }): string;
36
+ export declare function nodeRequest(options: {
37
+ baseUrl: string;
38
+ path: string;
39
+ method?: string;
40
+ headers?: Record<string, string>;
41
+ body?: string;
42
+ }): Promise<{
43
+ status: number;
44
+ headers: IncomingHttpHeaders;
45
+ json: unknown;
46
+ }>;
47
+ export declare function postMcp(baseUrl: string, body: unknown, options?: {
48
+ token?: string;
49
+ path?: string;
50
+ }): Promise<Response>;
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INITIALIZE_BODY = exports.OPAQUE_TOKEN_A = exports.TOKEN_READ_ONLY = exports.TOKEN_B = exports.TOKEN_A = void 0;
4
+ exports.listen = listen;
5
+ exports.startMockLightdashServer = startMockLightdashServer;
6
+ exports.baseOAuthConfig = baseOAuthConfig;
7
+ exports.brokerAccessToken = brokerAccessToken;
8
+ exports.nodeRequest = nodeRequest;
9
+ exports.postMcp = postMcp;
10
+ const node_http_1 = require("node:http");
11
+ const client_1 = require("@lightdash-tools/client");
12
+ const mcp_access_token_js_1 = require("./auth/oauth-broker/mcp-access-token.js");
13
+ const test_mcp_http_config_js_1 = require("./config/test-mcp-http-config.js");
14
+ // These constants model downstream Lightdash credentials only. MCP clients never send
15
+ // them directly after ADR-0026; tests wrap them in broker-issued MCP access tokens.
16
+ exports.TOKEN_A = scopedAccessToken('mcp:read mcp:write', 'token-a');
17
+ exports.TOKEN_B = scopedAccessToken('mcp:read mcp:write', 'token-b');
18
+ exports.TOKEN_READ_ONLY = scopedAccessToken('mcp:read', 'token-read-only');
19
+ exports.OPAQUE_TOKEN_A = 'opaque-token-user-a';
20
+ const USER_A = { userUuid: 'user-a-uuid', email: 'a@example.com', organizationUuid: 'org-a-uuid' };
21
+ const USER_B = { userUuid: 'user-b-uuid', email: 'b@example.com', organizationUuid: 'org-b-uuid' };
22
+ function scopedAccessToken(scope, subject) {
23
+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
24
+ const payload = Buffer.from(JSON.stringify({ scope, sub: subject })).toString('base64url');
25
+ return `${header}.${payload}.signature`;
26
+ }
27
+ exports.INITIALIZE_BODY = {
28
+ jsonrpc: '2.0',
29
+ method: 'initialize',
30
+ params: {
31
+ protocolVersion: '2024-11-05',
32
+ capabilities: {},
33
+ clientInfo: { name: 'integration-test', version: '1.0.0' },
34
+ },
35
+ id: 1,
36
+ };
37
+ function listen(server, port, host) {
38
+ return new Promise((resolve, reject) => {
39
+ server.once('error', reject);
40
+ server.listen(port, host, () => {
41
+ server.removeListener('error', reject);
42
+ resolve();
43
+ });
44
+ });
45
+ }
46
+ function writeJson(res, status, body) {
47
+ res.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify(body));
48
+ }
49
+ function writeUnauthorized(res) {
50
+ writeJson(res, 401, {
51
+ status: 'error',
52
+ error: { statusCode: 401, name: 'Unauthorized', message: 'Invalid token' },
53
+ });
54
+ }
55
+ function bearerFromAuth(auth) {
56
+ return auth.startsWith('Bearer ') ? auth.slice('Bearer '.length).trim() : '';
57
+ }
58
+ function userForAuth(auth, users) {
59
+ return users.get(bearerFromAuth(auth));
60
+ }
61
+ async function startMockLightdashServer() {
62
+ const authorizationHeaders = [];
63
+ const users = new Map([
64
+ [exports.TOKEN_A, USER_A],
65
+ [exports.TOKEN_B, USER_B],
66
+ [exports.TOKEN_READ_ONLY, USER_A],
67
+ [exports.OPAQUE_TOKEN_A, USER_A],
68
+ ]);
69
+ let issuerBaseUrl = '';
70
+ const server = (0, node_http_1.createServer)((req, res) => {
71
+ var _a;
72
+ const authHeader = req.headers.authorization;
73
+ const auth = typeof authHeader === 'string' ? authHeader : ((_a = authHeader === null || authHeader === void 0 ? void 0 : authHeader[0]) !== null && _a !== void 0 ? _a : '');
74
+ authorizationHeaders.push(auth);
75
+ if (req.method === 'GET' && req.url === '/.well-known/oauth-authorization-server') {
76
+ writeJson(res, 200, {
77
+ issuer: issuerBaseUrl,
78
+ authorization_endpoint: `${issuerBaseUrl}/api/v1/oauth/authorize`,
79
+ token_endpoint: `${issuerBaseUrl}/api/v1/oauth/token`,
80
+ revocation_endpoint: `${issuerBaseUrl}/api/v1/oauth/revoke`,
81
+ registration_endpoint: `${issuerBaseUrl}/api/v1/oauth/register`,
82
+ userinfo_endpoint: `${issuerBaseUrl}/api/v1/oauth/userinfo`,
83
+ });
84
+ return;
85
+ }
86
+ if (req.method === 'GET' && req.url === '/api/v1/user') {
87
+ const user = userForAuth(auth, users);
88
+ if (user === undefined) {
89
+ writeUnauthorized(res);
90
+ return;
91
+ }
92
+ writeJson(res, 200, { status: 'ok', results: user });
93
+ return;
94
+ }
95
+ if (req.method === 'GET' && req.url === '/api/v1/org/projects') {
96
+ if (userForAuth(auth, users) === undefined) {
97
+ writeUnauthorized(res);
98
+ return;
99
+ }
100
+ writeJson(res, 200, {
101
+ status: 'ok',
102
+ results: [{ projectUuid: 'project-a-uuid', name: 'Project A', type: 'DEFAULT' }],
103
+ });
104
+ return;
105
+ }
106
+ res.writeHead(404).end();
107
+ });
108
+ await listen(server, 0, '127.0.0.1');
109
+ const address = server.address();
110
+ issuerBaseUrl = `http://127.0.0.1:${address.port}`;
111
+ return {
112
+ baseUrl: issuerBaseUrl,
113
+ authorizationHeaders,
114
+ close: () => new Promise((resolve, reject) => {
115
+ server.close((err) => {
116
+ if (err)
117
+ reject(err);
118
+ else
119
+ resolve();
120
+ });
121
+ }),
122
+ };
123
+ }
124
+ function baseOAuthConfig(lightdashUrl, overrides) {
125
+ return (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)(Object.assign({ lightdashUrl, port: 0, publicUrl: 'http://127.0.0.1:0', oauthClientId: 'test-client-id', oauthClientSecret: new client_1.SecretString('test-client-secret'), maxBodyBytes: 1024 * 1024, requiredScopes: [], scopesSupported: [] }, overrides));
126
+ }
127
+ function brokerAccessToken(mcpBaseUrl, lightdashAccessToken, options = {}) {
128
+ var _a;
129
+ const path = (_a = options.path) !== null && _a !== void 0 ? _a : '/semantic-layer/v1/mcp';
130
+ return (0, mcp_access_token_js_1.mintMcpAccessToken)(baseOAuthConfig('https://lightdash.invalid'), {
131
+ lightdashAccessToken,
132
+ clientId: 'integration-test-client',
133
+ resource: `${mcpBaseUrl}${path}`,
134
+ scope: options.scope,
135
+ expiresAtMs: Date.now() + 60000,
136
+ }).accessToken;
137
+ }
138
+ function nodeRequest(options) {
139
+ const url = new URL(options.path, options.baseUrl);
140
+ return new Promise((resolve, reject) => {
141
+ var _a;
142
+ const req = (0, node_http_1.request)({
143
+ hostname: url.hostname,
144
+ port: url.port,
145
+ path: `${url.pathname}${url.search}`,
146
+ method: (_a = options.method) !== null && _a !== void 0 ? _a : 'GET',
147
+ headers: options.headers,
148
+ }, (res) => {
149
+ const chunks = [];
150
+ res.on('data', (chunk) => chunks.push(chunk));
151
+ res.on('end', () => {
152
+ var _a;
153
+ const text = Buffer.concat(chunks).toString('utf8');
154
+ let json = text;
155
+ try {
156
+ json = JSON.parse(text);
157
+ }
158
+ catch (_b) {
159
+ // keep text
160
+ }
161
+ resolve({
162
+ status: (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0,
163
+ headers: res.headers,
164
+ json,
165
+ });
166
+ });
167
+ });
168
+ req.on('error', reject);
169
+ if (options.body !== undefined) {
170
+ req.write(options.body);
171
+ }
172
+ req.end();
173
+ });
174
+ }
175
+ async function postMcp(baseUrl, body, options) {
176
+ var _a;
177
+ const headers = {
178
+ 'Content-Type': 'application/json',
179
+ Accept: 'application/json, text/event-stream',
180
+ };
181
+ if (options === null || options === void 0 ? void 0 : options.token) {
182
+ headers.Authorization = `Bearer ${options.token}`;
183
+ }
184
+ const path = (_a = options === null || options === void 0 ? void 0 : options.path) !== null && _a !== void 0 ? _a : '/semantic-layer/v1/mcp';
185
+ return fetch(`${baseUrl}${path}`, {
186
+ method: 'POST',
187
+ headers,
188
+ body: JSON.stringify(body),
189
+ });
190
+ }