### Install Kqlmagic Extension Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/recipes/KustoPrivateShotsNotebook.ipynb Installs the Kqlmagic extension if it's not already present. This is typically pre-installed on Fabric Notebooks. ```python # %pip install Kqlmagic ``` -------------------------------- ### Install Microsoft Fabric RTI MCP Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/README.md Install the MCP package using pip. This is the first step for getting started with the library. ```bash pip install microsoft-fabric-rti-mcp ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/CONTRIB.md Installs the project's development dependencies using pip. Ensure you are in the project's root directory. ```bash pip install -e '.[dev]" ``` -------------------------------- ### Make a GET Request using FabricHttpClient Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Example of making a GET request to retrieve workspace items using the FabricHttpClient. This method automatically handles authentication and error conversion. ```python client = FabricHttpClient() result = client.make_request( "GET", "/workspaces/550e8400-e29b-41d4-a716-446655440000/items" ) ``` -------------------------------- ### Initialize and Use KustoConnection Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Example of initializing a KustoConnection and executing a query using its query_client. Requires the KustoConnection class definition. ```python from fabric_rti_mcp.services.kusto.kusto_connection import KustoConnection conn = KustoConnection("https://help.kusto.windows.net", "Samples") result = conn.query_client.execute("Samples", "StormEvents | limit 10", crp) ``` -------------------------------- ### Basic Setup with Environment Variables Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/configuration.md Sets up basic Kusto connection details for stdio transport. Ensure these environment variables are exported before running the application. ```bash export KUSTO_SERVICE_URI=https://help.kusto.windows.net export KUSTO_SERVICE_DEFAULT_DB=Samples export FABRIC_API_BASE=https://api.fabric.microsoft.com/v1 ``` -------------------------------- ### Client Request Properties Example Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/types.md Example dictionary for setting Kusto client request properties like timeouts and query hints. ```python client_request_properties = { "servertimeout": "00:10:00", "querying_properties": json.dumps({"max_memory": 1000000}) } ``` -------------------------------- ### Install MCP Server Locally with Pip Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/README.md This command installs the MCP server locally in editable mode with development dependencies. Ensure Python 3.10+ is installed and added to your PATH. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Use Semantic Search for Kusto Query Examples Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/patterns-best-practices.md Leverage semantic search to find relevant KQL query examples before writing them from scratch. This helps in discovering correct tables, databases, and proven patterns, reducing development time and syntax errors. ```python # Get semantically similar examples BEFORE writing query shots = kusto_get_shots( "Find high-error transactions in the last hour", cluster_uri, shots_table_name="AI.Examples", sample_size=3 ) # Shots contain: # - similarity score # - natural language description # - expert-written KQL example # Use as template for your query # Modify column names and values as needed result = kusto_query( shots[0]['AugmentedText'], # Use example as starting point cluster_uri, database="MyDb" ) ``` -------------------------------- ### Production and Development Environment Setup Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/patterns-best-practices.md Use separate environment files for production and development to manage configurations and ensure isolation. This approach simplifies deployment and testing. ```bash # Prod source production.env python -m fabric_rti_mcp.server # Dev source development.env python -m fabric_rti_mcp.server ``` -------------------------------- ### Typical Eventstream Builder Workflow Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/eventstream-tools.md Demonstrates the typical sequence of operations for building an eventstream, from starting a session to creating the eventstream in a workspace. ```python # 1. Start a builder session session = eventstream_start_definition("MyStream", "My data stream") session_id = session['session_id'] # 2. Add sources eventstream_add_sample_data_source(session_id, "Bicycles") # 3. Add destinations eventstream_add_eventhouse_destination(session_id, database="MyDb", table="Events") # 4. Validate validation = eventstream_validate_definition(session_id) # 5. Create in workspace created = eventstream_create_from_definition( session_id, "550e8400-e29b-41d4-a716-446655440000", "MyStream" ) ``` -------------------------------- ### Set Up Test Database and Tables Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/patterns-best-practices.md Demonstrates the setup of a test database, creation of a test table, ingestion of sample data, execution of a query, and subsequent cleanup of the test database. Ensures a safe and reproducible testing environment. ```python # Setup test database kusto_command( ".create-merge database TestDB", cluster_uri, database="NetDefaultDB" ) # Create test tables kusto_command( ".create table TestEvents (EventId: int, Message: string)", cluster_uri, database="TestDB" ) # Add test data kusto_ingest_inline_into_table( "TestEvents", "1,Test message\n2,Another message", cluster_uri, database="TestDB" ) # Run tests result = kusto_query( "TestEvents | count", cluster_uri, database="TestDB" ) # Cleanup kusto_command( ".drop database TestDB", cluster_uri, database="NetDefaultDB" ) ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/README.md Installs the uv package manager using a PowerShell script. Ensure your execution policy allows script execution. ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Initialize and Query Kusto Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/index.md Find relevant Kusto query examples using natural language and then execute a specific KQL query against a database. Ensure the Kusto SDK is imported. ```python # Find relevant examples first shots = kusto_get_shots("your natural language query", cluster_uri) # Then execute result = kusto_query("KQL query", cluster_uri, database="MyDb") ``` -------------------------------- ### Get KustoConnection from Manager Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Example of obtaining a KustoConnection instance from the KustoConnectionManager. The manager handles caching and creation of new connections. ```python manager = KustoConnectionManager() conn = manager.get("https://prod.kusto.windows.net") ``` -------------------------------- ### Server Startup with Command-Line Arguments Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/configuration.md Example of launching the fabric-rti-mcp server using command-line arguments to override environment variables. This demonstrates enabling HTTP transport, specifying host and port, and activating OBO flow and AI Foundry compatibility. ```bash python -m fabric_rti_mcp.server \ --http \ --host 0.0.0.0 \ --port 8080 \ --stateless-http \ --use-obo-flow \ --use-ai-foundry-compat ``` -------------------------------- ### Define NL Prompt and Query Setup Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/recipes/KustoPrivateShotsNotebook.ipynb Sets up the natural language prompt for AI and defines the KQL query for generating explanations, embeddings, and ingesting data. Ensure necessary variables like SHOTS_TABLE, CHAT_COMPLETION_ENDPOINT, EMBEDDING_ENDPOINT, comma_separated_sample_shots, and AUTHOR are defined. ```python # Query setup NL_PROMPT = '''Generate a natural language request that would lead a user to write the following KQL query. The request should reflect what the user wants to know or investigate, phrased naturally and without technical jargon. The output should strictly be the generated natural language. After you generate the natural language make sure it matches the results given by the KQL query. KQL query: ''' explain_embed_ingest_query = f''' .append {SHOTS_TABLE} <| let chatCompletionEndpoint="{CHAT_COMPLETION_ENDPOINT}"; let embeddingEndpoint="{EMBEDDING_ENDPOINT}"; let embeddingModel = tostring(extract("deployments/([^/]*)/", 1, embeddingEndpoint)); let prompt = ```{NL_PROMPT}```; let Shots = datatable(Query:string) [{comma_separated_sample_shots}]; Shots | extend NLprompt = strcat(prompt, Query) | evaluate ai_chat_completion_prompt(NLprompt, chatCompletionEndpoint) | project-rename NaturalLanguage = NLprompt_chat_completion | evaluate ai_embeddings(NaturalLanguage, embeddingEndpoint) | project-rename EmbeddingVector = NaturalLanguage_embeddings | project Timestamp = now(), NaturalLanguage, Query, EmbeddingVector, Author = "{AUTHOR}", Tags = pack_array(embeddingModel) ''' ``` -------------------------------- ### Retrieve Semantically Similar KQL Query Examples Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-tools.md Retrieves semantically similar KQL query examples based on a natural language prompt. Call this before writing KQL to discover correct databases, tables, columns, and query patterns. The shots table requires 'EmbeddingText', 'AugmentedText', and 'EmbeddingVector' columns. ```python def kusto_get_shots( prompt: str, cluster_uri: str, shots_table_name: str | None = None, sample_size: int = 3, database: str | None = None, embedding_endpoint: str | None = None, client_request_properties: dict[str, Any] | None = None, ) -> dict[str, Any]: ... shots = kusto_get_shots( "Find all storms in Illinois", "https://help.kusto.windows.net", shots_table_name="AI.ShotsTable", sample_size=5 ) ``` -------------------------------- ### Example Azure OpenAI Embedding Endpoint Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/configuration.md An example of a fully formed Azure OpenAI embedding endpoint URL with impersonation enabled. ```text https://myopenai.openai.azure.com/openai/deployments/text-embedding-ada-002/embeddings?api-version=2024-10-21;impersonate ``` -------------------------------- ### Manual Install Configuration for Fabric RTI MCP Server Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/README.md This JSON configuration is used in vscode settings.json or mcp.json for manual installation from source. It specifies the command, directory, run arguments, and environment variables. ```json { "mcp": { "servers": { "fabric-rti-mcp": { "command": "uv", "args": [ "--directory", "C:/path/to/fabric-rti-mcp/", "run", "-m", "fabric_rti_mcp.server" ], "env": { "KUSTO_SERVICE_URI": "https://help.kusto.windows.net/", "KUSTO_SERVICE_DEFAULT_DB": "Samples", "FABRIC_API_BASE": "https://api.fabric.microsoft.com/v1" } } } } } ``` -------------------------------- ### Environment-Specific Configuration using Environment Variables Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/patterns-best-practices.md Provides examples of environment variable files for production and development environments. These variables define settings like API base URLs, Kusto URIs, and database names, allowing the same code to run with different configurations. ```bash # production.env export FABRIC_API_BASE=https://api.fabric.microsoft.com/v1 export KUSTO_SERVICE_URI=https://prod.kusto.windows.net export KUSTO_SERVICE_DEFAULT_DB=Production export KUSTO_ALLOW_UNKNOWN_SERVICES=false export FABRIC_RTI_KUSTO_TIMEOUT=300 # development.env export FABRIC_API_BASE=https://api.fabric.microsoft.com/v1 export KUSTO_SERVICE_URI=https://dev.kusto.windows.net export KUSTO_SERVICE_DEFAULT_DB=Development export KUSTO_ALLOW_UNKNOWN_SERVICES=true export FABRIC_RTI_KUSTO_TIMEOUT=600 ``` -------------------------------- ### HTTP Client Headers for MCP Server Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/README.md Example of setting up authorization and content type headers for an HTTP client connecting to the MCP server. Ensure the Authorization header includes the correct Bearer token. ```python # Example from test_kusto_tools_live_http.py auth_header = f"Bearer {token.token}" headers = { "Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": auth_header, } ``` -------------------------------- ### UUID Format Example Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/types.md Illustrates the standard UUID format used for all IDs in Fabric. Examples for Workspace, Item, and Stream IDs are provided. ```plaintext xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ``` -------------------------------- ### Kusto Response Format Example Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md An example of the native Azure Kusto response format, including column definitions and row data. This is the default format returned by the formatter. ```json { "format": "kusto_response", "data": { "columns": [ {"ColumnName": "col1", "ColumnType": "string"}, {"ColumnName": "col2", "ColumnType": "int"} ], "rows": [ ["value1", 100], ["value2", 200] ] } } ``` -------------------------------- ### Semantic Search Setup with Embeddings Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/configuration.md Configures Kusto connection and Azure OpenAI embedding endpoint for semantic search capabilities. This setup is useful for applications requiring vector search on data stored in Kusto. ```bash export KUSTO_SERVICE_URI=https://help.kusto.windows.net export KUSTO_SERVICE_DEFAULT_DB=Samples export AZ_OPENAI_EMBEDDING_ENDPOINT=https://myopenai.openai.azure.com/openai/deployments/text-embedding-ada-002/embeddings?api-version=2024-10-21;impersonate export KUSTO_SHOTS_TABLE=MyDatabase.QueryExamples ``` -------------------------------- ### ISO 8601 Timestamp Format Example Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/types.md Shows the ISO 8601 UTC format for timestamps in Fabric API responses. Includes examples for standard and Python isoformat representations. ```plaintext 2024-01-15T14:30:00Z or 2024-01-15T14:30:00+00:00 ``` ```plaintext 2024-01-15T14:30:00.123456 (Python isoformat) ``` -------------------------------- ### Run Tests Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/CONTRIB.md Executes all project tests using pytest. Ensure all dependencies are installed before running. ```bash pytest ``` -------------------------------- ### Start Eventstream Builder Session Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/eventstream-tools.md Initiates a new Eventstream builder session with a given name and optional description. Returns session details including a session ID. ```python def eventstream_start_definition(name: str, description: str | None = None) -> dict[str, Any]: pass session = eventstream_start_definition( "My_Data_Stream", "Processing IoT sensor data" ) session_id = session['session_id'] ``` -------------------------------- ### kusto_get_shots() Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-tools.md Retrieves semantically similar KQL query examples based on a natural language prompt. This is critical for discovering correct databases, tables, column names, and query patterns. ```APIDOC ## kusto_get_shots() ### Description Retrieves semantically similar KQL query examples. ### Method ```python def kusto_get_shots( prompt: str, cluster_uri: str, shots_table_name: str | None = None, sample_size: int = 3, database: str | None = None, embedding_endpoint: str | None = None, client_request_properties: dict[str, Any] | None = None, ) ``` ### Parameters #### Path Parameters - **prompt** (str) - Required - Natural language description of desired query - **cluster_uri** (str) - Required - Cluster URI #### Query Parameters - **shots_table_name** (str) - Optional - Table with EmbeddingText, AugmentedText, EmbeddingVector columns (Default: KUSTO_SHOTS_TABLE) - **sample_size** (int) - Optional - Number of similar examples to return (Default: 3) - **database** (str) - Optional - Database containing shots table (Default: AI or default) - **embedding_endpoint** (str) - Optional - Azure OpenAI embedding endpoint URL (Default: AZ_OPENAI_EMBEDDING_ENDPOINT) - **client_request_properties** (dict) - Optional - Custom client request properties ### Returns `dict[str, Any]` - Result with columns: similarity, EmbeddingText, AugmentedText (Sorted by semantic similarity) ### Critical Requirements - Call this BEFORE writing KQL queries to discover: Correct databases and tables for your data, Proper column names and schema, Proven query patterns. ### Shots Table Schema - `EmbeddingText` (string) — Natural language description - `AugmentedText` (string) — Example KQL query - `EmbeddingVector` (dynamic) — Embedding vector for EmbeddingText ### Example ```python shots = kusto_get_shots( "Find all storms in Illinois", "https://help.kusto.windows.net", shots_table_name="AI.ShotsTable", sample_size=5 ) ``` ``` -------------------------------- ### Example CRP Output Structure Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Illustrates the structure of a Client Request Properties (CRP) dictionary after being built. Includes application info, request ID, and readonly settings. ```json { "application": "fabric-rti-mcp{1.0.0}", "client_request_id": "KFRTI_MCP.kusto_query:uuid-here", "request_readonly": true, "request_readonly_hardline": true, "request_timeout": timedelta(seconds=30) } ``` -------------------------------- ### Local Development with Interactive Browser Login and Fabric Server Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Starts the Fabric RTI MCP server for local development using an interactive browser login. The --stdio flag indicates standard input/output mode. ```bash # Option 2: Interactive browser python -m fabric_rti_mcp.server --stdio ``` -------------------------------- ### Parsed Query Plan JSON Structure Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Example structure of a parsed query plan, including statistics, operator tree, and execution hints. ```json { "query_text": "normalized KQL", "stats": { "Duration": "00:00:00.123456", "PlanSize": 12345, "RelopSize": 6789 }, "relop_tree": { "Name": "Tabular", "Children": [...] }, "execution_hints": { "estimated_rows": 1000, "concurrency": -1, "spread": -1, "shard_scans": [ {"total_rows": 500, "has_selection": true}, {"total_rows": 500, "has_selection": false} ] }, "error": null } ``` -------------------------------- ### Initiate Interactive Browser Login Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Starts the Fabric RTI MCP server, defaulting to an interactive browser-based login flow when no environment variables for authentication are set. This is suitable for local development and testing. ```bash # No env vars set → defaults to interactive browser python -m fabric_rti_mcp.server ``` -------------------------------- ### Local Development with Azure CLI and Fabric Server Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Starts the Fabric RTI MCP server for local development using Azure CLI authentication. The --stdio flag indicates that the server should run in standard input/output mode. ```bash # Option 1: Azure CLI (recommended) az login python -m fabric_rti_mcp.server --stdio ``` -------------------------------- ### Azure Container Apps/Functions (HTTP) Setup Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Set up Azure Container Apps or Functions for Fabric RTI MCP using HTTP transport with managed identity. No explicit credentials are needed as managed identity is automatic. ```bash # Use managed identity export FABRIC_RTI_TRANSPORT=http export FABRIC_RTI_HTTP_HOST=0.0.0.0 # No explicit credentials needed — managed identity is automatic ``` -------------------------------- ### Execute KQL Query for Data Ingestion Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/recipes/KustoPrivateShotsNotebook.ipynb Runs the pre-defined KQL query to process shots, generate natural language explanations, create vector embeddings, and ingest the results into the specified shots table. This command requires the Kqlmagic extension to be installed and enabled. ```python # Run query # The query will generate natural language explanations, vector embeddings, and ingest into shots table %kql -query explain_embed_ingest_query ``` -------------------------------- ### Production Setup with HTTP Mode and Multiple Kusto Services Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/configuration.md Configures fabric-rti-mcp for production using HTTP transport, specifying host, port, and path. It also defines multiple Kusto services with their respective databases and enables AI embeddings. ```bash export FABRIC_RTI_TRANSPORT=http export FABRIC_RTI_HTTP_HOST=0.0.0.0 export FABRIC_RTI_HTTP_PORT=8080 export FABRIC_RTI_HTTP_PATH=/mcp export FABRIC_RTI_STATELESS_HTTP=true export KUSTO_KNOWN_SERVICES='[ {"service_uri":"https://prod.kusto.windows.net","default_database":"Production","description":"Prod"}, {"service_uri":"https://dev.kusto.windows.net","default_database":"Development","description":"Dev"} ]' export KUSTO_ALLOW_UNKNOWN_SERVICES=false export AZ_OPENAI_EMBEDDING_ENDPOINT=https://myopenai.openai.azure.com/openai/deployments/text-embedding-ada-002/embeddings?api-version=2024-10-21;impersonate export KUSTO_SHOTS_TABLE=AI.ShotsTable ``` -------------------------------- ### Interactive Eventstream Building with Validation Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/patterns-best-practices.md Build eventstreams interactively by starting a session, adding sources and destinations, and validating the definition before creation. This pattern provides immediate feedback on errors and allows for iterative refinement. ```python # 1. Start session session = eventstream_start_definition("DataPipeline") sid = session['session_id'] # 2. Add sources eventstream_add_sample_data_source(sid, "Bicycles", "bike_source") print(f"✓ Added bike data source") # 3. Add destinations eventstream_add_eventhouse_destination( sid, destination_name="kql_dest", database="Analytics", table="BikeEvents" ) print(f"✓ Added Eventhouse destination") # 4. Validate before creating validation = eventstream_validate_definition(sid) if not validation['is_valid']: print(f"✗ Validation failed: {validation['errors']}") else: print("✓ Definition is valid") # 5. Create in workspace created = eventstream_create_from_definition( sid, workspace_id, "BikeDataPipeline" ) print(f"✓ Created: {created['id']}") ``` -------------------------------- ### Build and Deploy Locally (macOS/Linux) Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/CONTRIB.md Builds executables and wheels, and uploads them locally. Replace '0.1.0' with the desired version. ```bash ./scripts/build_deploy_local.sh 0.1.0 ``` -------------------------------- ### Quick Test with Kusto Samples Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/README.md Run a quick test of the MCP server using sample Kusto data. This requires setting specific environment variables for the Kusto service. ```bash export KUSTO_SERVICE_URI=https://help.kusto.windows.net export KUSTO_SERVICE_DEFAULT_DB=Samples python -m fabric_rti_mcp.server ``` -------------------------------- ### Build and Deploy Locally (Windows) Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/CONTRIB.md Builds executables and wheels, and uploads them locally. Replace '0.1.0' with the desired version. ```powershell scripts\build_deploy_local.bat 0.1.0 ``` -------------------------------- ### Example Kusto Query Error Message Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Shows an example of an error message that might be returned during Kusto query execution, including the correlation ID and the specific error detail. ```text Error executing Kusto operation 'kusto_query' (correlation ID: KFRTI_MCP.kusto_query:uuid): Column 'InvalidCol' does not exist in the table or ADX expression. ``` -------------------------------- ### Create Activator Trigger Workflow Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/activator-map-tools.md Demonstrates the workflow for creating a new trigger using the ActivatorService. This involves listing existing artifacts, creating the trigger with specific KQL details and alert configurations, and then accessing the trigger's URL. ```python service = ActivatorService() # 1. List existing artifacts artifacts = service.activator_list_artifacts(workspace_id) # 2. Create new trigger trigger = service.activator_create_trigger( workspace_id=workspace_id, trigger_name="sales_alert", kql_cluster_url="https://cluster.kusto.windows.net", kql_database="Sales", kql_query="Revenue | where Amount > 10000", alert_recipient="sales-team@company.com", alert_headline="High Sale Alert", alert_message="Sale amount exceeded $10,000", alert_type="teams" ) # 3. Access trigger in Fabric UI via trigger['url'] print(f"Trigger created: {trigger['url']}") ``` -------------------------------- ### Configure OBO Flow and Tenant IDs Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/configuration.md Set environment variables to enable On-Behalf-Of (OBO) flow and specify Azure tenant and client IDs for authentication. ```bash export USE_OBO_FLOW=true export FABRIC_RTI_MCP_AZURE_TENANT_ID=72f988bf-86f1-41af-91ab-2d7cd011db47 export FABRIC_RTI_MCP_ENTRA_APP_CLIENT_ID=client-id-here export FABRIC_RTI_MCP_USER_MANAGED_IDENTITY_CLIENT_ID=umi-client-id-here ``` -------------------------------- ### kusto_command() Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-tools.md Executes a Kusto management command (DDL/DCL) on a Kusto cluster. Commands must start with a dot (`.`). ```APIDOC ## kusto_command() ### Description Executes a Kusto management command (DDL/DCL). ### Method POST ### Endpoint /kusto/command ### Parameters #### Query Parameters - **cluster_uri** (str) - Required - Cluster URI - **database** (str) - Optional - Database name #### Request Body - **command** (str) - Required - Kusto management command starting with `.` - **client_request_properties** (dict) - Optional - Custom client request properties ### Request Example ```json { "command": ".show tables", "cluster_uri": "https://help.kusto.windows.net", "database": "Samples" } ``` ### Response #### Success Response (200) - **result** (dict) - Command result (format depends on command type, tabular for `.show` commands) ### Response Example ```json { "result": { "columns": [...], "rows": [...] } } ``` ``` -------------------------------- ### Set Up Alerts with Activator Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/index.md Configure and create an alert trigger using the Activator tool. This involves specifying Kusto query details, alert recipients, and message content. Ensure the Activator SDK is imported. ```python trigger = activator_create_trigger( workspace_id, trigger_name="Alert", kql_cluster_url="https://...", kql_database="...", kql_query="...", alert_recipient="email@example.com", alert_headline="Alert Title", alert_message="Alert message" ) # Open trigger['url'] in Fabric UI ``` -------------------------------- ### Health Endpoint Response Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/configuration.md Example JSON response from the /health endpoint. Indicates the server status and operational times. ```json { "status": "healthy", "current_time_utc": "2024-01-15 14:30:00 UTC", "server": "fabric-rti-mcp", "start_time_utc": "2024-01-15 10:00:00 UTC" } ``` -------------------------------- ### Kusto Entity Name Escaping Example Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Demonstrates safe escaping of Kusto entity names using the kql_escape_entity_name function. ```python def kql_escape_entity_name(name: str) -> str: pass kql_escape_entity_name("MyTable") # → "['MyTable']" kql_escape_entity_name("['MyTable']") # → "['MyTable']" kql_escape_entity_name("My-Table") # → "['My-Table']" kql_escape_entity_name("My['Table']") # → ValueError! ``` -------------------------------- ### Create Shots Table Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/recipes/KustoPrivateShotsNotebook.ipynb This commented-out KQL command can be used to create the 'shots' table with a recommended minimal schema. Uncomment and run it within your notebook to create the table. ```python # %kql .create table {SHOTS_TABLE} (Timestamp:datetime, NaturalLanguage:string, Query:string, EmbeddingVector:dynamic, Author:string, Tags:dynamic) ``` -------------------------------- ### Get Azure Credential Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Retrieves an Azure credential provider using the DefaultAzureCredential chain. Use this when initializing Azure SDK clients. ```python from fabric_rti_mcp.auth.auth_context import get_credential credential = get_credential() # Use with Azure SDK clients ``` -------------------------------- ### Recommended Kusto Configuration Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/README.md Set environment variables for Kusto service URI and default database. These are recommended for optimal performance and connectivity. ```bash export KUSTO_SERVICE_URI=https://your-cluster.kusto.windows.net export KUSTO_SERVICE_DEFAULT_DB=YourDatabase ``` -------------------------------- ### Sample KQL Queries for Fabric RTI MCP Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/recipes/KustoPrivateShotsNotebook.ipynb A collection of sample KQL queries formatted as a Python string. These queries cover various data analysis tasks and are intended for use with Fabric RTI MCP and Kusto Copilot. ```kql ```StormEvents | where EventType has "Thunderstorm" | summarize count() by bin(StartTime, 7d)``` ``` ```kql ```StormEvents | join kind = inner (PopulationData | top 1 by Population desc) on State | distinct Source | count``` ``` ```kql ```US_States | project State=features.properties.NAME, Area=geo_polygon_area(features.geometry) | top 2 by Area desc | summarize arg_min(Area, *)``` ``` ```kql ```StormEvents | summarize countEvents=count() by State | join kind=inner ( PopulationData ) on State | order by countEvents desc | project State, Population | take 1``` ``` ```kql ```StormEvents | where State endswith "o" | partition by State ( summarize TotalDeaths = sum(DeathsDirect + DeathsIndirect) by EventType, State | top 3 by TotalDeaths | where TotalDeaths > 0 )``` ``` -------------------------------- ### Retrieve a Map item's definition Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/activator-map-tools.md Use `map_get_definition` to get the complete JSON definition, including datasources and layers, for a specific Map item. ```python def map_get_definition(workspace_id: str, item_id: str) -> dict[str, Any]: ... definition = map_get_definition( "550e8400-e29b-41d4-a716-446655440000", "660e8400-e29b-41d4-a716-446655440001" ) ``` -------------------------------- ### Connect to Database and Verify Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/recipes/KustoPrivateShotsNotebook.ipynb Use these commands to connect to your Kusto database and verify the connection by listing the first 10 tables. ```python %kql kusto://code;cluster=SHOTS_CLUSTER;database=SHOTS_DATABASE %kql .show tables | take 10 ``` -------------------------------- ### Initialize Connection Manager Singleton Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Initializes a module-level singleton connection manager. If eager connect is configured, it attempts to connect to all known services at startup. Connections are reused for all queries. ```python _CONNECTION_MANAGER = KustoConnectionManager() if CONFIG.eager_connect: _CONNECTION_MANAGER.connect_to_all_known_services() ``` -------------------------------- ### Describe Kusto Database Schema Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-tools.md Retrieves schema information for all entities within a specified Kusto database. Use this to get an overview of tables, views, and functions. ```python def kusto_describe_database( cluster_uri: str, database: str | None, client_request_properties: dict[str, Any] | None = None, ) -> dict[str, Any]: ... schema = kusto_describe_database( "https://help.kusto.windows.net", "Samples" ) ``` -------------------------------- ### Get Kusto Connection Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Retrieves a Kusto connection for a given cluster URI using the shared connection manager. All tools use this function to obtain connections. ```python def get_kusto_connection(cluster_uri: str) -> KustoConnection: return _CONNECTION_MANAGER.get(cluster_uri) ``` -------------------------------- ### Initialize Global Configuration Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-internals.md Loads module-level configuration from environment variables once at import time. Properties like timeout, response format, and connection behavior can be configured. ```python CONFIG = KustoConfig.from_env() ``` -------------------------------- ### VS Code Integration (stdio) Configuration Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Configure VS Code for Fabric RTI MCP integration using stdio. This setup uses system-authenticated credentials. ```json { "mcp": { "servers": { "fabric-rti-mcp": { "command": "uvx", "args": ["microsoft-fabric-rti-mcp"], "env": { "FABRIC_API_BASE": "https://api.fabric.microsoft.com/v1" } } } } } ``` -------------------------------- ### Configure Kqlmagic Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/recipes/KustoPrivateShotsNotebook.ipynb Sets environment variables and reloads the Kqlmagic extension for use in the notebook. It also configures automatic DataFrame conversion. ```python %env KQLMAGIC_LOAD_MODE=silent # %env KQLMAGIC_LOG_LEVEL=DEBUG %reload_ext Kqlmagic %config Kqlmagic.auto_dataframe = True ``` -------------------------------- ### get_credential() Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Retrieves an Azure Identity credential provider. It uses a chain of default credentials, starting from environment variables and progressing through various Azure authentication methods. ```APIDOC ## get_credential() ### Description Returns the appropriate credential provider using Azure Identity's `DefaultAzureCredential` chain. This function simplifies obtaining credentials for Azure services. ### Function Signature ```python def get_credential() -> AsyncTokenCredential | TokenCredential ``` ### Credential Chain 1. Environment Variables (`AZURE_CLIENT_ID` + `AZURE_CLIENT_SECRET` or `AZURE_CLIENT_ID` + `AZURE_CLIENT_CERTIFICATE_PATH`) 2. Visual Studio (`VisualStudioCredential`) 3. Azure CLI (`AzureCliCredential`) 4. Azure PowerShell (`AzurePowerShellCredential`) 5. Azure Developer CLI (`AzureDeveloperCliCredential`) 6. Interactive Browser (`InteractiveBrowserCredential`) ### Returns A credential object compatible with Azure SDK libraries. ### Usage Example ```python from fabric_rti_mcp.auth.auth_context import get_credential credential = get_credential() # Use with Azure SDK clients ``` ``` -------------------------------- ### Configure Service Principal Credentials via Environment Variables Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Sets up authentication for a service principal by exporting Azure tenant ID, client ID, and client secret as environment variables. This is a common method for non-interactive authentication. ```bash # Service Principal (Client Credential) export AZURE_TENANT_ID=72f988bf-86f1-41af-91ab-2d7cd011db47 export AZURE_CLIENT_ID=client-id-here export AZURE_CLIENT_SECRET=client-secret-here ``` -------------------------------- ### Create Eventstream (Simple and Interactive) Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/index.md Create an Eventstream either as a simple one-shot operation or using an interactive builder for more complex definitions. Ensure the Eventstream SDK is imported. ```python # Simple one-shot created = eventstream_create(workspace_id, "MyStream") # Or interactive builder session = eventstream_start_definition("MyStream") eventstream_add_sample_data_source(session['session_id'], "Bicycles") eventstream_add_eventhouse_destination(session['session_id'], database="MyDb", table="Events") eventstream_create_from_definition(session['session_id'], workspace_id) ``` -------------------------------- ### Add Authentication Middleware to FastMCP Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Integrates authentication middleware into a FastMCP server instance to handle Bearer tokens and OBO token exchange. This should be called during server setup. ```python from mcp.server.fastmcp import FastMCP from fabric_rti_mcp.auth.auth_middleware import add_auth_middleware mcp = FastMCP("my-server") add_auth_middleware(mcp) # Enable auth for all requests ``` -------------------------------- ### Execute Kusto Management Command Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-tools.md Executes a Kusto management command (DDL/DCL) on a specified cluster and database. Commands must start with a dot (e.g., '.show tables'). ```python @destructive_operation def kusto_command( command: str, cluster_uri: str, database: str | None = None, client_request_properties: dict[str, Any] | None = None, ) -> dict[str, Any] result = kusto_command( ".show tables", "https://help.kusto.windows.net", database="Samples" ) ``` -------------------------------- ### Kusto Connection Initialization Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/types.md Manages connection to a Kusto cluster, setting the cluster URI and a default database. Handles authentication via DefaultAzureCredential. ```python class KustoConnection: def __init__( self, cluster_uri: str, default_database: str = "NetDefaultDB" ) -> None: ... ``` -------------------------------- ### Configure Kusto Alerts with Meaningful Thresholds Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/patterns-best-practices.md Illustrates the difference between a bad alert configuration that fires on every data point and a good configuration that uses a threshold to alert only on meaningful events. This reduces alert noise and focuses on actionable issues. ```python # Bad: Alerts on every error trigger = activator_create_trigger( workspace_id, trigger_name="AnyError", kql_cluster_url=cluster_uri, kql_database="MyDb", kql_query="Errors | count", # ← This fires on ANY data ... ) # Good: Alert on meaningful threshold trigger = activator_create_trigger( workspace_id, trigger_name="HighErrorRate", kql_cluster_url=cluster_uri, kql_database="MyDb", kql_query=""" Errors | where Timestamp > ago(5m) | summarize ErrorCount = count() | where ErrorCount > 100 // ← Only alert if > 100 """, kql_polling_frequency_minutes=5, ... ) ``` -------------------------------- ### Get Current Eventstream Definition from Session Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/eventstream-tools.md Retrieves the current definition within an active builder session using the session ID. Returns the session details including the definition. ```python def eventstream_get_current_definition(session_id: str) -> dict[str, Any]: pass current = eventstream_get_current_definition(session_id) ``` -------------------------------- ### eventstream_start_definition() Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/eventstream-tools.md Initiates a new Eventstream builder session, requiring a name and optionally accepting a description. Returns session details including a session ID. ```APIDOC ## eventstream_start_definition() ### Description Starts a new Eventstream builder session. ### Method Not applicable (Python function) ### Parameters #### Path Parameters - **name** (str) - Yes - Name of the eventstream to create - **description** (str | None) - No - Optional description ### Response #### Success Response - **dict[str, Any]** - Session details including session_id, name, description, status, and next_steps. ```json { "session_id": "uuid", "name": "string", "description": "string|null", "status": "ready", "next_steps": [...] } ``` ### Request Example ```python session = eventstream_start_definition( "My_Data_Stream", "Processing IoT sensor data" ) session_id = session['session_id'] ``` ``` -------------------------------- ### List Eventstreams in a workspace Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/eventstream-tools.md Use `eventstream_list` to get a list of all Eventstream items within a given workspace. The function filters results to include only items of type "Eventstream". ```python def eventstream_list(workspace_id: str) -> list[dict[str, Any]]: ... streams = eventstream_list("550e8400-e29b-41d4-a716-446655440000") # Returns: [{"id": "...", "displayName": "...", "type": "Eventstream", ...}, ...] ``` -------------------------------- ### Environment Variable for Kusto Eager Connect Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/README.md Controls whether to eagerly connect to the default Kusto service on startup. Setting this to 'true' is not recommended. ```plaintext KUSTO_EAGER_CONNECT=true ``` -------------------------------- ### kusto_show_queryplan() Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/kusto-tools.md Retrieves the query execution plan for a given KQL query without actually executing it. This is useful for estimating query costs before running expensive queries. It returns a dictionary containing the query text, planning statistics, the logical operator tree, and any execution hints or semantic errors. ```APIDOC ## kusto_show_queryplan() ### Description Retrieves the query execution plan without executing the query. Useful for estimating cost before running expensive queries. ### Method Signature ```python def kusto_show_queryplan( query: str, cluster_uri: str, database: str | None = None, client_request_properties: dict[str, Any] | None = None, ) -> dict[str, Any] ``` ### Parameters #### Path Parameters - **query** (str) - Required - KQL query to analyze - **cluster_uri** (str) - Required - Cluster URI - **database** (str) - Optional - Database name (defaults to the cluster's default database) - **client_request_properties** (dict) - Optional - Custom client request properties ### Returns - `dict[str, Any]` - A dictionary containing: - `query_text` (str) - Query as received - `stats` (dict) - Planning statistics (Duration, PlanSize, RelopSize in bytes) - `relop_tree` (dict) - Logical operator tree (JSON) - `execution_hints` (dict) - Extracted from physical plan (e.g., estimated_rows, concurrency) - `error` (str) - Semantic errors (e.g., bad column name) ### Example ```python plan = kusto_show_queryplan( "StormEvents | where State == 'IL' | summarize count()", "https://help.kusto.windows.net", "Samples" ) # Returns: {"query_text": "...", "stats": {...}, "relop_tree": {...}, "execution_hints": {...}} ``` ``` -------------------------------- ### Get Cached FabricHttpClient Instance Source: https://github.com/microsoft/fabric-rti-mcp/blob/main/_autodocs/authentication-modules.md Demonstrates how to obtain a cached instance of FabricHttpClient using FabricHttpClientCache. This ensures a single, thread-safe instance is reused across the process, optimizing connection pooling and credential management. ```python from fabric_rti_mcp.fabric_api_http_client import FabricHttpClientCache client = FabricHttpClientCache.get_client() result = client.make_request("GET", "/workspaces") ```