### Install Dependencies Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ai_sdk_agent/README.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Start Local MCP Server Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ai_sdk_agent/README.md Start the dbt MCP server for local use. ```bash npm run start:local ``` -------------------------------- ### Example Usage Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/admin_api/get_job_run_artifact.md Examples of how to specify the artifact path and optionally the step. ```json { "run_id": 789, "artifact_path": "manifest.json" } ``` ```json { "run_id": 789, "artifact_path": "compiled/analytics/models/staging/stg_users.sql" } ``` ```json { "run_id": 789, "artifact_path": "run_results.json", "step": 2 } ``` -------------------------------- ### Start Remote MCP Server Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ai_sdk_agent/README.md Start the dbt MCP server for remote use. ```bash npm start ``` -------------------------------- ### Configure Complete Setup Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/configuration.md Environment variables for hybrid setups using both local projects and dbt Cloud. ```bash # Local project export DBT_PROJECT_DIR=/home/user/my-dbt-project export DBT_PATH=/usr/local/bin/dbt # Platform export DBT_HOST=us1.dbt.com export DBT_TOKEN=abc123... export DBT_PROD_ENV_ID=12345 export DBT_DEV_ENV_ID=67890 export DBT_USER_ID=999 # Tuning export DBT_CLI_TIMEOUT=120 export DBT_MCP_SL_METRICS_RELATED_MAX=20 ``` -------------------------------- ### Start Development Server Source: https://github.com/dbt-labs/dbt-mcp/blob/main/CONTRIBUTING.md Commands to start the development server with specific transport configurations. ```bash task dev ``` ```bash MCP_TRANSPORT=stdio task dev ``` ```bash task run ``` -------------------------------- ### Usage Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/openai_responses/README.md Command to run the example. ```bash uv run main.py ``` -------------------------------- ### Invoke list_tools Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/server.md Usage example for listing and iterating over available tools provided by the server. ```python tools = await server.list_tools() for tool in tools: print(f"{tool.name}: {tool.description}") ``` -------------------------------- ### Get Node Details (Development) Examples Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/dbt_cli/get_node_details_dev.md Examples of how to call the `get_node_details_dev` function with different node identifiers. ```python get_node_details_dev(node_id="stg_zip__invoices") get_node_details_dev(node_id="model.my_project.stg_zip__invoices") get_node_details_dev(node_id="seed.my_project.country_codes") ``` -------------------------------- ### Get Exposure Details Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_exposure_details.md Example of how to retrieve details for an exposure using its unique ID. ```python get_exposure_details(unique_id="exposure.analytics.customer_dashboard") ``` -------------------------------- ### Get Lineage Usage Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/discovery-tools.md Demonstrates calling the get_lineage tool to trace upstream dependencies up to a specified depth. ```python lineage = await get_lineage(context, "model.myproject.customers", direction=LineageDirection.UPSTREAM, depth=2) # Returns ancestors up to 2 hops upstream ``` -------------------------------- ### Get Model Performance Usage Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/discovery-tools.md Demonstrates calling the get_model_performance tool with specific model name and run constraints. ```python perf = await get_model_performance(context, name="orders", num_runs=5, include_tests=True) ``` -------------------------------- ### Execute search_product_docs query Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/product-docs-tools.md Example usage of the search_product_docs function with a sample query string. ```python results = await search_product_docs("how to write dbt tests") # Returns: # [ # { # "title": "Testing", # "url": "https://docs.getdbt.com/docs/build/tests", # "description": "Tests are assertions you make about your data...", # "relevance_score": 0.98 # }, # { # "title": "Test properties", # "url": "https://docs.getdbt.com/reference/test-properties", # "description": "...", # "relevance_score": 0.95 # }, # ] ``` -------------------------------- ### Fetch documentation pages example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/product-docs-tools.md Demonstrates how to retrieve content for multiple documentation pages in a single call. ```python result = await get_product_doc_pages(["docs/build/tests", "reference/test-properties"]) # Returns: # { # "docs/build/tests": "# Tests\n\nTests are assertions...", # "reference/test-properties": "# Test Properties\n\n..." # } ``` -------------------------------- ### Handle ConfigurationError Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/errors.md Example of catching configuration errors during server initialization. ```python try: server = await create_dbt_mcp(config) except ConfigurationError as e: print(f"Configuration error: {e}") # Check and fix environment variables ``` -------------------------------- ### Run the multi-agent example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ag2_agent/README.md Executes the main_multiagent.py script for a multi-agent setup using dbt Cloud. ```bash uv run main_multiagent.py ``` -------------------------------- ### Example usage of metadata tools Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/mcp-server-metadata-tools.md Demonstrates checking version and branch status for production validation. ```python # Check if running production version version = await get_mcp_server_version() if version["version"] != "0.10.0": print(f"Warning: Unexpected version {version['version']}") # Verify production branch branch = await get_mcp_server_branch() if branch["branch"] != "main": print(f"Warning: Running on branch {branch['branch']}, not main") if branch["is_dirty"]: print("Warning: Working directory has uncommitted changes") ``` -------------------------------- ### Test Output Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/aws_strands_agent/README.md An example of the output from the comprehensive test suite, showing successful environment setup, tool imports, and overall test completion. ```text 🚀 Complete Tool and Agent Test Suite ================================================== 🔧 Testing Environment Setup ------------------------------ ✅ DBT_MCP_URL: https://your-mcp-server.com ✅ DBT_TOKEN: **************** ✅ DBT_USER_ID: your_user_id ✅ DBT_PROD_ENV_ID: your_env_id ✅ Environment setup complete! 📦 Testing Tool Imports ------------------------------ ✅ All tools imported successfully ✅ dbt_compile is callable ✅ dbt_mcp_tool is callable ✅ dbt_model_analyzer_agent is callable ... (more tests) 🎉 All tests passed! Your agent and tools are working correctly. ``` -------------------------------- ### Invoke call_tool Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/server.md Usage example for executing a tool call through the DbtMCP server instance. ```python server = DbtMCP(...) result = await server.call_tool("get_all_models", {}) ``` -------------------------------- ### Invoke get_all_sources tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/discovery-tools.md Example usage of the get_all_sources tool to retrieve all project sources. ```python sources = await get_all_sources(context) ``` -------------------------------- ### Execute docs tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/dbt-cli-tools.md Example usage of the docs tool to generate project documentation. ```python result = await docs() # Returns: # { # "status": "success", # "docs_path": "/path/to/target/docs", # } ``` -------------------------------- ### Run the single agent, local example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ag2_agent/README.md Executes the main_stdio.py script for a single agent setup running locally. ```bash uv run main_stdio.py ``` -------------------------------- ### Execute SQL query example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/sql-tools.md Demonstrates calling execute_sql with a standard SQL query string. ```python result = await execute_sql( sql_query="SELECT customer_id, COUNT(*) as order_count FROM orders GROUP BY customer_id LIMIT 10" ) # Returns: # { # "rows": [ # {"customer_id": 1, "order_count": 5}, # {"customer_id": 2, "order_count": 3}, # ], # "columns": ["customer_id", "order_count"], # "row_count": 2, # "execution_time_ms": 245, # } ``` -------------------------------- ### Install dbt-mcp Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/OVERVIEW.md Install the package via pip. ```bash pip install dbt-mcp ``` -------------------------------- ### Run the single agent, dbt Cloud example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ag2_agent/README.md Executes the main_remote.py script for a single agent setup using dbt Cloud. ```bash uv run main_remote.py ``` -------------------------------- ### Execute run tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/dbt-cli-tools.md Example usage of the run tool to execute specific models. ```python result = await run(models="orders customers") # Returns: # { # "status": "success", # "message": "Completed running 2 models", # "execution_time": 45.2, # } ``` -------------------------------- ### Run dbt-mcp Server Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/OVERVIEW.md Set environment variables for the dbt project path and executable, then start the server. ```bash # Set minimal configuration export DBT_PROJECT_DIR=/path/to/dbt-project export DBT_PATH=dbt # Run server (listens on stdio by default) dbt-mcp ``` -------------------------------- ### Execute fusion.compile_sql Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/lsp-tools.md Example usage of the fusion.compile_sql tool with a Jinja-templated SQL string. ```python result = await fusion_compile_sql( sql="SELECT * FROM {{ ref('customers') }} WHERE created_at > '{{ var('cutoff_date') }}'" ) ``` -------------------------------- ### Execute show tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/dbt-cli-tools.md Example usage of the show tool to retrieve a limited number of rows from a specific model. ```python result = await show(models="customers", limit=10) # Returns: # { # "results": [ # {"id": 1, "name": "Alice", ...}, # {"id": 2, "name": "Bob", ...}, # ], # "columns": ["id", "name", ...] # } ``` -------------------------------- ### Google Model Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ai_sdk_agent/README.md Example of configuring the AI SDK to use a Google model. ```typescript // Google import { google } from "@ai-sdk/google"; const model = google("gemini-2.0-flash"); ``` -------------------------------- ### Usage example for get_metrics_compiled_sql Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/semantic-layer-tools.md Demonstrates calling the tool with specific metrics and grouping dimensions. ```python compiled = await get_metrics_compiled_sql(["revenue"], group_by=["country"]) # Returns: # { # "sql": "SELECT country, SUM(amount) as revenue FROM orders GROUP BY country", # "metadata": {...} # } ``` -------------------------------- ### Run MCP Inspector Source: https://github.com/dbt-labs/dbt-mcp/blob/main/CONTRIBUTING.md Command to start the MCP inspector tool. ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### dbt Compile Tool Usage Examples Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/aws_strands_agent/README.md Example user prompts for the dbt Compile Tool. ```text > "Compile my dbt project and find any issues" > "What's wrong with my models in the staging folder?" ``` -------------------------------- ### dbt MCP Server Tool Usage Examples Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/aws_strands_agent/README.md Example user prompts for the dbt MCP Server Tool. ```text > "List all available dbt MCP tools" > "Show me the catalog from dbt Cloud" > "Run my models in dbt Cloud" > "What tests are available in my dbt project?" ``` -------------------------------- ### Invoke get_exposures tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/discovery-tools.md Example usage of the get_exposures tool to retrieve project exposures. ```python exposures = await get_exposures(context) # Returns: # [ # {"name": "executive_dashboard", "type": "dashboard", "description": "..."}, # {"name": "marketing_app", "type": "application", "description": "..."}, # ] ``` -------------------------------- ### Use CredentialsProvider Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/credentials-and-providers.md Demonstrates how to instantiate the provider and retrieve resolved settings. ```python provider = CredentialsProvider(settings) resolved_settings, headers = await provider.get_credentials() print(resolved_settings.host) # "us1.dbt.com" ``` -------------------------------- ### Usage of get_mart_models Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/discovery-tools.md Example call to retrieve mart models using the provided context. ```python marts = await get_mart_models(context) ``` -------------------------------- ### Example 2: Get time-related dimensions for metrics Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/semantic_layer/get_dimensions.md This example shows how to filter for time-related dimensions for 'total_sales' and 'average_order_value' metrics using the search parameter. ```python Parameters: metrics=["total_sales", "average_order_value"] search="time" ``` -------------------------------- ### Example usage of get_mcp_server_version Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/mcp-server-metadata-tools.md Retrieves version information as a dictionary containing version strings and development status. ```python info = await get_mcp_server_version() # Returns: # { # "version": "0.10.0", # "version_py": "0.10.0", # "is_development": False # } ``` -------------------------------- ### Handle RemoteToolError Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/errors.md Example of catching platform connection errors. ```python try: result = await execute_sql("SELECT COUNT(*) FROM orders") except RemoteToolError as e: print(f"Platform connection error: {e}") # Verify DBT_HOST and network connectivity ``` -------------------------------- ### Execute clone tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/dbt-cli-tools.md Example usage of the clone tool to clone specific models from a production state. ```python result = await clone(state="prod", models="customers") ``` -------------------------------- ### Example 1: Get all dimensions for a metric Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/semantic_layer/get_dimensions.md This example demonstrates how to retrieve all available dimensions for the 'revenue' metric when the user is interested in general analysis trends. ```python Parameters: metrics=["revenue"] search=null ``` -------------------------------- ### Initialize Configured Clients Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/credentials-and-providers.md Standard pattern for loading configuration and initializing service-specific providers. ```python from dbt_mcp.config.config import load_config from dbt_mcp.config.config_providers import DefaultDiscoveryConfigProvider # Load settings from environment config = load_config() # Create a credentials provider credentials_provider = config.credentials_provider # Create service-specific config provider discovery_config_provider = DefaultDiscoveryConfigProvider( credentials_provider=credentials_provider ) # Get config when needed discovery_config = await discovery_config_provider.get_config() # Use config to initialize client client = DiscoveryClient(discovery_config) ``` -------------------------------- ### Lifecycle Management Usage Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/server.md Example of how the app_lifespan context manager is invoked by the FastMCP framework. ```python # Called automatically by FastMCP framework, not directly async with app_lifespan(server): # Server is running pass ``` -------------------------------- ### Handle BinaryExecutionError Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/errors.md Example of catching binary execution errors to verify the environment configuration. ```python try: result = await run() except BinaryExecutionError as e: print(f"dbt binary error: {e}") # Verify DBT_PATH is correct and executable ``` -------------------------------- ### Get warnings only Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/admin_api/get_job_run_error.md Example JSON payload to retrieve only warning information for a specific job run. ```json { "run_id": 789, "warning_only": true } ``` -------------------------------- ### Execute fusion.get_column_lineage Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/lsp-tools.md Example usage of the fusion.get_column_lineage tool to trace a specific column in a model. ```python lineage = await fusion_get_column_lineage( project_id=123, model="revenue_by_country", column_name="total_revenue" ) ``` -------------------------------- ### Server Initialization and Tool Execution Flows Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/README.md Visual representation of the server startup sequence and the lifecycle of an MCP tool call. ```text load_config() → load environment variables ↓ create_dbt_mcp(config) → initialize FastMCP with tools ↓ server.run(transport) → listen for MCP calls ``` ```text MCP call → DbtMCP.call_tool() ↓ Determine single vs multi-project mode ↓ Route to FastMCP instance ↓ Context adapter → Create typed context ↓ Tool function → Execute ↓ Return result or throw error ``` -------------------------------- ### Get Job Details Request Body Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/admin_api/get_job_details.md Example JSON payload to specify the job ID for which to retrieve details. ```json { "job_id": 456 } ``` -------------------------------- ### Example Lineage Response Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_lineage.md A sample JSON response structure returned by the get_lineage function. ```json [ { "uniqueId": "source.raw.users", "name": "users", "resourceType": "Source", "parentIds": [] }, { "uniqueId": "model.stg_customers", "name": "stg_customers", "resourceType": "Model", "parentIds": ["source.raw.users"] }, { "uniqueId": "model.customers", "name": "customers", "resourceType": "Model", "parentIds": ["model.stg_customers"] } ] ``` -------------------------------- ### Retrieve project macros Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/discovery-tools.md Defines the signature for fetching macros and provides an example of filtering by package name. ```python async def get_all_macros( context: DiscoveryToolContext, package_names: list[str] | None = None, include_default_dbt_packages: bool = True, return_package_names_only: bool = False, ) -> list[dict] ``` ```python macros = await get_all_macros(context, package_names=["custom_macros"]) ``` -------------------------------- ### Get errors with warnings Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/admin_api/get_job_run_error.md Example JSON payload to retrieve both error and warning information for a specific job run. ```json { "run_id": 789, "include_warnings": true } ``` -------------------------------- ### Register tools usage example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/tool-registration.md Demonstrates how to invoke register_tools with specific tool definitions, a context mapper, and filtering configurations. ```python from dbt_mcp.discovery.tools import DiscoveryToolContext, get_all_models definitions = [get_all_models, ...] mapper = lambda provider: DiscoveryToolContext(provider) await register_tools( dbt_mcp=server, tool_definitions=definitions, context_mapper=mapper, disabled_tools={ToolName.SEARCH}, # Disable alpha search tool enabled_tools=None, # No allowlist enabled_toolsets={Toolset.DISCOVERY}, # Enable discovery category disabled_toolsets=set(), ) ``` -------------------------------- ### Example Request Body Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/admin_api/get_job_run_details.md This JSON object represents the request body to get details for a specific dbt job run. ```json { "run_id": 789 } ``` -------------------------------- ### Get performance with test execution history Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_model_performance.md This example shows how to retrieve model performance metrics along with the execution history of associated tests. ```python get_model_performance(unique_id="model.analytics.stg_orders", num_runs=5, include_tests=True) ``` -------------------------------- ### Basic Node Selection Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/dbt_cli/args/node_selection.md Examples of selecting individual models. ```bash my_model ``` -------------------------------- ### Register a tool using @dbt_mcp_tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/tool-registration.md Example of applying the decorator to an asynchronous function to register it as a tool. ```python @dbt_mcp_tool( description="List all models in the dbt project", title="Get All Models", read_only_hint=True, destructive_hint=False, idempotent_hint=True, ) async def get_all_models( context: DiscoveryToolContext, ) -> list[dict]: """Implementation of the tool.""" return await context.models_fetcher.fetch_models() ``` -------------------------------- ### Get latest run performance using unique_id Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_model_performance.md This example shows the preferred method for retrieving the latest performance metrics of a dbt model by its unique identifier. ```python get_model_performance(unique_id="model.analytics.stg_orders") ``` -------------------------------- ### Initialize dbt-mcp server Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/OVERVIEW.md The startup sequence for the server, including configuration parsing and service registration. ```text load_config() → Parse environment variables → Initialize credentials provider → Create service config providers (Discovery, Semantic Layer, Admin, etc.) → Auto-disable features with missing dependencies create_dbt_mcp(config) → Create FastMCP instance → Register tool categories based on config → Attach lifespan handler for startup/shutdown server.run(transport) → Listen for MCP calls → Dispatch to appropriate tool handlers ``` -------------------------------- ### Example Request Body Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/admin_api/get_project_details.md A JSON object representing the request body to get details for a specific dbt Cloud project. ```json { "project_id": 123 } ``` -------------------------------- ### Getting lineage with depth control Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/dbt_cli/get_lineage_dev.md Example of retrieving lineage up to a specified depth. ```python get_lineage_dev(unique_id="model.my_project.customer_orders", depth=3) ``` -------------------------------- ### Configure Product Docs Tool Availability Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/product-docs-tools.md Use environment variables to enable or disable the product documentation tools. ```bash export DISABLE_PRODUCT_DOCS=false # or to disable export DISABLE_PRODUCT_DOCS=true ``` -------------------------------- ### Fetch a seed by unique_id Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_seed_details.md Example of fetching a seed using its unique identifier. ```python get_seed_details(unique_id="seed.analytics.customers") ``` -------------------------------- ### Load Configuration Programmatically Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/configuration.md Initialize configuration at server startup using the load_config function. ```python from dbt_mcp.config.config import load_config config = load_config() ``` -------------------------------- ### Clone the repository Source: https://github.com/dbt-labs/dbt-mcp/blob/main/CONTRIBUTING.md Initial steps to download the project source code and enter the directory. ```shell git clone https://github.com/dbt-labs/dbt-mcp.git cd dbt-mcp ``` -------------------------------- ### Getting full lineage for a model Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/dbt_cli/get_lineage_dev.md Example of retrieving the complete lineage for a specified model. ```python get_lineage_dev(unique_id="model.my_project.customer_orders") ``` -------------------------------- ### Set up environment variables Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/aws_strands_agent/README.md Copies the example environment file and instructs to edit it. ```bash cp .env.example .env # Edit .env with your configuration ``` -------------------------------- ### Getting parents using only uniqueId Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_model_parents.md Example of how to retrieve parent models by providing only the model's uniqueId. ```python get_model_parents(uniqueId="model.my_project.customer_orders") ``` -------------------------------- ### Mock tool context for testing Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/tool-registration.md Demonstrates how to initialize a DiscoveryToolContext with mocked dependencies to test individual tool functions. ```python from unittest.mock import AsyncMock mock_context = DiscoveryToolContext( config_provider=AsyncMock(), models_fetcher=AsyncMock(), ... ) # Test tool directly result = await get_all_models(mock_context) ``` -------------------------------- ### Getting parents for a model by name Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_model_parents.md Example of how to retrieve parent models by providing the model's name. ```python get_model_parents(name="customer_orders") ``` -------------------------------- ### Fetch a test by unique_id Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_test_details.md This example shows how to fetch a dbt test using its unique identifier. ```python get_test_details(unique_id="test.analytics.is_empty_string") ``` -------------------------------- ### New Users per Week Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/semantic_layer/query_metrics.md This example demonstrates how to query the number of new users per week for the previous year. It includes steps for identifying metrics, dimensions, and entities, and shows an initial query with a limit for verification, followed by a follow-up query. ```python metrics=["new_users"] group_by=[{"name": "metric_time", "grain": "WEEK", "type": "time_dimension"}] order_by=[{"name": "metric_time", "grain": "WEEK", "descending": false}] where="{{ TimeDimension('metric_time', 'WEEK') }} >= '2023-01-01' AND {{ TimeDimension('metric_time', 'WEEK') }} < '2024-01-01'" limit=4 ``` ```python metrics=["new_users"] group_by=[{"name": "metric_time", "grain": "WEEK", "type": "time_dimension"}] order_by=[{"name": "metric_time", "grain": "WEEK", "descending": false}] where="{{ TimeDimension('metric_time', 'WEEK') }} >= '2023-01-01' AND {{ TimeDimension('metric_time', 'WEEK') }} < '2024-01-01'" limit=null ``` -------------------------------- ### Getting lineage filtered to only models and sources Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/dbt_cli/get_lineage_dev.md Example of retrieving lineage, including only 'Model' and 'Source' resource types. ```python get_lineage_dev(unique_id="model.my_project.customer_orders", types=["Model", "Source"]) ``` -------------------------------- ### Getting lineage excluding tests Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/dbt_cli/get_lineage_dev.md Example of retrieving lineage, excluding 'Test' resource types by specifying allowed types. ```python get_lineage_dev(unique_id="model.my_project.customer_orders", types=["Model", "Source", "Seed", "Snapshot", "Exposure"]) ``` -------------------------------- ### Fetch a test when only the node name is known Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_test_details.md This example demonstrates fetching a dbt test when only the node's name is available. ```python get_test_details(name="is_empty_string") ``` -------------------------------- ### Initialize MultiProjectDiscoveryConfigProvider Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/credentials-and-providers.md Constructor for multi-project Discovery API configuration that requires an admin client. ```python class MultiProjectDiscoveryConfigProvider(ConfigProvider[DiscoveryConfig]): def __init__( self, credentials_provider: CredentialsProvider, admin_client: DbtAdminAPIClient, ) -> None ``` -------------------------------- ### Configure environment variables Source: https://github.com/dbt-labs/dbt-mcp/blob/main/CONTRIBUTING.md Create a local environment file from the provided template. ```shell cp .env.example .env ``` -------------------------------- ### Fetch a seed when only the node name is known Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_seed_details.md Example of fetching a seed using its node name when the unique ID is not available. ```python get_seed_details(name="customers") ``` -------------------------------- ### Initialize DefaultProxiedToolConfigProvider Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/credentials-and-providers.md Configures remote SQL tools proxied through the dbt Platform. ```python class DefaultProxiedToolConfigProvider(ConfigProvider[ProxiedToolConfig]): def __init__(self, credentials_provider: CredentialsProvider) -> None ``` -------------------------------- ### Fetch a semantic model by unique_id Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_semantic_model_details.md This example shows how to retrieve semantic model details using its unique identifier. ```python get_semantic_model_details(unique_id="semantic_model.analytics.customers") ``` -------------------------------- ### Getting parents for a model by uniqueId (more precise) Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_model_parents.md Example of how to retrieve parent models by providing both the model's name and its uniqueId for a more precise match. ```python get_model_parents(name="customer_orders", uniqueId="model.my_project.customer_orders") ``` -------------------------------- ### Initialize DefaultAdminApiConfigProvider Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/credentials-and-providers.md Configures Admin API access using a provided credentials provider. ```python class DefaultAdminApiConfigProvider(ConfigProvider[AdminApiConfig]): def __init__(self, credentials_provider: CredentialsProvider) -> None ``` -------------------------------- ### Fetch a semantic model when only the node name is known Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_semantic_model_details.md This example demonstrates fetching semantic model details when only the node name is available. ```python get_semantic_model_details(name="customers") ``` -------------------------------- ### Initialize DefaultDiscoveryConfigProvider Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/credentials-and-providers.md Constructor for single-project Discovery API configuration. ```python class DefaultDiscoveryConfigProvider(ConfigProvider[DiscoveryConfig]): def __init__(self, credentials_provider: CredentialsProvider) -> None ``` -------------------------------- ### Analyze performance trend over last 10 runs Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_model_performance.md This example demonstrates how to analyze the performance trend of a dbt model over its last 10 execution runs. ```python get_model_performance(unique_id="model.analytics.fct_orders", num_runs=10) ``` -------------------------------- ### Fetch documentation using search results Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/product-docs-tools.md Shows how to pass a URL obtained from a search result into the documentation fetcher. ```python search_results = await search_product_docs("dbt macros") page_url = search_results[0]["url"] # e.g., "https://docs.getdbt.com/docs/build/macros" content = await get_product_doc_pages([page_url]) ``` -------------------------------- ### Fallback method using only name Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_model_performance.md This example illustrates the fallback method for retrieving model performance metrics using only the model's name, which should only be used when the unique_id is unknown. ```python get_model_performance(name="stg_orders", num_runs=5) ``` -------------------------------- ### Run Development Tasks Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/OVERVIEW.md Commands for running tests, formatting, and linting the project. ```bash # Run unit tests task test:unit # Run integration tests (requires credentials) task test:integration # Format and lint task fmt task check ``` -------------------------------- ### Enable SQL Tools Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/sql-tools.md Configure environment variables to enable SQL tool functionality. ```bash export DISABLE_SQL=false # or export DBT_MCP_ENABLE_SQL=true ``` -------------------------------- ### Anthropic Model Example Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ai_sdk_agent/README.md Example of configuring the AI SDK to use an Anthropic model. ```typescript // Anthropic import { anthropic } from "@ai-sdk/anthropic"; const model = anthropic("claude-sonnet-4-20250514"); ``` -------------------------------- ### Implement Tool with Context Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/tool-registration.md Demonstrates a tool function declaring its dependency on DiscoveryToolContext. ```python @dbt_mcp_tool(...) async def get_all_models(context: DiscoveryToolContext) -> list[dict]: config = await context.config_provider.get_config() return await context.models_fetcher.fetch_models(config=config) ``` -------------------------------- ### Configure dbt Platform Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/configuration.md Environment variables for connecting to dbt Cloud without a local project. ```bash export DBT_HOST=us1.dbt.com export DBT_TOKEN=abc123... export DBT_PROD_ENV_ID=12345 export DISABLE_DBT_CLI=true export DISABLE_DBT_CODEGEN=true ``` -------------------------------- ### Search and Fetch Documentation Workflow Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/product-docs-tools.md A common pattern for finding relevant documentation by query and retrieving the full content of the top result. ```python # 1. Search for relevant documentation search_results = await search_product_docs("dbt Python models") # 2. Get the top result's full content top_result_url = search_results[0]["url"] content = await get_product_doc_pages([top_result_url]) # 3. Use content in your application print(content) ``` -------------------------------- ### Install dependencies Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/aws_strands_agent/README.md Installs project dependencies using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Retrieve dbt resource details Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_node_details.md Examples demonstrating how to fetch metadata for various dbt resource types using unique identifiers or names. ```python # Get details for a model by unique_id get_node_details(resource_type="model", unique_id="model.analytics.orders") # Get details for a source by name get_node_details(resource_type="source", name="raw_users") # Get details for a semantic model get_node_details(resource_type="semantic_model", unique_id="semantic_model.analytics.orders") ``` -------------------------------- ### Batch Fetch Documentation Pages Source: https://github.com/dbt-labs/dbt-mcp/blob/main/_autodocs/api-reference/product-docs-tools.md Retrieves multiple documentation pages simultaneously using a list of paths. ```python paths = [ "docs/build/tests", "reference/test-properties", "guides/best-practices-dbt-tests" ] all_content = await get_product_doc_pages(paths) for path, markdown in all_content.items(): print(f"=== {path} ===\n{markdown}\n") ``` -------------------------------- ### Install AG2 with OpenAI and MCP support Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/ag2_agent/README.md Installs the AG2 library with necessary dependencies for OpenAI and dbt-mcp. ```bash pip install "ag2[openai,mcp]>=0.11.0" ``` -------------------------------- ### Get macros for specific packages Source: https://github.com/dbt-labs/dbt-mcp/blob/main/src/dbt_mcp/prompts/discovery/get_all_macros.md This command retrieves macros for specific packages by calling `get_all_macros` with a list of package names. ```python get_all_macros(package_names=['my_project']) ``` -------------------------------- ### Define an interactive MCP app tool Source: https://github.com/dbt-labs/dbt-mcp/blob/main/CONTRIBUTING.md Configure a tool with structured_output and meta fields to link it to an interactive UI resource. ```python @dbt_mcp_tool( description=get_prompt("category/tool_name"), title="My Visualization", read_only_hint=True, structured_output=True, meta={"ui": {"resourceUri": "ui://dbt-mcp/my-app"}}, ) async def my_viz_tool(context: MyToolContext, param: str) -> MyResult: ... ``` -------------------------------- ### dbt Model Analyzer Tool Usage Examples Source: https://github.com/dbt-labs/dbt-mcp/blob/main/examples/aws_strands_agent/README.md Example user prompts for the dbt Model Analyzer Tool. ```text > "Analyze my data modeling approach for best practices" > "Review the dependencies in my dbt project" > "Check the data quality patterns in my models" ```