### Example: Describe Table Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/tools.md Demonstrates how to call the describe_table tool using the MCP client to get schema details for a specific table. ```python # Via MCP client tool_result = await client.call_tool( "describe_table", {"table_name": "MY_DB.PUBLIC.CUSTOMERS"} ) # Response example: # database: MY_DB # schema: PUBLIC # table: CUSTOMERS # data: # - COLUMN_NAME: ID # DATA_TYPE: NUMBER # IS_NULLABLE: 'N' # COMMENT: Primary key # - COLUMN_NAME: NAME # DATA_TYPE: VARCHAR # IS_NULLABLE: 'N' # COMMENT: Customer name ``` -------------------------------- ### Copy Environment Example to .env Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/CONTRIBUTING.md Copies the example environment file to .env for local configuration. Do not quote values or use inline comments in .env files. ```bash cp .env.example .env ``` -------------------------------- ### Install Development Dependencies and Git Hooks Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/CONTRIBUTING.md Installs JavaScript tooling with bun, syncs Python dependencies with uv, and installs prek Git hooks. Reinstall hooks later with 'make hooks'. ```bash make install ``` -------------------------------- ### Logging Configuration Examples Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Demonstrates how to configure logging levels and output destinations for the mcp_snowflake_server command. ```bash # Log to stderr only mcp_snowflake_server --log_level DEBUG ``` ```bash # Log to stderr + file mcp_snowflake_server --log_level INFO --log_dir /var/log/mcp # File location: /var/log/mcp/mcp_snowflake_server.log ``` -------------------------------- ### Key-Pair Authentication Connection Configuration Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/types.md Demonstrates the `ConnectionConfig` setup for key-pair authentication using JWT, specifying the private key file path and its passphrase. ```python keypair_config: ConnectionConfig = { "account": "xy12345", "user": "user@example.com", "authenticator": "snowflake_jwt", "private_key_file": "/path/to/key.p8", "private_key_file_pwd": "key_passphrase", "warehouse": "COMPUTE_WH", "database": "PRODUCTION", "schema": "PUBLIC" } ``` -------------------------------- ### main Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/initialization.md Starts the async event loop for the MCP Snowflake Server with specified configuration. ```APIDOC ## main ### Description Starts the async event loop and runs the MCP Snowflake Server until shutdown. Allows configuration of various server behaviors including write access, connection details, logging, and tool prefetching. ### Method `main` (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **allow_write** (bool) - Optional - Enable write_query and create_table tools. Defaults to False. * **connection_args** (dict[str, Any] | None) - Optional - Snowflake connection configuration. Defaults to None. * **log_dir** (str | None) - Optional - Directory for log file output. Defaults to None. * **prefetch** (bool) - Optional - Pre-load table schema as context://table/* resources. Defaults to False. * **log_level** (str) - Optional - Logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL. Defaults to "INFO". * **exclude_tools** (list[str] | None) - Optional - List of tool names to exclude. Defaults to None. * **config_file** (str) - Optional - Path to runtime config file with exclusion patterns. Defaults to "runtime_config.json". * **exclude_patterns** (dict[str, list[str]] | None) - Optional - Exclusion patterns for databases, schemas, tables. Defaults to None. * **exclude_json_results** (bool) - Optional - Omit embedded JSON from tool responses. Defaults to False. ### Request Example ```python import asyncio from mcp_snowflake_server.server import main connection_config = { 'account': 'myaccount', 'user': 'user@example.com', 'password': 'secret', 'warehouse': 'COMPUTE_WH', 'database': 'MY_DB', 'schema': 'PUBLIC' } asyncio.run(main( allow_write=False, connection_args=connection_config, log_level='INFO', prefetch=False )) ``` ### Response #### Success Response (None) Returns `None`. Starts the async event loop and runs until the server shuts down. #### Response Example None ``` -------------------------------- ### Example Tool Instantiation Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/types.md Illustrates how to instantiate the Tool Pydantic model with specific parameters for a 'read_query' tool. ```python Tool( name="read_query", description="Execute a SELECT query.", input_schema={ "type": "object", "properties": { "query": { "type": "string", "description": "SELECT SQL query to execute" } }, "required": ["query"], }, handler=handle_read_query, tags=[] ) ``` -------------------------------- ### Async Server Startup Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/MANIFEST.txt Starts the MCP server asynchronously. This is the main entry point for running the server. ```python import asyncio from mcp.api.initialization import server async def main(): await server.main() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Bash Invocation Examples Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/initialization.md Examples of how to invoke the mcp-snowflake-server via different methods, including uvx, Docker, with TOML configuration, and with individual parameters. ```bash # Via uvx uvx --python=3.13 --from mcp-snowflake-server-nsp mcp_snowflake_server ``` ```bash # Via Docker docker run --rm -i nsphung/mcp-snowflake-server-nsp ``` ```bash # With TOML configuration mcp_snowflake_server --connections-file /path/to/snowflake_connections.toml --connection-name production ``` ```bash # With individual parameters mcp_snowflake_server --account myaccount --user myuser --password mypassword --warehouse WH --database DB --schema SCHEMA --role ROLE ``` -------------------------------- ### Example TOML Configuration for Key-Pair Authentication Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md A complete TOML configuration example demonstrating key-pair authentication, including account, user, private key file path, passphrase, and other connection details. ```toml [development] account = "xy12345" user = "user@example.com" authenticator = "snowflake_jwt" private_key_file = "/home/user/.ssh/snowflake_key.p8" private_key_file_pwd = "passphrase" warehouse = "DEV_WH" database = "DEV_DB" schema = "PUBLIC" role = "DEVELOPER" ``` -------------------------------- ### Complete uvx Command Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md A comprehensive example of the uvx command invoking mcp-snowflake-server with various configuration options, including connection details, write permissions, prefetching, logging, and exclusions. ```bash uvx --python=3.13 --from mcp-snowflake-server-nsp mcp_snowflake_server \ --connections-file /path/to/snowflake_connections.toml \ --connection-name production \ --allow_write \ --prefetch \ --log_level INFO \ --log_dir /var/log/mcp-snowflake-server \ --exclude_tools list_databases \ --exclude-json-results ``` -------------------------------- ### Runtime Configuration JSON Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Example runtime_config.json file demonstrating exclusion patterns for databases, schemas, and tables. Patterns are matched case-insensitively as substrings. ```json { "exclude_patterns": { "databases": ["information_schema", "snowflake", "temp"], "schemas": ["information_schema", "temp", "staging"], "tables": ["temp", "backup", "archive", "_tmp"] } } ``` -------------------------------- ### main() Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/initialization.md The main entry point for the mcp-snowflake-server package. Initializes the MCP server with Snowflake connection and starts the stdio transport. ```APIDOC ## main() ### Description The main entry point for the mcp-snowflake-server package. Initializes the MCP server with Snowflake connection and starts the stdio transport. This function serves as the CLI entry point. It: - Loads environment variables from `.env` file - Parses command-line arguments - Validates connection configuration - Initializes the MCP server with Snowflake connection - Runs the event loop to start the server ### Invocation ```bash # Via uvx uvx --python=3.13 --from mcp-snowflake-server-nsp mcp_snowflake_server # Via Docker docker run --rm -i nsphung/mcp-snowflake-server-nsp # With TOML configuration mcp_snowflake_server --connections-file /path/to/snowflake_connections.toml --connection-name production # With individual parameters mcp_snowflake_server --account myaccount --user myuser --password mypassword --warehouse WH --database DB --schema SCHEMA --role ROLE ``` ### Parameters No direct parameters. Configuration comes from: - Command-line arguments (see [Configuration Reference](../configuration.md)) - Environment variables (SNOWFLAKE_* prefixed) - TOML configuration file (via --connections-file and --connection-name) ### Errors | Error Type | |---| | `FileNotFoundError` | TOML connections file does not exist | | `KeyError` | Connection name not found in TOML file | | `ValueError` | Invalid TOML file, missing required connection parameters, or both --connections-file and --connection-name must be provided together | ### Example Usage ```python # Start the server with environment variables set import os os.environ['SNOWFLAKE_ACCOUNT'] = 'myaccount' os.environ['SNOWFLAKE_USER'] = 'user@example.com' os.environ['SNOWFLAKE_PASSWORD'] = 'secret' os.environ['SNOWFLAKE_DATABASE'] = 'MY_DB' os.environ['SNOWFLAKE_SCHEMA'] = 'PUBLIC' from mcp_snowflake_server import main main() # Starts the MCP server ``` ``` -------------------------------- ### Example Output for List Resources Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/resources.md This example shows the expected JSON output from the list_resources endpoint, including both the insights memo and dynamically generated table resources. ```python [ Resource( uri=AnyUrl("memo://insights"), name="Data Insights Memo", description="A living document of discovered data insights", mimeType="text/plain" ), Resource( uri=AnyUrl("context://table/CUSTOMERS"), name="CUSTOMERS table", description="Description of the CUSTOMERS table", mimeType="text/plain" ), Resource( uri=AnyUrl("context://table/ORDERS"), name="ORDERS table", description="Description of the ORDERS table", mimeType="text/plain" ), Resource( uri=AnyUrl("context://table/PRODUCTS"), name="PRODUCTS table", description="Description of the PRODUCTS table", mimeType="text/plain" ) ] ``` -------------------------------- ### TOML File Format Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/initialization.md Example structure for a TOML configuration file used to define Snowflake connection parameters. ```toml [production] account = "your_account" user = "your_user" password = "your_password" authenticator = "snowflake" warehouse = "COMPUTE_WH" database = "PROD_DB" schema = "PUBLIC" role = "ACCOUNTADMIN" [development] account = "your_account" user = "dev_user" authenticator = "externalbrowser" warehouse = "DEV_WH" database = "DEV_DB" schema = "PUBLIC" role = "DEVELOPER" ``` -------------------------------- ### Configure MCP Snowflake Server with Command-Line Arguments Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Example of launching the MCP Snowflake Server by providing all connection details as command-line arguments. ```bash mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password secret \ --warehouse COMPUTE_WH \ --database PROD_DB \ --schema PUBLIC \ --role ACCOUNTADMIN ``` -------------------------------- ### Example Exclusion Configuration JSON Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/types.md Provides an example of an exclusion configuration in JSON format, detailing patterns for excluding databases, schemas, and tables. ```json { "exclude_patterns": { "databases": ["information_schema", "snowflake", "temp"], "schemas": ["information_schema", "temp", "staging"], "tables": ["temp", "backup", "archive"] } } ``` -------------------------------- ### TOML Connection Profile Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Example TOML file structure for defining Snowflake connection profiles, including production and staging configurations. ```toml [production] account = "xy12345" user = "prod_user@example.com" password = "prod_password" warehouse = "PROD_WH" database = "PROD_DB" schema = "PUBLIC" role = "ACCOUNTADMIN" [staging] account = "xy12345" user = "staging_user@example.com" password = "staging_password" warehouse = "STAGING_WH" database = "STAGING_DB" schema = "PUBLIC" role = "ANALYST" ``` -------------------------------- ### Example: Testing Snowflake Connection with Basic Parameters Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Use this command to test connection parameters with a simpler configuration, useful for debugging. ```bash mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password "secret" \ --database "INFORMATION_SCHEMA" \ --schema "PUBLIC" ``` -------------------------------- ### Background Initialization Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/MANIFEST.txt Starts the Snowflake connection initialization in the background. This allows the server to start serving requests while the connection is being established. ```python from mcp.api.snowflake_db import SnowflakeDB snowflake_db = SnowflakeDB(connection_config) init_task = asyncio.create_task(snowflake_db.start_init_connection()) # The server can now start accepting requests # await init_task # Optionally wait for initialization to complete ``` -------------------------------- ### Initialize and Execute Query with SnowflakeDB Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Demonstrates initializing the SnowflakeDB client and executing a SQL query. The initialization can start in the background. ```python db = SnowflakeDB(connection_config) # Start initialization in background init_task = db.start_init_connection() # Execute SQL query (awaits init if needed) rows, data_id = await db.execute_query("SELECT * FROM table") # Manage insights db.add_insight("Revenue up 15%") memo = db.get_memo() # Returns formatted memo ``` -------------------------------- ### Basic MCP Snowflake Server Configuration with Environment Variables Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/README.md Sets up essential Snowflake connection parameters using environment variables and runs the MCP Snowflake Server. This is a quick start method. ```bash export SNOWFLAKE_ACCOUNT=xy12345 export SNOWFLAKE_USER=user@example.com export SNOWFLAKE_PASSWORD=secret export SNOWFLAKE_DATABASE=PROD_DB export SNOWFLAKE_SCHEMA=PUBLIC mcp_snowflake_server ``` -------------------------------- ### TOML Connection File Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/README.md Example TOML file for managing multiple connection environments. ```toml [production] account = "your_account" user = "your_user" password = "your_password" authenticator = "snowflake" warehouse = "COMPUTE_WH" database = "PROD_DB" schema = "PUBLIC" role = "ACCOUNTADMIN" [development] account = "your_account" user = "dev_user" authenticator = "externalbrowser" warehouse = "DEV_WH" database = "DEV_DB" schema = "PUBLIC" role = "DEVELOPER" [reporting] account = "your_account" user = "reporting_user" authenticator = "snowflake_jwt" private_key_file = "/path/to/private_key.pem" private_key_file_pwd = "passphrase" # Optional warehouse = "REPORTING_WH" database = "REPORTING_DB" schema = "REPORTS" role = "REPORTING_ROLE" [analytics_oauth] account = "your_account" authenticator = "oauth_client_credentials" oauth_client_id = "your_client_id" oauth_client_secret = "your_client_secret" oauth_token_request_url = "https://your-idp.example.com/oauth/token" oauth_scope = "session:role:ANALYTICS_ROLE" # Optional warehouse = "ANALYTICS_WH" database = "ANALYTICS_DB" schema = "PUBLIC" role = "ANALYTICS_ROLE" ``` -------------------------------- ### Initialize Snowflake Server Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/initialization.md Starts the async event loop for the Snowflake server. Configure connection details, logging, and write permissions as needed. ```python import asyncio from mcp_snowflake_server.server import main connection_config = { 'account': 'myaccount', 'user': 'user@example.com', 'password': 'secret', 'warehouse': 'COMPUTE_WH', 'database': 'MY_DB', 'schema': 'PUBLIC' } asyncio.run(main( allow_write=False, connection_args=connection_config, log_level='INFO', prefetch=False )) ``` -------------------------------- ### Basic Snowflake Connection Configuration Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/types.md Illustrates a typical `ConnectionConfig` dictionary for establishing a standard Snowflake connection using username and password authentication. ```python config: ConnectionConfig = { "account": "xy12345", "user": "user@example.com", "password": "secret", "authenticator": "snowflake", "warehouse": "COMPUTE_WH", "database": "PRODUCTION", "schema": "PUBLIC", "role": "ANALYTICS" } db = SnowflakeDB(config) ``` -------------------------------- ### Example ResponseType Usage Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/types.md Provides an example of creating a list of ResponseType objects, including TextContent and EmbeddedResource with different content types. ```python from mcp import types from pydantic import AnyUrl responses: list[ResponseType] = [ types.TextContent( type="text", text="yaml formatted output" ), types.EmbeddedResource( type="resource", resource=types.TextResourceContents( uri=AnyUrl("data://abc123"), text="json formatted output", mimeType="application/json" ) ) ] ``` -------------------------------- ### Handling Unknown Resources Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Provides examples of how to list available resources and read them correctly. It also shows incorrect attempts to read non-existent resources. ```python # List available resources resources = await client.list_resources() # Read only available resources for resource in resources: content = await client.read_resource(resource.uri) # Wrong: non-existent resource await client.read_resource("unknown://resource") # Correct: available resources await client.read_resource("memo://insights") # Correct: table resource (only if --prefetch enabled) await client.read_resource("context://table/CUSTOMERS") ``` -------------------------------- ### Initialization Entry Points Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/MANIFEST.txt Details the main entry points for initializing and running the mcp-snowflake-server, including functions for starting the server, loading configurations, and parsing command-line arguments. ```APIDOC ## Initialization ### Description Provides the primary functions to start and configure the mcp-snowflake-server. ### Functions - **main()**: The main entry point for the server application. - **server.main()**: An alternative entry point for the server. - **load_connection_from_toml()**: Loads Snowflake connection configuration from a TOML file. - **parse_args()**: Parses command-line arguments for server configuration. ``` -------------------------------- ### Call create_table Tool Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/tools.md Use the `call_tool` method to create a new table. Requires the server to be started with the `--allow_write` flag and the query must start with 'CREATE TABLE'. ```python # Via MCP client (only if server started with --allow_write) tool_result = await client.call_tool( "create_table", { "query": """ CREATE TABLE analytics_summary ( date DATE NOT NULL, region VARCHAR NOT NULL, revenue DECIMAL(12,2), customer_count INTEGER, PRIMARY KEY (date, region) ) """ } ) # Response example: # TextContent(text="Table created successfully. data_id = 12345...") ``` -------------------------------- ### Example: Query Validation with SQLWriteDetector Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/write-detector.md Provides a practical example of using SQLWriteDetector to analyze various SQL queries and identify whether they are read-only or contain write operations. It prints the status and detected operations for each query. ```python from mcp_snowflake_server.write_detector import SQLWriteDetector detector = SQLWriteDetector() queries_to_test = [ "SELECT COUNT(*) FROM users", # Safe "SELECT * FROM users WHERE id IN (SELECT user_id FROM orders)", # Safe "INSERT INTO audit_log VALUES (...)", # Write "DELETE FROM temp_data", # Write "CREATE TEMP TABLE staging AS SELECT * FROM users", # Write "ALTER TABLE users ADD COLUMN created_at TIMESTAMP", # Write "WITH recent_users AS (SELECT * FROM users WHERE created_at > NOW()) SELECT * FROM recent_users", # Safe ] for query in queries_to_test: result = detector.analyze_query(query) status = "✗ WRITE" if result['contains_write'] else "✓ READ ONLY" ops = ", ".join(result['write_operations']) if result['write_operations'] else "none" print(f"{status:12} | Operations: {ops:20} | {query[:50]}") # Output: # ✓ READ ONLY | Operations: none | SELECT COUNT(*) FROM users # ✓ READ ONLY | Operations: none | SELECT * FROM users WHERE id IN (SE # ✗ WRITE | Operations: INSERT | INSERT INTO audit_log VALUES (...) # ✗ WRITE | Operations: DELETE | DELETE FROM temp_data # ✗ WRITE | Operations: CREATE | CREATE TEMP TABLE staging AS SELECT # ✗ WRITE | Operations: ALTER | ALTER TABLE users ADD COLUMN create # ✓ READ ONLY | Operations: none | WITH recent_users AS (SELECT * FROM ``` -------------------------------- ### Example: Correct Usage of read_query and write_query Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Demonstrates the correct way to use `read_query` for SELECT statements and `write_query` for data modification operations. ```python # Wrong: write query in read_query await client.call_tool("read_query", { "query": "INSERT INTO table VALUES (...)" }) # Correct: use write_query for writes (requires --allow_write) await client.call_tool("write_query", { "query": "INSERT INTO table VALUES (...)" }) # Correct: use read_query for SELECT only await client.call_tool("read_query", { "query": "SELECT * FROM table" }) ``` -------------------------------- ### Configure MCP Snowflake Server with TOML File Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Example of launching the MCP Snowflake Server using a TOML configuration file for connection details. ```bash mcp_snowflake_server \ --connections-file /path/to/config.toml \ --connection-name production ``` -------------------------------- ### SnowflakeDB `start_init_connection` Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/snowflake-db.md Starts the database initialization process in the background. This method returns immediately, allowing other operations to proceed while the connection is established asynchronously. ```APIDOC ## SnowflakeDB `start_init_connection` ### Description Start database initialization in the background. Returns immediately without blocking. This method schedules the async _init_database() coroutine to run in the background. The actual connection establishment happens asynchronously without blocking the caller. The first query execution will wait for this task to complete if it hasn't already. ### Method None (This is a Python method call) ### Endpoint None ### Parameters None ### Request Example ```python db = SnowflakeDB(config) # Start connection in background init_task = db.start_init_connection() # Continue with other work; connection happens asynchronously # First query will wait for init_task to complete result = await db.execute_query("SELECT 1") ``` ### Response #### Success Response (200) `asyncio.Task[None]` — Task object for the background initialization. Can be awaited to wait for completion. #### Response Example None ### Errors #### Error Type `ValueError` #### Condition Connection fails due to invalid credentials or network issues (raised when task is awaited) ``` -------------------------------- ### OAuth Client Credentials Connection Configuration Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/types.md Shows how to configure `ConnectionConfig` for OAuth client credentials authentication, including necessary OAuth-specific parameters. ```python oauth_config: ConnectionConfig = { "account": "xy12345", "authenticator": "oauth_client_credentials", "oauth_client_id": "my_client_id", "oauth_client_secret": "my_client_secret", "oauth_token_request_url": "https://idp.example.com/oauth/token", "oauth_scope": "session:role:MY_ROLE", "warehouse": "COMPUTE_WH", "database": "PRODUCTION", "schema": "PUBLIC" } ``` -------------------------------- ### Example of Correct and Incorrect Tool Calls Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Illustrates the proper usage of read_query for SELECT statements and write_query for data modification or other DDL. Also shows correct usage of create_table. ```python # Wrong: SELECT in write_query await client.call_tool("write_query", { "query": "SELECT * FROM users" }) # Correct: SELECT in read_query await client.call_tool("read_query", { "query": "SELECT * FROM users" }) # Correct: INSERT/UPDATE/DELETE in write_query await client.call_tool("write_query", { "query": "UPDATE users SET status = 'active' WHERE id = 1" }) ``` ```python # Wrong: INSERT in create_table await client.call_tool("create_table", { "query": "INSERT INTO users VALUES (...)" }) # Correct: CREATE TABLE in create_table await client.call_tool("create_table", { "query": """ CREATE TABLE users ( id INTEGER, name VARCHAR, email VARCHAR ) """ }) # Wrong: CREATE VIEW in create_table await client.call_tool("create_table", { "query": "CREATE VIEW user_summary AS SELECT COUNT(*) FROM users" }) # Correct: use write_query for other DDL await client.call_tool("write_query", { "query": "CREATE VIEW user_summary AS SELECT COUNT(*) FROM users" }) ``` -------------------------------- ### Example: Verifying SSH Key for Key-Pair Authentication Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Verify that your SSH key file exists, is readable, and is correctly formatted when using key-pair authentication. ```bash ls -la ~/.ssh/snowflake_key.p8 openssl pkey -in ~/.ssh/snowflake_key.p8 -text -noout ``` -------------------------------- ### SnowflakeDB Query Execution Example Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/types.md Shows basic usage of the `SnowflakeDB` client to execute a query and retrieve results, demonstrating the context for `SnowflakeValue`. ```python from mcp_snowflake_server.db_client import SnowflakeDB, SnowflakeValue from typing import cast db = SnowflakeDB(config) rows, data_id = await db.execute_query("SELECT * FROM CUSTOMERS LIMIT 5") ``` -------------------------------- ### Example: Read Query Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/tools.md Shows how to use the read_query tool via the MCP client to fetch data based on a SQL SELECT statement. The query is validated to ensure it's read-only. ```python # Via MCP client tool_result = await client.call_tool( "read_query", {"query": "SELECT id, name, revenue FROM customers WHERE revenue > 10000 ORDER BY revenue DESC LIMIT 5"} ) # Response example: # type: data # data_id: f47ac10b-58cc-4372-a567-0e02b2c3d479 # data: # - ID: 101 # NAME: Acme Corp # REVENUE: 50000 # - ID: 102 # NAME: TechCorp # REVENUE: 30000 ``` -------------------------------- ### Example: Enabling Write Operations Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Include the `--allow_write` flag in your command to permit write operations like INSERT, UPDATE, or DELETE. ```bash mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password secret \ --database DB \ --schema PUBLIC \ --allow_write # Or use read_query for SELECT-only operations (always allowed) ``` -------------------------------- ### Quick Start with UVX and TOML Connection File Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/README.md This snippet shows how to set up a TOML connection file and run the Snowflake MCP Server using uvx. ```bash # 1. Create a connections file cat > ~/snowflake_connections.toml << 'EOF' [myconn] account = "your_account" user = "your_user" password = "your_password" warehouse = "COMPUTE_WH" database = "MY_DB" schema = "PUBLIC" role = "MYROLE" EOF # 2. Run the server uvx --python=3.13 --from mcp-snowflake-server-nsp mcp_snowflake_server \ --connections-file ~/snowflake_connections.toml \ --connection-name myconn ``` -------------------------------- ### Password Authentication Configuration via TOML Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Example TOML configuration for password-based authentication. This requires account, user, password, database, and schema parameters. ```toml [production] account = "xy12345" user = "user@example.com" password = "your_password" authenticator = "snowflake" warehouse = "COMPUTE_WH" database = "PROD_DB" schema = "PUBLIC" role = "ACCOUNTADMIN" ``` -------------------------------- ### Managing Excluded Tools in MCP Snowflake Server Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Shows how to list excluded tools using the help command and how to start the server without excluding specific tools or by removing them from the exclusion list. ```bash # List excluded tools mcp_snowflake_server --help | grep exclude_tools # Start server without excluding tool mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password secret \ --database DB \ --schema PUBLIC # No --exclude_tools # Or remove tool from exclusion list mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password secret \ --database DB \ --schema PUBLIC \ --exclude_tools other_tool1 other_tool2 # Don't exclude list_databases ``` -------------------------------- ### Python Main Entry Point Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/initialization.md The main entry point for the package, responsible for initializing the server with Snowflake connection and starting the stdio transport. It loads environment variables, parses arguments, validates configuration, and runs the event loop. ```python def main() -> None: """Main entry point for the package.""" ``` ```python # Start the server with environment variables set import os os.environ['SNOWFLAKE_ACCOUNT'] = 'myaccount' os.environ['SNOWFLAKE_USER'] = 'user@example.com' os.environ['SNOWFLAKE_PASSWORD'] = 'secret' os.environ['SNOWFLAKE_DATABASE'] = 'MY_DB' os.environ['SNOWFLAKE_SCHEMA'] = 'PUBLIC' from mcp_snowflake_server import main main() # Starts the MCP server ``` -------------------------------- ### Parse Arguments for MCP Snowflake Server Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/initialization.md Parses command-line arguments to obtain server and connection configurations. Use this to start the server with custom settings. ```python from mcp_snowflake_server import parse_args server_args, connection_args = parse_args() print(server_args) # {'allow_write': False, 'prefetch': False, ...} print(connection_args) # {'account': 'myaccount', 'user': 'user', ...} ``` -------------------------------- ### Start SnowflakeDB Connection Initialization Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/snowflake-db.md Initiate the database connection process asynchronously in the background. This method returns immediately, allowing other operations to proceed while the connection is established. The actual connection is awaited implicitly by the first query execution if not already complete. ```python db = SnowflakeDB(config) # Start connection in background init_task = db.start_init_connection() # Continue with other work; connection happens asynchronously # First query will wait for init_task to complete result = await db.execute_query("SELECT 1") ``` -------------------------------- ### Execute SQL Query using MCP Snowflake Server Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/README.md Shows how to execute a SQL query against Snowflake using the MCP Snowflake Server client. This example focuses on reading data. ```python from mcp_snowflake_server.client import MCPClient async def main(): client = MCPClient() # Read query await client.call_tool("read_query", { "query": "SELECT * FROM my_table LIMIT 10" }) ``` -------------------------------- ### CLI Entry Point: main() Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Demonstrates how to launch the mcp-snowflake-server via CLI using uvx, Docker, or direct Python execution. ```bash # Via uvx (recommended) uvx --python=3.13 --from mcp-snowflake-server-nsp mcp_snowflake_server # Via Docker docker run --rm -i nsphung/mcp-snowflake-server-nsp # Via Python (direct) python -m mcp_snowflake_server ``` -------------------------------- ### List Databases using MCP Snowflake Server Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/README.md Demonstrates how to list available databases using the MCP Snowflake Server client. Ensure the client is initialized and connected. ```python from mcp_snowflake_server.client import MCPClient async def main(): client = MCPClient() # List databases await client.call_tool("list_databases", {}) ``` -------------------------------- ### Example TOML Configuration for OAuth 2.0 Client Credentials Authentication Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md TOML configuration for OAuth 2.0 client credentials authentication. Requires account, client ID, client secret, token request URL, database, and schema. ```toml [analytics] account = "xy12345" authenticator = "oauth_client_credentials" oauth_client_id = "my_client_id" oauth_client_secret = "my_client_secret" oauth_token_request_url = "https://idp.example.com/oauth/token" oauth_scope = "session:role:ANALYTICS_ROLE" warehouse = "ANALYTICS_WH" database = "ANALYTICS_DB" schema = "PUBLIC" role = "ANALYTICS_ROLE" ``` -------------------------------- ### Example TOML Configuration for External Browser Authentication Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md TOML configuration for authenticating via an external browser. This method requires account, user, database, and schema, and will prompt the user to authenticate through their web browser. ```toml [browser_auth] account = "xy12345" user = "user@example.com" authenticator = "externalbrowser" warehouse = "DEV_WH" database = "DEV_DB" schema = "PUBLIC" role = "DEVELOPER" ``` -------------------------------- ### Run Server with UV Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/CONTRIBUTING.md Equivalent command to 'make run' for executing the server directly from source using uv. ```bash uv --directory . run mcp_snowflake_server ``` -------------------------------- ### Get Memo Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/MANIFEST.txt Retrieves data from the memoization cache using a specified key. ```python from mcp.api.snowflake_db import SnowflakeDB snowflake_db = SnowflakeDB(connection_config) insight_key = "my_insight_key" retrieved_data = await snowflake_db.get_memo(insight_key) print(retrieved_data) ``` -------------------------------- ### Describe Table Tool Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/MANIFEST.txt Uses the describe_table tool to get the schema definition of a specific table. ```python from mcp.api.tools import Tool # Assuming 'tool' is an instance of Tool # database_name = "MY_DATABASE" # schema_name = "MY_SCHEMA" # table_name = "MY_TABLE" # result = await tool.describe_table(database_name=database_name, schema_name=schema_name, table_name=table_name) print("describe_table tool executed.") ``` -------------------------------- ### Describe Table Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/README.md Use the `describe_table` tool to get the schema definition for a specific table. This is a read-only operation. ```python await client.call_tool("describe_table", { "table_name": "MY_DB.PUBLIC.USERS" }) ``` -------------------------------- ### Initialization and Configuration Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/MANIFEST.txt This section covers the entry points for initializing the MCP Snowflake Server and its various configuration methods. ```APIDOC ## Initialization and Configuration ### Description This documentation covers the primary methods for starting and configuring the MCP Snowflake Server, including CLI entry points, file-based configuration, and environment variable loading. ### Entry Points - **main()**: The main command-line interface entry point for the server. - **server.main()**: Asynchronous server startup function. ### Configuration Loading - **load_connection_from_toml()**: Loads connection and server configurations from a TOML file. - **parse_args()**: Parses command-line arguments for configuration. - **_connection_args_from_env()**: Loads connection arguments from environment variables. - **_validate_connection_args()**: Validates the provided connection arguments. ### Configuration Methods - **TOML File**: Configuration can be specified in a TOML file (e.g., `runtime_config.json`). - **Command-Line Arguments**: Server and connection parameters can be provided via CLI arguments. - **Environment Variables**: Connection parameters can be set using environment variables. ### Configuration Options Refer to `configuration.md` for a complete list of options, including: - Snowflake connection parameters (account, user, password, warehouse, database, schema, role, authenticator) - Authentication method parameters (key-pair, OAuth) - MCP server parameters (allow_write, prefetch, exclude_tools, log_level) ### Examples See `configuration.md` for comprehensive examples demonstrating TOML, CLI, and environment variable configurations. ``` -------------------------------- ### Example YAML Response Content Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Illustrates the structure of YAML-formatted TextContent in an API response, including data details. ```yaml # TextContent type: data data_id: 550e8400-e29b-41d4-a716-446655440000 database: MYDB schema: PUBLIC data: - ID: 1 NAME: Alice REVENUE: 10500.50 CREATED_AT: '2024-01-15' ``` -------------------------------- ### Logging Database and General Errors Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Examples of logging database-specific errors and general function errors using the 'mcp_snowflake_server' logger. ```python logger = logging.getLogger("mcp_snowflake_server") # Error logging logger.error(f"Database error executing '{query}': {e}") logger.error(f"Error in {func.__name__}: {str(e)}") logger.error(msg) # For validation errors ``` -------------------------------- ### Troubleshooting Connection Initialization Timeout Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/errors.md Provides recovery steps for connection initialization timeouts, including checking network connectivity, verifying credentials with snowsql, and trying with a reduced warehouse size. ```bash # Check network connectivity ping xy12345.snowflakecomputing.com # Verify credentials snowsql -a xy12345 -u user@example.com # Try with reduced warehouse mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password secret \ --warehouse COMPUTE_WH \ --database DB \ --schema PUBLIC ``` -------------------------------- ### Example JSON Embedded Resource Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Shows the JSON-formatted data for an embedded resource in an API response, mirroring the YAML content. ```json { "type": "data", "data_id": "550e8400-e29b-41d4-a716-446655440000", "database": "MYDB", "schema": "PUBLIC", "data": [ { "ID": 1, "NAME": "Alice", "REVENUE": 10500.5, "CREATED_AT": "2024-01-15" } ] } ``` -------------------------------- ### Call write_query Tool Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/tools.md Use the `call_tool` method to execute a write query. Requires the server to be started with the `--allow_write` flag. ```python # Via MCP client (only if server started with --allow_write) tool_result = await client.call_tool( "write_query", {"query": "UPDATE customers SET revenue = revenue * 1.1 WHERE region = 'WEST'"} ) # Response example: # TextContent(text="... update results ...") ``` -------------------------------- ### Exclusion Patterns Configuration Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/README.md Example JSON configuration for excluding databases, schemas, and tables from discovery tools. ```json { "exclude_patterns": { "databases": ["temp"], "schemas": ["temp", "information_schema"], "tables": ["temp"] } } ``` -------------------------------- ### Configure mcp-snowflake-server with Individual Parameters Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Use this method to specify all configuration options directly as command-line arguments. Ensure all required parameters are provided. ```bash mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password "your_password" \ --warehouse COMPUTE_WH \ --database PRODUCTION \ --schema PUBLIC \ --role ACCOUNTADMIN \ --authenticator snowflake \ --log_level INFO \ --allow_write ``` -------------------------------- ### Register Resource Read Handler Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/resources.md Example of registering a resource read handler for the 'memo://insights' URI using the server.read_resource decorator. ```python @server.read_resource() async def handle_read_resource(uri: AnyUrl) -> str: if str(uri) == "memo://insights": return str(db.get_memo()) ... ``` -------------------------------- ### Create Table using MCP Snowflake Server Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/README.md Demonstrates how to create a table in Snowflake using the MCP Snowflake Server client. This requires write permissions. ```python from mcp_snowflake_server.client import MCPClient async def main(): client = MCPClient() # Create table await client.call_tool("create_table", { "table_name": "my_new_table", "schema": { "column1": "VARCHAR", "column2": "INTEGER" } }) ``` -------------------------------- ### Initialize SnowflakeDB Client Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/snowflake-db.md Instantiate the SnowflakeDB client with connection configuration. The configuration dictionary should include parameters like account, user, password, warehouse, database, and schema. ```python from mcp_snowflake_server.db_client import SnowflakeDB config = { 'account': 'myaccount', 'user': 'user@example.com', 'password': 'secret', 'warehouse': 'COMPUTE_WH', 'database': 'MY_DB', 'schema': 'PUBLIC' } db = SnowflakeDB(config) ``` -------------------------------- ### Initialize SnowflakeDB Client Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/README.md Initializes the main database client for Snowflake. Requires a ConnectionConfig dictionary. ```python from mcp_snowflake_server.db_client import SnowflakeDB, ConnectionConfig # Assuming connection_config is a dictionary with connection parameters connection_config: ConnectionConfig = { "account": "xy12345", "user": "user@example.com", "password": "secret", "database": "PROD_DB", "schema": "PUBLIC" } db_client = SnowflakeDB(connection_config) ``` -------------------------------- ### Configure mcp-snowflake-server with .env File Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Store configuration in a .env file and load it using tools like Docker or uvx. This centralizes configuration and simplifies deployment. ```bash # .env file SNOWFLAKE_ACCOUNT=xy12345 SNOWFLAKE_USER=user@example.com SNOWFLAKE_PASSWORD=your_password SNOWFLAKE_WAREHOUSE=COMPUTE_WH SNOWFLAKE_DATABASE=PRODUCTION SNOWFLAKE_SCHEMA=PUBLIC SNOWFLAKE_ROLE=ACCOUNTADMIN SNOWFLAKE_AUTHENTICATOR=snowflake ``` ```bash # Via Docker with env file docker run --rm -i \ --env-file /path/to/.env \ nsphung/mcp-snowflake-server-nsp \ --log_level INFO \ --allow_write ``` ```json # Via uvx with Claude Desktop config (uses envFile) # In claude_desktop_config.json: { "mcpServers": { "snowflake": { "command": "uvx", "args": ["--python=3.13", "--from", "mcp-snowflake-server-nsp", "mcp_snowflake_server"], "envFile": "${workspaceFolder}/.env" } } } ``` -------------------------------- ### Run Server Directly from Source Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/CONTRIBUTING.md Executes the server directly from the source code. This is an equivalent command to 'uv --directory . run mcp_snowflake_server'. ```bash make run ``` -------------------------------- ### Enable Table Schema Prefetching Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Use the --prefetch flag to pre-load all table and column metadata at startup. This disables list_tables and describe_table tools and makes schemas available as context resources. ```bash mcp_snowflake_server \ --account xy12345 \ --user user@example.com \ --password secret \ --database DB \ --schema PUBLIC \ --prefetch ``` -------------------------------- ### VS Code Configuration for Snowflake Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/API_OVERVIEW.md Configure VS Code for Snowflake development. This setup uses stdio communication with uvx and specifies the command and arguments. ```jsonc { "snowflake": { "type": "stdio", "command": "uvx", "args": [ "--python=3.13", "--from", "mcp-snowflake-server-nsp", "mcp_snowflake_server" ], "envFile": "${workspaceFolder}/.env" } } ``` -------------------------------- ### Read Table Schema Context Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/resources.md Use the MCP client to read the schema and metadata for a specific table resource. This is only available when the server is started with the --prefetch flag. ```python # Using MCP client to read table schema table_schema = await client.read_resource("context://table/CUSTOMERS") # Table schema is now available for analysis # Useful for understanding column names, types, and metadata ``` -------------------------------- ### Configure Private Key File Path (CLI/Env) Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Specify the absolute path to your .p8 private key file using either the CLI flag or an environment variable. This is required for key-pair authentication if the private key is not provided directly. ```bash --private_key_file /home/user/.ssh/snowflake_key.p8 export SNOWFLAKE_PRIVATE_KEY_FILE=/home/user/.ssh/snowflake_key.p8 ``` -------------------------------- ### Configure Private Key File Passphrase (CLI/Env) Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/configuration.md Provide the passphrase for an encrypted private key file using the CLI flag or an environment variable. This is only necessary if your private key file is protected by a password. ```bash --private_key_file_pwd "key_passphrase" export SNOWFLAKE_PRIVATE_KEY_FILE_PWD="key_passphrase" ``` -------------------------------- ### Enable Table Prefetching in Claude Desktop Config Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/resources.md Configure the mcpServers.snowflake.args in Claude Desktop's JSON configuration to include the --prefetch flag for the mcp_snowflake_server command. ```jsonc { "mcpServers": { "snowflake": { "command": "uvx", "args": [ "--python=3.13", "--from", "mcp-snowflake-server-nsp", "mcp_snowflake_server", "--connections-file", "/path/to/config.toml", "--connection-name", "production", "--prefetch" // Enable prefetching ] } } } ``` -------------------------------- ### Analyze Multi-Statement Query with Writes Source: https://github.com/nsphung/mcp-snowflake-server/blob/main/_autodocs/api-reference/write-detector.md Demonstrates analyzing a query containing multiple statements, including CREATE TABLE and DELETE. The result correctly identifies both as write operations. ```python detector = SQLWriteDetector() # Multi-statement with CREATE TABLE result = detector.analyze_query(""" CREATE TABLE users_backup AS SELECT * FROM users; DELETE FROM users; """) print(result) # Output: {'contains_write': True, 'write_operations': {'CREATE', 'DELETE'}, 'has_cte_write': False} ```