@databrainhq/mcp-server 0.3.0-rc.14 → 0.3.0-rc.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hosted/main.ts","../src/hosted/config.ts","../src/hosted/http.ts","../src/hosted/authorization.ts","../src/hosted/server.ts","../src/tools/infrastructure/create-workspace.ts","../src/hosted/provider.ts"],"sourcesContent":["import { isAbsolute } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { FilePatStore } from './auth.js';\nimport { loadHostedConfig } from './config.js';\nimport { createHostedHttpServer } from './http.js';\nimport { createProviderAdapter } from './provider.js';\nimport type { HostedAdapter } from './types.js';\n\nexport async function startHosted(): Promise<void> {\n const config = loadHostedConfig();\n let adapter: HostedAdapter;\n if (config.testOnly) {\n const file = process.env.DATABRAIN_HOSTED_TEST_FIXTURES;\n if (!file || !isAbsolute(file))\n throw new Error(\n 'Hosted test mode requires an absolute fixture store path.'\n );\n const { createTestOnlyAdapter } = await import('./test-only.js');\n adapter = createTestOnlyAdapter(file);\n } else {\n const file = process.env.DATABRAIN_HOSTED_ADAPTER_MODULE;\n if (!file) {\n adapter = createProviderAdapter(config);\n process.stderr.write(\n '[databrain] OAuth configured: data tools run as the signed-in user through the issuer; PAT membership requires a trusted adapter.\\n'\n );\n } else {\n if (!isAbsolute(file))\n throw new Error(\n 'DATABRAIN_HOSTED_ADAPTER_MODULE must be an absolute path.'\n );\n try {\n adapter = (await import(pathToFileURL(file).href)).adapter;\n } catch {\n throw new Error('Could not load the trusted hosted adapter.');\n }\n }\n if (\n !adapter ||\n ['verifyOAuth', 'resolvePatGrant', 'executeRequest'].some(\n (key) => typeof adapter[key as keyof HostedAdapter] !== 'function'\n )\n )\n throw new Error('Invalid trusted hosted adapter.');\n }\n const patPath = process.env.DATABRAIN_HOSTED_PAT_STORE;\n if (patPath && !isAbsolute(patPath))\n throw new Error('Hosted PAT store must be an absolute path.');\n const server = createHostedHttpServer(\n config,\n adapter,\n patPath ? new FilePatStore(patPath) : undefined\n );\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(config.port, config.bind, resolve);\n });\n process.stderr.write(\n `[databrain] hosted HTTP ready on ${config.bind}:${config.port}/mcp${config.testOnly ? ' — TEST ONLY: synthetic identity and data; no OAuth consent' : ''}\\n`\n );\n const shutdown = () => {\n server.close(() => process.exit(0));\n setTimeout(() => {\n server.closeAllConnections();\n process.exit(0);\n }, 5000).unref();\n };\n process.once('SIGINT', shutdown);\n process.once('SIGTERM', shutdown);\n}\n","import type { HostedConfig } from './types.js';\n\nexport function loadHostedConfig(\n env: NodeJS.ProcessEnv = process.env\n): HostedConfig {\n const testOnly = env.DATABRAIN_HOSTED_TEST_ONLY === '1';\n if (testOnly && env.NODE_ENV === 'production')\n throw new Error('Hosted test mode is forbidden in production.');\n if (env.DATABRAIN_HOSTED_TEST_ONLY && !testOnly)\n throw new Error('Invalid DATABRAIN_HOSTED_TEST_ONLY.');\n const validUrl = (value: string | undefined, field: string) => {\n try {\n if (!value) throw new Error();\n const url = new URL(value);\n if (\n url.username ||\n url.password ||\n url.search ||\n url.hash ||\n url.protocol !== 'https:'\n )\n throw new Error();\n return url;\n } catch {\n throw new Error(\n `Configure ${field} as an HTTPS URL without credentials, query or fragment.`\n );\n }\n };\n // Self-hosted installs set no new variable: with neither URL given, both come from the\n // HOSTED_APP_URL origin the image already has (app, API and /mcp on one origin). HTTPS only.\n let publicValue = env.DATABRAIN_HOSTED_PUBLIC_URL;\n let issuerValue = env.DATABRAIN_HOSTED_ISSUER;\n if (!publicValue && !issuerValue && env.HOSTED_APP_URL) {\n const origin = validUrl(env.HOSTED_APP_URL, 'HOSTED_APP_URL').origin;\n publicValue = `${origin}/mcp`;\n issuerValue = origin;\n }\n const publicUrl = validUrl(publicValue, 'DATABRAIN_HOSTED_PUBLIC_URL');\n validUrl(issuerValue, 'DATABRAIN_HOSTED_ISSUER');\n if (publicUrl.pathname !== '/mcp')\n throw new Error('DATABRAIN_HOSTED_PUBLIC_URL must end in /mcp.');\n const port = Number(env.DATABRAIN_HOSTED_PORT || '3144');\n // Loopback by default so a laptop run is not silently on the network. A\n // container has to be told, because binding loopback inside a task means the\n // load balancer health check can never reach it and the service never\n // stabilises. Set DATABRAIN_HOSTED_BIND=0.0.0.0 in ECS.\n const bind = env.DATABRAIN_HOSTED_BIND || '127.0.0.1';\n if (!Number.isInteger(port) || port < 1024 || port > 65535)\n throw new Error('Invalid DATABRAIN_HOSTED_PORT.');\n // Optional private address of the same API (for example ECS service discovery), so\n // the token check and data calls stay inside the network. The issuer is still the\n // identity the principal must name; this only changes where the requests go.\n let apiUrl: string | undefined;\n if (env.DATABRAIN_HOSTED_API_URL) {\n let url: URL | undefined;\n try {\n url = new URL(env.DATABRAIN_HOSTED_API_URL);\n } catch {\n url = undefined;\n }\n if (\n !url ||\n !['http:', 'https:'].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash ||\n url.pathname !== '/'\n ) {\n throw new Error(\n 'Configure DATABRAIN_HOSTED_API_URL as an origin without credentials, path, query or fragment.'\n );\n }\n apiUrl = url.origin;\n }\n return {\n publicUrl: publicValue!,\n issuer: issuerValue!,\n ...(apiUrl ? { apiUrl } : {}),\n port,\n bind,\n testOnly,\n };\n}\n","import {\n createServer,\n type IncomingMessage,\n type ServerResponse,\n} from 'node:http';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { createBearerVerifier } from './auth.js';\nimport {\n assertToolArguments,\n authorizeTool,\n requiredScopes,\n WorkspaceSelectionError,\n} from './authorization.js';\nimport {\n createHostedToolServer,\n scopeError,\n workspaceError,\n} from './server.js';\nimport type { HostedAdapter, HostedConfig, PatStore } from './types.js';\nimport { HOSTED_SCOPES, HostedAuthError } from './types.js';\n\nconst HEALTH_BODY = JSON.stringify({ status: 'ok' });\n\n/** Exactly `/health`, with or without a query string; `/health/x` is not health. */\nfunction healthPath(url: string | undefined): boolean {\n const path = (url || '/').split('?')[0];\n return path === '/health';\n}\n\nfunction reply(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-store',\n });\n res.end(JSON.stringify(body));\n}\n\nasync function readBody(req: IncomingMessage): Promise<unknown> {\n let size = 0;\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n size += chunk.length;\n if (size > 1_048_576) throw new Error('body_too_large');\n chunks.push(Buffer.from(chunk));\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf8'));\n}\n\nexport function createHostedHttpServer(\n config: HostedConfig,\n adapter: HostedAdapter,\n pats?: PatStore\n) {\n const publicUrl = new URL(config.publicUrl);\n const metadataPath = `/.well-known/oauth-protected-resource${publicUrl.pathname === '/' ? '' : publicUrl.pathname}`;\n const metadataUrl = `${publicUrl.origin}${metadataPath}`;\n const verify = createBearerVerifier(adapter, config.publicUrl, pats);\n let active = 0;\n\n const server = createServer(async (req, res) => {\n // Liveness for the load balancer. It arrives with the target IP:port as Host,\n // so it runs before the Host/Origin checks and sets no CORS headers. It is\n // unauthenticated, reads no body and never echoes configuration.\n if (healthPath(req.url)) {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n res.writeHead(405, { Allow: 'GET, HEAD', 'Cache-Control': 'no-store' });\n res.end();\n return;\n }\n res.writeHead(200, {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-store',\n 'Content-Length': Buffer.byteLength(HEALTH_BODY),\n });\n res.end(req.method === 'HEAD' ? undefined : HEALTH_BODY);\n return;\n }\n res.setHeader('X-Content-Type-Options', 'nosniff');\n if (config.testOnly) res.setHeader('X-Databrain-Test-Only', 'true');\n try {\n // Tailscale Serve may preserve the public Host or use the loopback destination.\n // Never use Host/Forwarded headers to construct discovery URLs or trust an identity.\n const localPort = (server.address() as { port: number } | null)?.port;\n if (\n ![\n publicUrl.host,\n `127.0.0.1:${localPort}`,\n `localhost:${localPort}`,\n ].includes(req.headers.host || '')\n ) {\n reply(res, 403, { error: 'invalid_host' });\n return;\n }\n if (req.headers.origin && req.headers.origin !== publicUrl.origin) {\n reply(res, 403, { error: 'invalid_origin' });\n return;\n }\n if (req.headers.origin) {\n res.setHeader('Access-Control-Allow-Origin', publicUrl.origin);\n res.setHeader('Vary', 'Origin');\n res.setHeader(\n 'Access-Control-Expose-Headers',\n 'WWW-Authenticate, MCP-Protocol-Version'\n );\n }\n const url = new URL(req.url || '/', publicUrl.origin);\n if (\n req.method === 'GET' &&\n [metadataPath, '/.well-known/oauth-protected-resource'].includes(\n url.pathname\n )\n ) {\n reply(res, 200, {\n resource: config.publicUrl,\n authorization_servers: [config.issuer],\n scopes_supported: HOSTED_SCOPES,\n bearer_methods_supported: ['header'],\n resource_name: config.testOnly\n ? 'Databrain (TEST ONLY; fixture identity)'\n : 'Databrain',\n });\n return;\n }\n if (url.pathname !== publicUrl.pathname) {\n reply(res, 404, { error: 'not_found' });\n return;\n }\n if (url.search) {\n reply(res, 400, { error: 'query_parameters_not_supported' });\n return;\n }\n if (req.method === 'OPTIONS') {\n res.setHeader(\n 'Access-Control-Allow-Methods',\n 'POST, GET, DELETE, OPTIONS'\n );\n res.setHeader(\n 'Access-Control-Allow-Headers',\n 'Authorization, Content-Type, MCP-Protocol-Version, MCP-Session-Id'\n );\n res.writeHead(204);\n res.end();\n return;\n }\n // Duplicate Authorization fields and cookies never select a principal.\n const authFields = req.rawHeaders.filter(\n (_, i) =>\n i % 2 === 0 && req.rawHeaders[i].toLowerCase() === 'authorization'\n );\n const match = /^Bearer ([^\\s]+)$/i.exec(req.headers.authorization || '');\n if (authFields.length !== 1 || !match)\n throw new HostedAuthError(401, 'invalid_token');\n const principal = await verify(match[1]);\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST, OPTIONS');\n reply(res, 405, { error: 'method_not_allowed' });\n return;\n }\n if (\n !req.headers['content-type']\n ?.toLowerCase()\n .startsWith('application/json')\n ) {\n reply(res, 415, { error: 'unsupported_media_type' });\n return;\n }\n if (active >= 32) {\n reply(res, 503, { error: 'server_busy' });\n return;\n }\n active++;\n let body: any;\n try {\n body = await readBody(req);\n } catch {\n active--;\n reply(res, 400, { error: 'invalid_request' });\n return;\n }\n try {\n // The installed SDK accepts batches; this endpoint does not. A batch must\n // never skip the per-call HTTP authorization/challenge path below.\n if (Array.isArray(body)) {\n reply(res, 400, { error: 'batch_not_supported' });\n return;\n }\n // Only an OAuth bearer delegates; a PAT never leaves this process.\n const delegation = match[1].startsWith('dbp_')\n ? undefined\n : adapter.delegate?.(match[1], principal);\n if (\n body?.method === 'tools/call' &&\n typeof body.params?.name === 'string'\n ) {\n try {\n authorizeTool(body.params.name, principal);\n assertToolArguments(\n body.params.name,\n body.params.arguments,\n principal,\n delegation !== undefined\n );\n } catch (error) {\n // A workspace the grant does not hold, or two that disagree: answer the call as a\n // tool error with the granted names, which an AI can act on. No tool runs.\n if (error instanceof WorkspaceSelectionError) {\n reply(res, 200, {\n jsonrpc: '2.0',\n id: body.id ?? null,\n result: workspaceError(error),\n });\n return;\n }\n // A scope the grant lacks: consent already trimmed the scopes to the role, so a\n // step-up challenge (403 insufficient_scope) cannot get more. It made Claude Code\n // drop the whole connection to \"needs authentication\". Answer the call instead.\n if (\n error instanceof HostedAuthError &&\n error.code === 'insufficient_scope'\n ) {\n const missing = requiredScopes(body.params.name).filter(\n (scope) => !principal.scopes.includes(scope)\n );\n reply(res, 200, {\n jsonrpc: '2.0',\n id: body.id ?? null,\n result: scopeError(missing),\n });\n return;\n }\n throw error;\n }\n }\n const mcp = createHostedToolServer(principal, adapter, delegation);\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n let closed = false;\n const close = () => {\n if (!closed) {\n closed = true;\n void mcp.close();\n }\n };\n res.once('close', close);\n try {\n await mcp.connect(transport);\n await transport.handleRequest(req, res, body);\n } finally {\n if (res.writableEnded) close();\n }\n } finally {\n active--;\n }\n } catch (error) {\n if (res.headersSent) {\n res.end();\n return;\n }\n const status = error instanceof HostedAuthError ? error.status : 503;\n if (status === 401)\n res.setHeader(\n 'WWW-Authenticate',\n `Bearer error=\"invalid_token\", resource_metadata=\"${metadataUrl}\"`\n );\n reply(res, status, {\n error:\n error instanceof HostedAuthError\n ? error.code\n : 'temporarily_unavailable',\n });\n }\n });\n server.requestTimeout = 30_000;\n server.headersTimeout = 10_000;\n server.keepAliveTimeout = 5_000;\n return server;\n}\n","import type {\n GrantedWorkspace,\n HostedPrincipal,\n HostedScope,\n} from './types.js';\nimport { HostedAuthError } from './types.js';\n\n/** Explicit exhaustive policy: a newly registered tool is denied until it gets a policy. */\nexport const TOOL_SCOPES: Readonly<Record<string, readonly HostedScope[]>> = {\n whoami: [],\n list_datasources: ['mcp:datamarts:read'],\n discover_datasource_schema: ['mcp:datamarts:read'],\n list_datamarts: ['mcp:datamarts:read'],\n list_workspaces: ['mcp:datamarts:read'],\n sync_datasource: ['mcp:datamarts:write'],\n create_datamart: ['mcp:datamarts:write'],\n list_data_apps: ['mcp:dashboards:read'],\n list_tenants: ['mcp:dashboards:read'],\n create_data_app: ['mcp:embeds:write'],\n list_api_tokens: ['mcp:embeds:write'],\n create_api_token: ['mcp:embeds:write'],\n rotate_api_token: ['mcp:embeds:write'],\n create_embed: ['mcp:embeds:write'],\n list_embeds: ['mcp:dashboards:read'],\n get_embed_details: ['mcp:dashboards:read'],\n update_embed: ['mcp:embeds:write'],\n customize_embed_theme: ['mcp:embeds:write'],\n get_demo_link: ['mcp:embeds:write'],\n generate_guest_token: ['mcp:embeds:write'],\n generate_embed_code: ['mcp:dashboards:read'],\n create_workspace: ['mcp:datamarts:write'],\n list_dashboards: ['mcp:dashboards:read'],\n create_dashboard: ['mcp:dashboards:write'],\n get_dashboard: ['mcp:dashboards:read'],\n dashboard_snapshot: ['mcp:dashboards:read'],\n generate_dashboard_tiles: [\n 'mcp:dashboards:write',\n 'mcp:query',\n 'mcp:embeds:write',\n ],\n ask_question: ['mcp:query'],\n get_semantic_layer: ['mcp:datamarts:read'],\n update_semantic_layer: ['mcp:datamarts:write'],\n start_semantic_layer_generation: ['mcp:datamarts:write'],\n get_semantic_layer_generation_status: ['mcp:datamarts:read'],\n search_semantic_model: ['mcp:datamarts:read'],\n get_semantic_entity: ['mcp:datamarts:read'],\n propose_semantic_change: ['mcp:datamarts:read'],\n apply_semantic_change: ['mcp:datamarts:write'],\n eval_semantic_model: ['mcp:datamarts:read', 'mcp:query'],\n list_widgets: ['mcp:dashboards:read'],\n validate_metric_spec: [\n 'mcp:dashboards:read',\n 'mcp:query',\n 'mcp:embeds:write',\n ],\n create_or_update_metric_from_query: [\n 'mcp:dashboards:write',\n 'mcp:query',\n 'mcp:embeds:write',\n ],\n create_workspace_metric: ['mcp:dashboards:write', 'mcp:query'],\n add_widget: ['mcp:dashboards:write', 'mcp:embeds:write'],\n update_widget: ['mcp:dashboards:write', 'mcp:embeds:write'],\n remove_widget: ['mcp:dashboards:write', 'mcp:embeds:write'],\n generate_widget: ['mcp:dashboards:write', 'mcp:query', 'mcp:embeds:write'],\n list_scheduled_reports: ['mcp:dashboards:read'],\n custom_chart_edit: ['mcp:custom-charts:write'],\n custom_chart_preview: ['mcp:custom-charts:read'],\n load_custom_chart_bundle: ['mcp:custom-charts:read'],\n load_custom_chart_runtime: ['mcp:custom-charts:read'],\n custom_chart_scaffold: [],\n custom_chart_validate: ['mcp:custom-charts:read'],\n custom_chart_upload: ['mcp:custom-charts:write'],\n list_custom_charts: ['mcp:custom-charts:read'],\n publish_custom_chart: ['mcp:custom-charts:write'],\n // Chart tile controls (the chart-apps composition). The same routes as ask_question and a\n // dashboard save; listed so a hosted composition is not refused for want of a policy.\n preview_chart: ['mcp:query'],\n save_chart_as_dashboard: ['mcp:dashboards:write', 'mcp:query'],\n // Hosted platform reads do not mint embed credentials. Guest rendering retains its backend boundary.\n render_metric_tile: ['mcp:dashboards:read', 'mcp:query'],\n render_chart: ['mcp:dashboards:read', 'mcp:query'],\n refresh_widget: ['mcp:dashboards:read', 'mcp:query'],\n drill_down: ['mcp:dashboards:read', 'mcp:query'],\n change_date_range: ['mcp:dashboards:read', 'mcp:query'],\n};\n\nexport function requiredScopes(name: string): readonly HostedScope[] {\n if (!Object.hasOwn(TOOL_SCOPES, name))\n throw new HostedAuthError(403, 'tool_not_authorized');\n return TOOL_SCOPES[name];\n}\n\nexport function authorizeTool(name: string, principal: HostedPrincipal): void {\n if (\n principal.expiresAt !== undefined &&\n principal.expiresAt <= Date.now() / 1000\n )\n throw new HostedAuthError(401, 'invalid_token');\n if (requiredScopes(name).some((scope) => !principal.scopes.includes(scope)))\n throw new HostedAuthError(403, 'insufficient_scope');\n}\n\n/**\n * A tool's own top-level argument whose name is also a forbidden identity key, with the\n * only values it may take. `list_dashboards.scope` picks the listing, not an OAuth scope.\n */\nconst TOOL_ARGUMENT_VALUES: Readonly<\n Record<string, Readonly<Record<string, readonly string[]>>>\n> = {\n list_dashboards: { scope: ['auto', 'data_app', 'global'] },\n};\n\n/**\n * Top-level tool arguments that carry query rows, not selectors. A row may have a\n * `userId` or `workspaceId` column; the issuer treats the rows as data.\n */\nconst TOOL_OPAQUE_ARGUMENTS: Readonly<Record<string, readonly string[]>> = {\n preview_chart: ['rows'],\n custom_chart_preview: ['rows', 'manifest'],\n custom_chart_edit: ['draft'],\n};\n\n/**\n * Tool-call arguments: the allowed own arguments by exact value, then the shared binding rules\n * against the call's workspace. Returns that workspace (see selectWorkspace).\n */\nexport function assertToolArguments(\n name: string,\n value: unknown,\n principal: HostedPrincipal,\n delegated = false\n): GrantedWorkspace | undefined {\n const allowed = Object.hasOwn(TOOL_ARGUMENT_VALUES, name)\n ? TOOL_ARGUMENT_VALUES[name]\n : {};\n const opaque = Object.hasOwn(TOOL_OPAQUE_ARGUMENTS, name)\n ? TOOL_OPAQUE_ARGUMENTS[name]\n : undefined;\n const target = selectWorkspace(value, principal);\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n assertBoundArguments(value, principal, { target, delegated });\n return target;\n }\n const rest: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n if (!Object.hasOwn(allowed, key)) {\n rest[key] = child;\n continue;\n }\n if (typeof child !== 'string' || !allowed[key].includes(child))\n throw new HostedAuthError(403, 'identity_argument_forbidden');\n }\n assertBoundArguments(rest, principal, { target, delegated, opaque });\n return target;\n}\n\n/**\n * Tools that act on no single workspace: identity, the granted list, company-level\n * custom charts, local code generation, and workspace creation. Every other tool\n * reaches a workspace-scoped route, so it can name its workspace.\n */\nexport const WORKSPACE_FREE_TOOLS: ReadonlySet<string> = new Set([\n 'whoami',\n 'list_workspaces',\n 'create_workspace',\n 'generate_embed_code',\n 'custom_chart_preview',\n 'load_custom_chart_bundle',\n 'load_custom_chart_runtime',\n 'custom_chart_scaffold',\n 'custom_chart_validate',\n 'custom_chart_upload',\n 'list_custom_charts',\n 'publish_custom_chart',\n]);\n\n/**\n * Tools that walk every granted workspace when the call names none (each request then names\n * its own workspace), and only the named one when it does. They never ask for a workspace.\n */\nexport const WORKSPACE_SPANNING_TOOLS: ReadonlySet<string> = new Set([\n 'list_dashboards',\n]);\n\n/** The workspace selector a hosted tool gains when its own schema has none. Sent only as a header. */\nexport const WORKSPACE_INPUT = 'workspace';\n\n/** Raised before any request when a call names its workspace wrongly; the tool shows the message. */\nexport class WorkspaceSelectionError extends HostedAuthError {\n constructor(\n status: 400 | 404,\n code: string,\n public readonly reason: string\n ) {\n super(status, code);\n }\n}\n\nexport function grantedWorkspaces(\n principal: HostedPrincipal\n): GrantedWorkspace[] {\n if (principal.grantedWorkspaces) return principal.grantedWorkspaces;\n return principal.workspaceId\n ? [{ id: principal.workspaceId, name: principal.workspaceName }]\n : [];\n}\n\n/** \"A, B, C\", at most 20 names, then \"and N more\". Only the user's own granted names. */\nexport function grantedNames(principal: HostedPrincipal): string {\n const names = grantedWorkspaces(principal).map(\n (item) => item.name ?? item.id\n );\n return names.length > 20\n ? `${names.slice(0, 20).join(', ')} and ${names.length - 20} more`\n : names.join(', ');\n}\n\n/** A selector is a granted workspace's id, else its exact name. Nothing else, and never two. */\nfunction findGranted(\n principal: HostedPrincipal,\n key: string,\n value: unknown\n): GrantedWorkspace {\n const granted = grantedWorkspaces(principal);\n const matches =\n typeof value !== 'string'\n ? []\n : key === 'workspaceId'\n ? granted.filter((item) => item.id === value)\n : key === 'workspaceName'\n ? granted.filter((item) => item.name === value)\n : granted.some((item) => item.id === value)\n ? granted.filter((item) => item.id === value)\n : granted.filter((item) => item.name === value);\n if (matches.length !== 1) {\n throw new WorkspaceSelectionError(\n 404,\n 'NOT_FOUND_IN_GRANT',\n `Workspace ${JSON.stringify(String(value).slice(0, 100))} is not one this sign-in granted. Granted: ${grantedNames(principal)}.`\n );\n }\n return matches[0];\n}\n\n/**\n * The one workspace a tool call acts in: the top-level `workspace`, `workspaceName` or\n * `workspaceId` inputs (all must name the same granted workspace), else the only granted\n * workspace, else none (the issuer then asks for one, or the route is company-level).\n */\nexport function selectWorkspace(\n args: unknown,\n principal: HostedPrincipal,\n keys: readonly string[] = [WORKSPACE_INPUT, 'workspaceName', 'workspaceId']\n): GrantedWorkspace | undefined {\n let target: GrantedWorkspace | undefined;\n if (args && typeof args === 'object' && !Array.isArray(args)) {\n for (const key of keys) {\n const value = (args as Record<string, unknown>)[key];\n if (value === undefined) continue;\n const found = findGranted(principal, key, value);\n if (target && target.id !== found.id) {\n throw new WorkspaceSelectionError(\n 400,\n 'WORKSPACE_CONFLICT',\n 'These inputs name different workspaces. Name one workspace for this call.'\n );\n }\n target = found;\n }\n }\n const granted = grantedWorkspaces(principal);\n return target ?? (granted.length === 1 ? granted[0] : undefined);\n}\n\n/** True when a workspace selector appears anywhere in the arguments, raw passthroughs included. */\nexport function namesWorkspace(value: unknown): boolean {\n if (!value || typeof value !== 'object') return false;\n return Object.entries(value).some(\n ([key, child]) =>\n ([WORKSPACE_INPUT, 'workspaceName', 'workspaceId'].includes(key) &&\n child !== undefined) ||\n namesWorkspace(child)\n );\n}\n\n/** What one tool call is bound to, beyond the principal. */\nexport interface ArgumentBinding {\n /** The call's workspace (selectWorkspace). Every workspace selector must name it. */\n target?: GrantedWorkspace;\n /**\n * The call runs as a delegated OAuth request: the issuer checks any tenant id against its\n * route policy on that very call, as it does for the app user, and refuses a route that\n * claims none. Without it (a PAT, a non-delegating adapter) a tenant needs `tenantIds`.\n */\n delegated?: boolean;\n /** Top-level keys holding data rather than selectors (query rows), never scanned. */\n opaque?: readonly string[];\n}\n\nfunction tenantAllowed(\n child: unknown,\n principal: HostedPrincipal,\n delegated: boolean\n): boolean {\n if (typeof child !== 'string') return false;\n if (principal.tenantIds) return principal.tenantIds.includes(child);\n return delegated && principal.credentialType === 'oauth';\n}\n\n/**\n * Reject conflicting selectors even in raw body passthroughs before a handler can use them.\n * A workspace selector must name the call's target when it has one, else a granted workspace.\n */\nexport function assertBoundArguments(\n value: unknown,\n principal: HostedPrincipal,\n binding: ArgumentBinding = {}\n): void {\n if (!value || typeof value !== 'object') return;\n const { opaque, ...nested } = binding;\n for (const [key, child] of Object.entries(value)) {\n if (opaque?.includes(key) && !Array.isArray(value)) continue;\n if (key === 'workspaceId' || key === 'workspaceName') {\n const target = binding.target;\n if (\n target\n ? child !== (key === 'workspaceId' ? target.id : target.name)\n : !findGranted(principal, key, child)\n ) {\n throw new HostedAuthError(403, 'principal_mismatch');\n }\n }\n if (\n ['companyId', 'userId'].includes(key) &&\n child !== principal[key as 'companyId' | 'userId']\n ) {\n throw new HostedAuthError(403, 'principal_mismatch');\n }\n if (\n [\n 'scope',\n 'scopes',\n 'authUser',\n 'actorKind',\n 'credentialType',\n 'oauthClientId',\n 'operatorEmail',\n 'session_variables',\n 'isAllClient',\n 'isAdmin',\n 'serviceToken',\n 'apiToken',\n 'authorization',\n ].includes(key)\n ) {\n throw new HostedAuthError(403, 'identity_argument_forbidden');\n }\n if (\n ['clientId', 'tenantId'].includes(key) &&\n !tenantAllowed(child, principal, binding.delegated === true)\n ) {\n throw new HostedAuthError(403, 'tenant_not_authorized');\n }\n assertBoundArguments(child, principal, nested);\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { instrument } from '@posthog/mcp';\nimport { PostHog } from 'posthog-node';\nimport { z } from 'zod';\nimport { enableChartApps } from '../apps/feature.js';\nimport { PREVIEW_PATH } from '../apps/preview.js';\nimport { registerChartApps } from '../apps/registry.js';\nimport { DatabrainClient } from '../client/databrain-client.js';\nimport type { RequestOptions } from '../client/types.js';\nimport { registerAllPrompts } from '../prompts/registry.js';\nimport { registerAllResources } from '../resources/registry.js';\nimport { registerCreateWorkspace } from '../tools/infrastructure/create-workspace.js';\nimport { registerAllTools } from '../tools/registry.js';\nimport { DatabrainApiError, toolError, toolSuccess } from '../utils/errors.js';\nimport { toolContext } from '../utils/tool-context.js';\nimport { MCP_SERVER_VERSION } from '../version.js';\nimport {\n assertBoundArguments,\n assertToolArguments,\n authorizeTool,\n grantedNames,\n grantedWorkspaces,\n namesWorkspace,\n selectWorkspace,\n WORKSPACE_FREE_TOOLS,\n WORKSPACE_INPUT,\n WORKSPACE_SPANNING_TOOLS,\n WorkspaceSelectionError,\n} from './authorization.js';\nimport type {\n GrantedWorkspace,\n HostedAdapter,\n HostedDelegation,\n HostedPrincipal,\n} from './types.js';\nimport { HostedAuthError } from './types.js';\n\n// Stdio's instrumentation changes the wire schema (required `context`). Use that\n// same implementation, with capture disabled until hosted telemetry has an owner.\n// No bearer, request headers, tool arguments or results are sent to analytics.\nconst schemaInstrumentation = new PostHog('hosted-contract-only', {\n disabled: true,\n});\n\n/** The granted workspace the running tool call acts in. Set by the tool wrapper only. */\nconst callWorkspace = new AsyncLocalStorage<{ target?: GrantedWorkspace }>();\n\nconst WORKSPACE_HINT =\n 'Call whoami to see the workspaces this sign-in granted, then name one.';\n\n/** A workspace selection problem, as the tool result the AI reads: reason, code, next step. */\nexport function workspaceError(error: WorkspaceSelectionError) {\n return toolError(\n `Error: ${error.reason} (${error.code})\\n\\nHint: ${WORKSPACE_HINT}`\n );\n}\n\n/** A tool this sign-in's scopes do not cover, as a tool result: the connection stays up. */\nexport function scopeError(missing: readonly string[]) {\n return toolError(\n `Error: This connection cannot do this. It needs ${missing.join(', ')}, which your role did not allow ` +\n 'when you connected. (INSUFFICIENT_SCOPE)\\n\\nHint: Ask a Databrain admin for a role that allows it, then connect ' +\n 'again. If your role allows it in a workspace you did not choose, connect again and choose that workspace.'\n );\n}\n\n/** The workspace list answer (bare or under `data`) cut to one workspace. */\nfunction onlyWorkspace(raw: unknown, target: GrantedWorkspace): unknown {\n const keep = (items: unknown) =>\n Array.isArray(items)\n ? items.filter((item) => {\n const record =\n item && typeof item === 'object'\n ? (item as Record<string, unknown>)\n : {};\n return (\n record.id === target.id ||\n record._id === target.id ||\n (record.id === undefined &&\n record._id === undefined &&\n target.name !== undefined &&\n record.name === target.name)\n );\n })\n : items;\n if (Array.isArray(raw)) return keep(raw);\n if (raw && typeof raw === 'object' && 'data' in raw)\n return { ...raw, data: keep((raw as { data: unknown }).data) };\n return raw;\n}\n\n/** A request-local client: shared APIs/tools run unchanged, through a delegated executor. */\nclass HostedClient extends DatabrainClient {\n constructor(\n private readonly adapter: HostedAdapter,\n private readonly principal: HostedPrincipal,\n private readonly delegation?: HostedDelegation\n ) {\n super({\n apiUrl: 'https://api.usedatabrain.com',\n demoDomain: 'https://demo.usedatabrain.com',\n });\n }\n // A generated API credential must never replace the authorizing hosted principal.\n override setRuntimeApiToken(_token: string): void {}\n override isHosted(): boolean {\n return true;\n }\n\n override async request<T>(options: RequestOptions): Promise<T> {\n try {\n const name = toolContext.getStore()?.tool;\n if (!name) throw new HostedAuthError(403, 'tool_not_authorized');\n authorizeTool(name, this.principal);\n const named = callWorkspace.getStore()?.target;\n // With no workspace for the call (a tool that walks every granted workspace), a request\n // that names one top-level workspace acts in it, and says so in the header too.\n const target =\n named ??\n selectWorkspace(options.body, this.principal, [\n 'workspaceName',\n 'workspaceId',\n ]) ??\n selectWorkspace(options.query, this.principal, [\n 'workspaceName',\n 'workspaceId',\n ]);\n const delegated = this.delegation !== undefined;\n // Chart preview rows are query output (a row may have a userId column); the issuer\n // treats them as data too. Every other body field is still checked.\n const opaque =\n options.method === 'POST' && options.path === PREVIEW_PATH\n ? ['rows']\n : options.method === 'POST' &&\n /^\\/api\\/v2\\/custom-charts\\/[a-z][a-z0-9_-]*\\/bryn\\/turn$/.test(\n options.path\n )\n ? ['draft']\n : undefined;\n assertBoundArguments(options.body, this.principal, {\n target,\n delegated,\n opaque,\n });\n assertBoundArguments(options.query, this.principal, {\n target,\n delegated,\n });\n let raw = await this.adapter.executeRequest(\n structuredClone(options),\n structuredClone(this.principal),\n this.delegation,\n target && structuredClone(target)\n );\n // A call that named its workspace reads the workspace list as that workspace only, so a\n // tool that walks the list (list_dashboards) stays in it.\n if (\n named &&\n options.method === 'GET' &&\n options.path === '/api/v2/workspace'\n )\n raw = onlyWorkspace(raw, named);\n if (\n !options.skipDataUnwrap &&\n raw &&\n typeof raw === 'object' &&\n !Array.isArray(raw) &&\n 'data' in raw &&\n raw.data !== null &&\n raw.data !== undefined\n )\n return raw.data as T;\n return raw as T;\n } catch (error) {\n if (error instanceof WorkspaceSelectionError) {\n throw new DatabrainApiError(\n error.status,\n error.code,\n `${error.reason} (${error.code})`,\n undefined,\n WORKSPACE_HINT\n );\n }\n // The adapter may encounter secret-bearing remote bodies. Do not pass them to tools/logs.\n const status = error instanceof HostedAuthError ? error.status : 503;\n const detail =\n error instanceof HostedAuthError ? error.detail : undefined;\n // A 403 reaches the tool only with a reason about this user's own grant (the adapter\n // keeps no other 403 body): the role in that workspace, or workspace creation.\n if (status === 403 && detail?.code) {\n throw new DatabrainApiError(\n 0,\n detail.code,\n `${detail.message ?? 'Your role does not allow this here.'} (${detail.code})`,\n undefined,\n 'Ask a Databrain admin for access, or pick a workspace where your role allows it.'\n );\n }\n if (status === 401 || status === 403) {\n // Status 0 carries no API-key hint: a hosted user has no key to rotate, only a sign-in.\n throw new DatabrainApiError(\n 0,\n 'HOSTED_REQUEST_DENIED',\n 'The signed-in Databrain user cannot do this: the sign-in expired or was revoked, or the granted scopes, role or workspace do not allow it. Sign in again or ask an admin.'\n );\n }\n if (detail && (detail.code || detail.message)) {\n // The code rides with the message: a short message (\"The workspace does not allow\n // this.\") only makes sense next to its reason (DATA_APP_REQUIRED).\n const message =\n detail.message ??\n (status === 404\n ? 'Not found in the workspace this sign-in approved.'\n : 'The backend refused this request.');\n throw new DatabrainApiError(\n detail.status,\n detail.code ?? 'HOSTED_REQUEST_FAILED',\n detail.code && !message.includes(detail.code)\n ? `${message} (${detail.code})`\n : message,\n { error: { code: detail.code, message: detail.message } }\n );\n }\n throw new DatabrainApiError(\n status,\n 'HOSTED_REQUEST_DENIED',\n status === 404\n ? 'Not found in the workspace this sign-in approved.'\n : 'The authorized backend could not complete this request. Check workspace access and hosted integration.'\n );\n }\n }\n}\n\n/** The hosted description line for a tool that works in one workspace. */\nfunction workspaceLine(name: string, input: string): string {\n return WORKSPACE_SPANNING_TOOLS.has(name)\n ? ` With more than one granted workspace, name one in \\`${input}\\` to list only that one; leave it out to list them all.`\n : ` Needed when you granted more than one workspace: name it in \\`${input}\\`.`;\n}\n\nfunction whoami(principal: HostedPrincipal) {\n const granted = grantedWorkspaces(principal);\n return toolSuccess(\n JSON.stringify(\n {\n status: 'authenticated',\n activeBearer: principal.credentialType,\n actorKind: principal.actorKind,\n userId: principal.userId,\n companyId: principal.companyId,\n workspaceGrant:\n principal.workspaces?.mode === 'all'\n ? 'All workspaces I can access (new ones are included)'\n : 'Only the workspaces chosen at sign-in',\n grantedWorkspaces: granted.map((item) => ({\n id: item.id,\n name: item.name,\n })),\n ...(granted.length === 1\n ? { workspaceId: granted[0].id, workspaceName: granted[0].name }\n : {}),\n note:\n granted.length === 1\n ? 'Every call works in this workspace.'\n : `Name the workspace on each call that works in one (the \\`${WORKSPACE_INPUT}\\` or \\`workspaceName\\` input): ${grantedNames(principal)}.`,\n oauthClientId: principal.clientId,\n scopes: principal.scopes,\n },\n null,\n 2\n )\n );\n}\n\nexport function createHostedToolServer(\n principal: HostedPrincipal,\n adapter: HostedAdapter,\n delegation?: HostedDelegation\n): McpServer {\n const bound = structuredClone(principal);\n const delegated = delegation !== undefined;\n const server = new McpServer(\n { name: 'databrain', version: MCP_SERVER_VERSION },\n {\n instructions:\n \"Hosted Databrain: each request is authenticated as the signed-in user, with that user's own role in each workspace. \" +\n 'Use whoami to see the verified identity, scopes and the workspaces this sign-in granted. ' +\n 'When more than one workspace is granted, name the workspace on each call (the workspace or workspaceName input). ' +\n 'Never ask for a service token or put credentials in tool arguments. ' +\n 'Workspace and tenant access come from the bearer principal. Existing dry-run and production-confirmation rules still apply. ' +\n 'For existing saved charts, call list_widgets with dashboardId or dashboardName and no clientId; no embed, data app or datamart is needed. Use render_metric_tile to draw a metricRef directly. Use ask_question for new data questions. Chart controls and save_chart_as_dashboard use the same workspace and role; ' +\n 'saving requires the existing production confirmation. Hosts without MCP Apps can read the text answer.',\n }\n );\n\n // The existing shared registry already wraps server.tool for intent telemetry. Layer\n // hosted policy underneath it; keep every handler and annotation. A tool that works in one\n // workspace says so, and gains a `workspace` input when its own schema names none.\n const register = server.tool.bind(server) as (...args: any[]) => unknown;\n server.tool = ((...args: any[]) => {\n const name = args[0] as string;\n const index = args.length - 1;\n const handler = args[index] as (\n ...values: any[]\n ) => CallToolResult | Promise<CallToolResult>;\n const shape =\n typeof args[1] === 'string' &&\n args[2] &&\n typeof args[2] === 'object' &&\n !('readOnlyHint' in args[2])\n ? (args[2] as Record<string, unknown>)\n : undefined;\n const ownSelector =\n shape &&\n (['workspaceName', 'workspaceId'] as const).find((key) =>\n Object.hasOwn(shape, key)\n );\n const addsInput =\n shape !== undefined &&\n !ownSelector &&\n !WORKSPACE_FREE_TOOLS.has(name) &&\n !Object.hasOwn(shape, WORKSPACE_INPUT);\n if (shape && !WORKSPACE_FREE_TOOLS.has(name)) {\n if (addsInput) {\n args[2] = {\n ...shape,\n [WORKSPACE_INPUT]: z\n .string()\n .min(1)\n .max(512)\n .optional()\n .describe(\n WORKSPACE_SPANNING_TOOLS.has(name)\n ? 'Workspace id or name. Leave it out to cover every granted workspace.'\n : 'Workspace id or name. Needed when you granted more than one workspace.'\n ),\n };\n }\n args[1] = `${args[1]}${workspaceLine(name, addsInput ? WORKSPACE_INPUT : ownSelector!)}`;\n }\n args[index] = async (...values: any[]) => {\n try {\n authorizeTool(name, bound);\n const target = assertToolArguments(name, values[0], bound, delegated);\n if (name === 'whoami') return whoami(bound);\n const input =\n values[0] && typeof values[0] === 'object'\n ? (values[0] as Record<string, unknown>)\n : undefined;\n if (input?.projectDir !== undefined)\n return toolError(\n 'projectDir is not available on the hosted server. Pass chartTs, manifest, bundleCss and iconSvg to compile in memory.'\n );\n if (\n !target &&\n !WORKSPACE_FREE_TOOLS.has(name) &&\n !WORKSPACE_SPANNING_TOOLS.has(name) &&\n !namesWorkspace(input)\n ) {\n throw new WorkspaceSelectionError(\n 400,\n 'WORKSPACE_REQUIRED',\n `Name the workspace for this call. Granted: ${grantedNames(bound)}.`\n );\n }\n if (input) {\n // The new input is a header, never a body field. A selector the tool declares\n // gets the call's workspace when it was left out, as for one granted workspace before.\n if (addsInput) delete input[WORKSPACE_INPUT];\n if (shape && target) {\n if (Object.hasOwn(shape, 'workspaceId'))\n input.workspaceId = target.id;\n if (\n Object.hasOwn(shape, 'workspaceName') &&\n target.name !== undefined\n )\n input.workspaceName = target.name;\n }\n }\n const result = await callWorkspace.run({ target }, () =>\n handler(...values)\n );\n // The iframe's follow-up calls have no model to repeat the workspace selector.\n // Carry only this verified call's workspace, never a draft's claimed choices.\n if (target && result?._meta?.['ui/resourceUri']) {\n return {\n ...result,\n _meta: { ...result._meta, 'databrain/workspace': target },\n };\n }\n return result;\n } catch (error) {\n if (error instanceof WorkspaceSelectionError)\n return workspaceError(error);\n return toolError(\n 'Hosted authorization denied this tool call. Check the granted scopes, workspace and tenant access.'\n );\n }\n };\n return register(...args);\n }) as McpServer['tool'];\n\n const client = new HostedClient(adapter, bound, delegation);\n enableChartApps(server);\n registerAllTools(server, client);\n // Hosted only: a grant of \"All workspaces I can access\" may create one (the issuer decides).\n registerCreateWorkspace(server, client);\n registerAllResources(server);\n registerAllPrompts(server);\n // Keep Apps on the principal-bound client and under the same registration policy.\n registerChartApps(server, client);\n instrument(server, schemaInstrumentation, { beforeSend: () => null });\n return server;\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport type { DatabrainClient } from '../../client/databrain-client.js';\nimport {\n DatabrainApiError,\n stringify,\n toolError,\n toolSuccess,\n} from '../../utils/errors.js';\nimport { WRITE_CREATE } from '../annotations.js';\n\n/**\n * Registered by the hosted server only (stdio dropped it in v0.2.0). The issuer allows it\n * only for a sign-in granted \"All workspaces I can access\" and a role that may create one.\n */\nexport function registerCreateWorkspace(\n server: McpServer,\n client: DatabrainClient\n): void {\n server.tool(\n 'create_workspace',\n 'Create a new workspace to connect a datasource or datamart for dashboard building. ' +\n 'Works only when this sign-in granted \"All workspaces I can access\" and your role may create workspaces; ' +\n 'the new workspace is usable on the next call.',\n {\n name: z.string().describe('Unique workspace name'),\n connectionType: z\n .enum(['DATASOURCE', 'DATAMART', 'MULTI_DATASOURCE'])\n .optional()\n .describe(\n 'Connection type — DATASOURCE, DATAMART, or MULTI_DATASOURCE'\n ),\n datasourceName: z\n .string()\n .optional()\n .describe(\n 'Datasource name (required when connectionType is DATASOURCE)'\n ),\n datamartName: z\n .string()\n .optional()\n .describe('Datamart name (required when connectionType is DATAMART)'),\n body: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Raw API body passthrough for POST /api/v2/workspace'),\n },\n WRITE_CREATE,\n async (params) => {\n try {\n const body: Record<string, unknown> = params.body\n ? { ...params.body }\n : {\n name: params.name,\n connectionType: params.connectionType,\n datasourceName: params.datasourceName,\n datamartName: params.datamartName,\n };\n\n const result = await client.request<{\n name?: string;\n id?: string;\n _id?: string;\n error?: unknown;\n }>({\n method: 'POST',\n path: '/api/v2/workspace',\n body,\n auth: 'service',\n invalidateCache: ['list_workspaces'],\n });\n\n if (result.error) {\n return toolError(\n `Workspace creation failed: ${stringify(result.error)}`\n );\n }\n\n return toolSuccess(\n `Workspace \"${result.name || params.name}\" created successfully.\\n\\n` +\n 'Next steps:\\n' +\n '1. Use `create_data_app` to create a data app linked to this workspace\\n' +\n '2. Build dashboards in the Databrain UI using this workspace\\n' +\n '3. Use `create_embed` to embed dashboards'\n );\n } catch (err) {\n if (err instanceof DatabrainApiError) return err.toToolResponse();\n return toolError(`Unexpected error: ${(err as Error).message}`);\n }\n }\n );\n}\n","import { z } from 'zod';\nimport { parseErrorBody } from '../client/error-body.js';\nimport { parseStudioStream } from '../custom-chart/studio.js';\nimport { toolContext } from '../utils/tool-context.js';\nimport { MCP_SERVER_VERSION } from '../version.js';\nimport { principalSchema } from './auth.js';\nimport type {\n HostedAdapter,\n HostedConfig,\n HostedDelegation,\n HostedErrorDetail,\n} from './types.js';\nimport { HostedAuthError } from './types.js';\n\nconst USER_AGENT = `databrain-mcp-server/${MCP_SERVER_VERSION} (hosted)`;\nconst REQUEST_TIMEOUT_MS = 30_000;\n/** Request headers a tool may set; nothing that can carry or replace a credential. */\nconst FORWARDED_HEADERS = new Set(['idempotency-key']);\n/** The call's workspace, for the issuer's delegated path. Only this adapter sets it. */\nexport const WORKSPACE_HEADER = 'X-Databrain-Workspace';\n/**\n * 403 codes whose reason is about the caller's own grant in a workspace it named and holds,\n * so they reveal nothing about other workspaces or companies. Every other 403 stays opaque.\n */\nconst GRANT_DENIALS = new Set([\n 'ROLE_NOT_ALLOWED',\n 'WORKSPACE_CREATE_NOT_ALLOWED',\n 'forbidden_permission',\n 'insufficient_scope',\n]);\n\n/** Code and message only, as short plain text; never other body fields or the bearer. */\nfunction errorDetail(\n status: number,\n text: string,\n bearer: string | undefined\n): HostedErrorDetail {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { status };\n }\n const envelope = parseErrorBody(parsed);\n // A dashboard write the API refuses tile by tile (422 `{tileVerdicts}`) carries no\n // envelope; its problems are the only reason a tool can act on.\n const tiles = tileProblems(parsed);\n const code = envelope.code ?? (tiles ? 'TILE_VALIDATION_FAILED' : undefined);\n const message = envelope.message ?? tiles;\n const clean = (value: string | undefined, max: number) => {\n if (!value) return undefined;\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Redaction intentionally removes control characters.\n let out = value.replace(/[\\u0000-\\u001f\\u007f]+/g, ' ').trim();\n if (bearer) out = out.split(bearer).join('[redacted]');\n return out.slice(0, max) || undefined;\n };\n // Long enough for the issuer's list of up to 20 granted workspace names.\n return {\n status,\n code: code && /^[A-Za-z0-9_.:-]{1,64}$/.test(code) ? code : undefined,\n message: clean(message, 1200),\n };\n}\n\n/** \"Tile t1: problem; problem. Tile t2: ...\" for the tiles a dashboard write refused. */\nfunction tileProblems(body: unknown): string | undefined {\n const verdicts = (body as { tileVerdicts?: unknown } | null)?.tileVerdicts;\n if (!Array.isArray(verdicts)) return undefined;\n const lines = verdicts.flatMap((verdict) => {\n const { id, ok, problems } = (verdict ?? {}) as {\n id?: unknown;\n ok?: unknown;\n problems?: unknown;\n };\n if (ok !== false || !Array.isArray(problems)) return [];\n const words = problems.filter((p): p is string => typeof p === 'string');\n return words.length\n ? [`Tile ${typeof id === 'string' ? id : '?'}: ${words.join(' ')}`]\n : [];\n });\n return lines.length\n ? `The dashboard was not saved. ${lines.join(' ')}`\n : undefined;\n}\n\n/** BE-3's documented principal endpoint is the trust boundary for opaque OAuth tokens. */\nexport function createProviderAdapter(config: HostedConfig): HostedAdapter {\n const issuer = new URL(config.issuer);\n if (\n issuer.protocol !== 'https:' ||\n issuer.username ||\n issuer.password ||\n issuer.search ||\n issuer.hash\n ) {\n throw new Error('Invalid hosted authorization server configuration.');\n }\n const apiBase = (config.apiUrl ?? config.issuer).replace(/\\/$/, '');\n const apiOrigin = new URL(apiBase).origin;\n const endpoint = `${apiBase}/oauth/principal`;\n const publicOrigin = new URL(config.publicUrl).origin;\n // Handle -> bearer, for this process only. A handle is unreadable and dies with its request.\n const bearers = new WeakMap<HostedDelegation, string>();\n const responseSchema = principalSchema\n .extend({ issuer: z.literal(config.issuer) })\n .strip();\n return {\n async verifyOAuth(token, resource) {\n try {\n // Only the explicitly configured issuer ever receives the token: here to verify it,\n // and in executeRequest for its delegated REST path. No redirects, other origins,\n // cache or service-token fallback.\n const response = await fetch(endpoint, {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n redirect: 'error',\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) {\n if (response.status === 429 || response.status >= 500)\n throw new HostedAuthError(503, 'temporarily_unavailable');\n throw new HostedAuthError(401, 'invalid_token');\n }\n const { issuer: _issuer, ...principal } = responseSchema.parse(\n await response.json()\n );\n if (\n principal.resource !== resource ||\n principal.credentialType !== 'oauth'\n )\n throw new HostedAuthError(401, 'invalid_token');\n return principal;\n } catch (error) {\n if (error instanceof HostedAuthError) throw error;\n throw new HostedAuthError(401, 'invalid_token');\n }\n },\n async resolvePatGrant() {\n throw new HostedAuthError(401, 'pat_membership_adapter_required');\n },\n delegate(token) {\n const handle: HostedDelegation = Object.freeze({\n kind: 'hosted-delegation' as const,\n });\n bearers.set(handle, token);\n return handle;\n },\n async executeRequest(options, principal, delegation, workspace) {\n // The backend's delegated path re-verifies this bearer for this resource on every\n // call, then binds workspace, objects, role and audit. Only the configured issuer\n // receives it, exactly as for /oauth/principal. A guest-token call carries only the\n // guest token the backend minted for this user's earlier, authorized call.\n const bearer = delegation ? bearers.get(delegation) : undefined;\n if (options.auth !== 'none' && !bearer)\n throw new HostedAuthError(503, 'delegated_backend_adapter_required');\n if (options.auth === 'none' && !options.token)\n throw new HostedAuthError(403, 'tool_not_authorized');\n if (!options.path.startsWith('/') || options.path.startsWith('//'))\n throw new HostedAuthError(403, 'tool_not_authorized');\n const url = new URL(`${apiBase}${options.path}`);\n if (url.origin !== apiOrigin)\n throw new HostedAuthError(403, 'tool_not_authorized');\n for (const [key, value] of Object.entries(options.query ?? {}))\n url.searchParams.set(key, value);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n 'X-Databrain-Client': USER_AGENT,\n };\n for (const [key, value] of Object.entries(options.headers ?? {})) {\n if (FORWARDED_HEADERS.has(key.toLowerCase())) headers[key] = value;\n }\n const tool = toolContext.getStore();\n if (tool) {\n headers['X-Databrain-MCP-Tool'] = tool.tool;\n headers['X-Databrain-MCP-Tool-Category'] = tool.category;\n headers['X-Databrain-MCP-Workflow-Intent'] = tool.workflowIntent;\n headers['X-Databrain-MCP-Input-Mode'] = tool.inputMode;\n }\n if (options.auth === 'none') {\n headers['x-plugin-token'] = options.token!;\n headers.Origin = publicOrigin;\n } else {\n headers.Authorization = `Bearer ${bearer}`;\n // Same rule as the bearer: only with it, only to the issuer, and only a workspace\n // this principal holds. The issuer re-checks it against the live grant.\n if (workspace) {\n if (\n !principal.grantedWorkspaces?.some(\n (item) => item.id === workspace.id\n ) &&\n principal.workspaceId !== workspace.id\n )\n throw new HostedAuthError(403, 'principal_mismatch');\n headers[WORKSPACE_HEADER] = workspace.id;\n }\n }\n const response = await fetch(url, {\n method: options.method,\n headers,\n redirect: 'error',\n body:\n options.body === undefined ? undefined : JSON.stringify(options.body),\n signal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS),\n });\n const text = await response.text();\n if (!response.ok) {\n // A wrong-workspace object is a 404, like a missing one. 401, 403 and 5xx keep the\n // status class only. Other 4xx keep the backend's code and message (a validation\n // reason, `layer_not_found`), so a tool can recover as it does on stdio.\n const forbidden =\n response.status === 403 ? errorDetail(403, text, bearer) : undefined;\n if (forbidden?.code && GRANT_DENIALS.has(forbidden.code)) {\n throw new HostedAuthError(\n 403,\n 'delegated_request_denied',\n forbidden.code === 'insufficient_scope' &&\n options.path === '/api/v2/guest-token/create'\n ? {\n ...forbidden,\n message:\n 'Guest/tenant operations require mcp:embeds:write. Ask an admin for a role that allows it, then connect again.',\n }\n : forbidden\n );\n }\n const status =\n response.status === 403 && options.responseFormat === 'studio-sse'\n ? 403\n : response.status === 401\n ? 401\n : response.status >= 500\n ? 503\n : response.status === 403 || response.status === 404\n ? 404\n : 400;\n const detail =\n status === 401 || status === 503 || response.status === 403\n ? undefined\n : errorDetail(response.status, text, bearer);\n throw new HostedAuthError(status, 'delegated_request_denied', detail);\n }\n try {\n return options.responseFormat === 'studio-sse'\n ? parseStudioStream(text)\n : text\n ? JSON.parse(text)\n : null;\n } catch {\n throw new HostedAuthError(503, 'delegated_response_invalid');\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;;;ACCvB,SAAS,iBACd,MAAyB,QAAQ,KACnB;AACd,QAAM,WAAW,IAAI,+BAA+B;AACpD,MAAI,YAAY,IAAI,aAAa;AAC/B,UAAM,IAAI,MAAM,8CAA8C;AAChE,MAAI,IAAI,8BAA8B,CAAC;AACrC,UAAM,IAAI,MAAM,qCAAqC;AACvD,QAAM,WAAW,CAAC,OAA2B,UAAkB;AAC7D,QAAI;AACF,UAAI,CAAC,MAAO,OAAM,IAAI,MAAM;AAC5B,YAAM,MAAM,IAAI,IAAI,KAAK;AACzB,UACE,IAAI,YACJ,IAAI,YACJ,IAAI,UACJ,IAAI,QACJ,IAAI,aAAa;AAEjB,cAAM,IAAI,MAAM;AAClB,aAAO;AAAA,IACT,QAAQ;AACN,YAAM,IAAI;AAAA,QACR,aAAa,KAAK;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AAGA,MAAI,cAAc,IAAI;AACtB,MAAI,cAAc,IAAI;AACtB,MAAI,CAAC,eAAe,CAAC,eAAe,IAAI,gBAAgB;AACtD,UAAM,SAA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