import { CallToolResult } from '@modelcontextprotocol/server'; import { Ok } from 'ts-results-es'; import { z } from 'zod'; import { ArgsValidationError, DatasourceNotAllowedError, FeatureDisabledError, WorkbookDatasourceNotEnabledError, } from '../../../errors/mcpToolError.js'; import { useRestApi } from '../../../restApiInstance.js'; import { luidSchema } from '../../../sdks/routeSafety/ids.js'; import { GraphQLResponse } from '../../../sdks/tableau/apis/metadataApi.js'; import { RestApi } from '../../../sdks/tableau/restApi.js'; import { isEmbeddedDatasource } from '../../../sdks/tableau/types/dataSource.js'; import { ProductVersion } from '../../../sdks/tableau/types/serverInfo.js'; import { SiteRole } from '../../../sdks/tableau/types/user.js'; import { WebMcpServer } from '../../../server.web.js'; import { getResultForTableauVersion } from '../../../utils/isTableauVersionAtLeast.js'; import { Provider } from '../../../utils/provider.js'; import { getVizqlDataServiceDisabledError } from '../getVizqlDataServiceDisabledError.js'; import { resourceAccessChecker } from '../resourceAccessChecker.js'; import { ToolRules, WebTool } from '../tool.js'; import { combineFields, DatasourceType, FieldsResult, simplifyReadMetadataResult, } from './datasourceMetadataUtils.js'; export const getGraphqlQuery = (datasourceLuid: string): string => ` query datasourceFieldInfo { publishedDatasources(filter: { luid: "${datasourceLuid}" }) { name description owner { name } fields { name isHidden description descriptionInherited { attribute value } fullyQualifiedName __typename upstreamTables { name } ... on AnalyticsField { __typename } ... on ColumnField { dataCategory role dataType defaultFormat semanticRole aggregation aggregationParam } ... on CalculatedField { dataCategory role dataType defaultFormat semanticRole aggregation aggregationParam formula isAutoGenerated hasUserReference } ... on BinField { dataCategory role dataType formula binSize } ... on GroupField { dataCategory role dataType hasOther } ... on CombinedSetField { delimiter combinationType } } } }`; const paramsSchema = { datasourceLuid: luidSchema, fieldNames: z .array(z.string().nonempty()) .nonempty() .optional() .describe('Exact, case-sensitive field captions. Returns all matches for duplicate captions.'), search: z .string() .trim() .nonempty() .optional() .describe( 'Case-insensitive substring of field caption or description; combined with fieldNames using AND.', ), workbookLuid: luidSchema .optional() .describe( 'Required to access an embedded (workbook) data source: the LUID of the workbook it belongs to, e.g. the workbook LUID passed to get-workbook. Omit for published data sources.', ), }; export type GetDatasourceMetadataError = | { type: 'feature-disabled'; } | { type: 'datasource-not-allowed'; message: string; }; const getDatasourceMetadataToolDescription = ` This tool retrieves metadata for a specified datasource by taking the basic, high level, metadata results from Tableau's VizQL Data Service and enriches them with additional context provided by Tableau's Metadata API. The metadata provided by this tool consists of the datasource model, fields, and parameters that belong to the datasource. Fields will contain properties such as name and dataType, but may also expose richer context such as descriptions, dataCategories, roles, etc. This tool should be used for getting the metadata to ground the use of a tool that queries Tableau published data sources. `; const getDatasourceMetadataToolDescription20263 = ` This tool retrieves metadata for a datasource specified by its datasourceLuid, which may be a published or an embedded (workbook) data source. It takes the basic, high level, metadata results from Tableau's VizQL Data Service and enriches them with additional context provided by Tableau's Metadata API. The metadata provided by this tool consists of the datasource model, fields, and parameters that belong to the datasource. Fields will contain properties such as name and dataType. The richer Metadata API context (descriptions, dataCategories, roles, etc.) is only available for published data sources and may be absent for embedded ones. For an embedded data source, also pass workbookLuid: the LUID of the workbook it belongs to. The server configuration may restrict access to embedded data sources based on their workbook. This tool should be used for getting the metadata to ground the use of a tool that queries Tableau data sources. `; const fieldNameQueryGuidance = ` name is the display caption; fieldName is the internal query name. For duplicate captions, choose the intended logical table and use exact fieldName values with query-datasource's interpretFieldCaptionsAsFieldNames option. parameterName is the corresponding internal parameter name. `; export const getGetDatasourceMetadataTool = ( server: WebMcpServer, productVersion: ProductVersion, ): WebTool => { const rules = getDatasourceMetadataRules(productVersion); const getDatasourceMetadataTool = new WebTool({ server, name: 'get-datasource-metadata', minRequiredRole: SiteRole.VIEWER, description: new Provider( () => 'Retrieve metadata for all or selected fields. Use fieldNames for known exact captions, or search for a targeted caption/description lookup. Search is literal: related fields and formula dependencies may not match. For broad discovery or uncertain terminology, omit selectors; fetch referenced fields when needed. Selectors filter fields only; datasource descriptions, parameters and model relationships are unchanged. Inspect mcp.resultInfo for matching counts and unknown field names.\n' + getResultForTableauVersion({ productVersion, mappings: { '2026.3.0': getDatasourceMetadataToolDescription20263, default: getDatasourceMetadataToolDescription, }, }) + (rules.fieldNamesAreUnavailable ? '' : fieldNameQueryGuidance), ), paramsSchema, annotations: { title: 'Get Datasource Metadata', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false, }, callback: async ( { datasourceLuid, workbookLuid, fieldNames, search }, extra, ): Promise => { const query = getGraphqlQuery(datasourceLuid); return await getDatasourceMetadataTool.logAndExecute({ extra, args: { datasourceLuid, workbookLuid, fieldNames, search }, callback: async () => { if (!datasourceLuid) { return new ArgsValidationError('datasourceLuid must be a non-empty string.').toErr(); } const configWithOverrides = await extra.getConfigWithOverrides(); const isDatasourceAllowedResult = await resourceAccessChecker.isDatasourceAllowed({ datasourceLuid, workbookLuid, supportsWorkbookLuid: true, extra, }); if (!isDatasourceAllowedResult.allowed) { return new DatasourceNotAllowedError(isDatasourceAllowedResult.message).toErr(); } return await useRestApi({ ...extra, jwtScopes: getDatasourceMetadataTool.requiredApiScopes, callback: async (restApi) => { // Fetching metadata from VizQL Data Service API. const readMetadataResult = await restApi.vizqlDataServiceMethods.readMetadata({ datasource: { datasourceLuid, }, }); if (readMetadataResult.isErr()) { // Embedded (workbook) data sources are gated behind a per-site opt-in; surface the // actionable gate error rather than the generic VizQL-disabled message. if (readMetadataResult.error === 'workbook-datasource-not-enabled') { return new WorkbookDatasourceNotEnabledError().toErr(); } return new FeatureDisabledError(getVizqlDataServiceDisabledError()).toErr(); } // Fetching datasource model from VizQL Data Service API. const datasourceModelResult = !rules.datasourceModelIsUnavailable ? await restApi.vizqlDataServiceMethods.getDatasourceModel({ datasource: { datasourceLuid, }, }) : undefined; if (datasourceModelResult && datasourceModelResult.isErr()) { return new FeatureDisabledError(getVizqlDataServiceDisabledError()).toErr(); } // Resolve the type on every path so it's set even when the Metadata API is disabled or // throws, not only on the publishedDatasources-match path. if (configWithOverrides.disableMetadataApiRequests) { // Exit early since requests to the Tableau Metadata API are disabled. return Ok( simplifyReadMetadataResult( readMetadataResult.value, datasourceModelResult?.value, await resolveDatasourceType(restApi, datasourceLuid, false), ), ); } let listFieldsResult: GraphQLResponse; try { // Fetching metadata from Tableau Metadata API. // Using try-catch here since requests could fail if the service is not enabled. listFieldsResult = await restApi.metadataMethods.graphql(query); } catch { return Ok( simplifyReadMetadataResult( readMetadataResult.value, datasourceModelResult?.value, await resolveDatasourceType(restApi, datasourceLuid, false), ), ); } const datasourceType = await resolveDatasourceType( restApi, datasourceLuid, !!listFieldsResult.data.publishedDatasources?.[0], ); // Combine the results from the VizQL Data Service API and the Tableau Metadata API. return Ok( combineFields( readMetadataResult.value, listFieldsResult, datasourceModelResult?.value, datasourceType, ), ); }, }); }, constrainSuccessResult: (fields) => { return { type: 'success', result: selectFields(fields, fieldNames, search), }; }, }); }, }); return getDatasourceMetadataTool; }; function selectFields(source: FieldsResult, fieldNames?: string[], search?: string): FieldsResult { if (!fieldNames && search === undefined) return source; const fields = source.fieldGroups.flatMap((group) => group.fields); const availableNames = new Set(fields.map((field) => field.name)); const selectedNames = fieldNames ? new Set(fieldNames) : undefined; const term = search?.toLowerCase(); const fieldGroups = source.fieldGroups .map((group) => ({ ...group, fields: group.fields.filter( (field) => (!selectedNames || selectedNames.has(field.name ?? '')) && (term === undefined || [field.name, field.description].some((value) => value?.toLowerCase().includes(term))), ), })) .filter((group) => group.fields.length > 0); return { ...source, fieldGroups, mcp: { resultInfo: { totalFields: fields.length, matchedFields: fieldGroups.reduce((count, group) => count + group.fields.length, 0), unknownFieldNames: [...(selectedNames ?? [])].filter((name) => !availableNames.has(name)), }, }, }; } // A publishedDatasources match (Metadata API) is authoritative and free. Otherwise probe the REST // Query Data Source endpoint and classify on the returned shape: WBDS-enabled servers return // embedded (workbook) data sources here too (HTTP 200) — those carry `parentType: "Workbook"` and no // `project`, while published ones carry a `project`. A 404 means the server doesn't serve this LUID // via REST at all; since the LUID is already VizQL-resolvable, that too is an embedded signal. Any // other error ⇒ leave unset (best-effort; must never break the metadata response). async function resolveDatasourceType( restApi: RestApi, datasourceLuid: string, hasPublishedMatch: boolean, ): Promise { if (hasPublishedMatch) { return 'published'; } const restLookup = await restApi.datasourcesMethods.tryQueryDatasource({ siteId: restApi.siteId, datasourceId: datasourceLuid, }); if (restLookup.isOk()) { return isEmbeddedDatasource(restLookup.value) ? 'embedded' : 'published'; } if (restLookup.error === 'not-found') { return 'embedded'; } return undefined; } function getDatasourceMetadataRules(productVersion: ProductVersion): ToolRules { return getResultForTableauVersion({ productVersion, mappings: { '2025.3.0': {}, default: { datasourceModelIsUnavailable: true, fieldNamesAreUnavailable: true, }, }, }); }