### Install db-query-mcp via pip Source: https://github.com/newtoolai/db-query-mcp/blob/main/README.md Standard installation command for the package. ```bash pip install db-query-mcp ``` -------------------------------- ### Install db-query-mcp from GitHub Source: https://github.com/newtoolai/db-query-mcp/blob/main/README.md Install the latest version directly from the source repository. ```bash pip install git+https://github.com/NewToolAI/db-query-mcp ``` -------------------------------- ### Install db-query-mcp with ElasticSearch support Source: https://github.com/newtoolai/db-query-mcp/blob/main/README.md Install the package with the optional ElasticSearch dependency. ```bash pip install "db-query-mcp[elasticsearch]" ``` -------------------------------- ### Configure MCP server using command Source: https://github.com/newtoolai/db-query-mcp/blob/main/README.md Configuration examples for running the server directly via command for SQLite and ElasticSearch. ```json { "mcpServers": { "sqlite_db_mcp": { "command": "db-query-mcp", "args": [ "--db", "sqlite", "--uri", "sqlite:///sqlite_company.db" ] } } } ``` ```json { "mcpServers": { "es_db_mcp": { "command": "db-query-mcp", "args": [ "--db", "elasticsearch", "--uri", "https://user:password@localhost:9200?index=test_data_index&ca_certs=/home/user/http_ca.crt" ] } } } ``` -------------------------------- ### Supported Relational Database URI Formats Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Examples of connection strings for various relational databases using the standard SQLAlchemy URI format. Ensure the correct driver is installed. ```python # SQLite - Local file database (built-in Python support) uri = "sqlite:///path/to/database.db" uri = "sqlite:///./relative/path/mydb.db" ``` ```python # MySQL - With pymysql driver uri = "mysql+pymysql://username:password@hostname:3306/database_name" uri = "mysql+pymysql://root:secret@localhost/myapp" ``` ```python # PostgreSQL - With psycopg2 driver uri = "postgresql://username:password@hostname:5432/database_name" uri = "postgresql://admin:pass123@db.example.com:5432/production" ``` ```python # Oracle - With cx_Oracle driver uri = "oracle+cx_oracle://username:password@hostname:1521/service_name" uri = "oracle+cx_oracle://sys:oracle@localhost:1521/ORCL" ``` ```python # SQL Server - With pyodbc driver uri = "mssql+pyodbc://username:password@hostname/database_name" uri = "mssql+pymysql://sa:password@localhost/master" ``` -------------------------------- ### Install DB Query MCP via pip Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Commands to install the base package, ElasticSearch support, or specific database drivers. ```bash # Base installation for relational databases pip install db-query-mcp # With ElasticSearch support pip install "db-query-mcp[elasticsearch]" # Install from GitHub (latest) pip install git+https://github.com/NewToolAI/db-query-mcp # Database-specific drivers pip install pymysql # MySQL pip install psycopg2-binary # PostgreSQL pip install cx_Oracle # Oracle pip install pyodbc # SQL Server ``` -------------------------------- ### ElasticSearch Connection URI Examples Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Examples of connection strings for Elasticsearch, including options for SSL and specifying an index and CA certificates. ```python # ElasticSearch - With optional SSL and index parameters uri = "https://user:password@localhost:9200?index=my_index" uri = "https://elastic:changeme@es.example.com:9200?index=logs&ca_certs=/certs/ca.crt" ``` -------------------------------- ### Configure MCP server with uvx Source: https://github.com/newtoolai/db-query-mcp/blob/main/README.md Configuration examples for running the server using uvx for SQLite and ElasticSearch. ```json { "mcpServers": { "sqlite_db_mcp": { "command": "uvx", "args": [ "db-query-mcp", "--db", "sqlite", "--uri", "sqlite:///sqlite_company.db" ] } } } ``` ```json { "mcpServers": { "es_db_mcp": { "command": "uvx", "args": [ "db-query-mcp", "--db", "elasticsearch", "--uri", "https://user:password@localhost:9200?index=test_data_index&ca_certs=/home/user/http_ca.crt" ] } } } ``` -------------------------------- ### Install MySQL dependencies Source: https://github.com/newtoolai/db-query-mcp/blob/main/README.md Required dependency for MySQL database connections. ```bash pip install pymysql ``` -------------------------------- ### Example Export to CSV Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Demonstrates exporting relational database query results to a CSV file. ```APIDOC # Example for relational database - Export to CSV export_database( query="Export all customer orders from 2024", statement='SELECT "order_id", "customer_name", "total", "order_date" FROM "orders" WHERE "order_date" >= \'2024-01-01\'', path="/path/to/orders_2024.csv" ) # Returns: "Successfully exported the data to /path/to/orders_2024.csv" ``` -------------------------------- ### Install PostgreSQL dependencies Source: https://github.com/newtoolai/db-query-mcp/blob/main/README.md Required dependency for PostgreSQL database connections. ```bash pip install psycopg2-binary ``` -------------------------------- ### Database Connection Strings Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Provides examples of database URI formats for various database systems supported by the library. ```APIDOC ## Database Connection Strings ### Supported Database URI Formats Use the appropriate connection string format for your database type. All connections support the standard SQLAlchemy URI format for relational databases. ```python # SQLite - Local file database (built-in Python support) uri = "sqlite:///path/to/database.db" uri = "sqlite:///./relative/path/mydb.db" # MySQL - With pymysql driver uri = "mysql+pymysql://username:password@hostname:3306/database_name" uri = "mysql+pymysql://root:secret@localhost/myapp" # PostgreSQL - With psycopg2 driver uri = "postgresql://username:password@hostname:5432/database_name" uri = "postgresql://admin:pass123@db.example.com:5432/production" # Oracle - With cx_Oracle driver uri = "oracle+cx_oracle://username:password@hostname:1521/service_name" uri = "oracle+cx_oracle://sys:oracle@localhost:1521/ORCL" # SQL Server - With pyodbc driver uri = "mssql+pyodbc://username:password@hostname/database_name" uri = "mssql+pymysql://sa:password@localhost/master" # ElasticSearch - With optional SSL and index parameters uri = "https://user:password@localhost:9200?index=my_index" uri = "https://elastic:changeme@es.example.com:9200?index=logs&ca_certs=/certs/ca.crt" ``` ``` -------------------------------- ### Example Export to JSON Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Demonstrates exporting Elasticsearch query results to a JSON file. ```APIDOC # Example for ElasticSearch - Export to JSON export_database( query="Export all error logs from today", statement={ "query": { "bool": { "must": [ {"match": {"level": "error"}}, {"range": {"timestamp": {"gte": "now-1d/d"}}} ] } }, "size": 1000 }, path="/path/to/error_logs.json" ) # Returns: "Successfully exported data to /path/to/error_logs.json" ``` -------------------------------- ### Execute query_database Tool Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Examples of using the query_database tool for SQL SELECT statements and ElasticSearch DSL queries. ```python # MCP Tool: query_database # Parameters: # query (str): The natural language query from the user # statement (str|dict): The SQL statement or ElasticSearch DSL query # Example for relational database - SQL SELECT statement query_database( query="Show all employees with salary over 50000", statement='SELECT "id", "name", "department", "salary" FROM "employees" WHERE "salary" > 50000 ORDER BY "salary" DESC' ) # Returns markdown table: # | id | name | department | salary | # | --- | --- | --- | --- | # | 1 | John Smith | Engineering | 75000 | # | 2 | Jane Doe | Marketing | 65000 | # # **Query result summary:** 2 rows, 4 columns # Example for ElasticSearch - DSL query query_database( query="Find documents where status is active", statement={ "query": { "bool": { "must": [ {"match": {"status": "active"}} ] } }, "size": 10, "sort": [{"created_at": "desc"}] } ) # Returns JSON response with hits ``` -------------------------------- ### Get Relational Database Type and Schema Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Retrieve the database type and the full schema (tables, columns, keys) from a RelationalDBAdapter. The schema is returned in markdown format. ```python # Get database type db_type = adapter.get_db_type() # Returns: "sqlite" ``` ```python # Get full database schema (tables, columns, primary keys, foreign keys) schema = adapter.get_db_schema() # Returns markdown-formatted schema: # ### Table name: `employees` # | Column Name | Data Type | Nullable | Default Value | Primary Key | Comment | # |---|---|---|---|---|---| # | id | INTEGER | ✗ | - | ✓ | - | # | name | VARCHAR(100) | ✗ | - | ✗ | - | # | department | VARCHAR(50) | ✓ | - | ✗ | - | ``` -------------------------------- ### Get Elasticsearch Type and Schema Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Retrieve the database type and the index mapping schema from an ElasticsearchDBAdapter. The schema is returned as a JSON string. ```python # Get database type db_type = adapter.get_db_type() # Returns: "elasticsearch" ``` ```python # Get index mapping schema schema = adapter.get_db_schema() # Returns JSON string with index mapping ``` -------------------------------- ### Initialize Database Connections Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Create database instances for various supported backends using the factory pattern. ```python db = factory.create_db("sqlite", "sqlite:///example.db") db = factory.create_db("mysql", "mysql+pymysql://user:pass@localhost/mydb") db = factory.create_db("postgresql", "postgresql://user:pass@localhost:5432/mydb") ``` ```python db = factory.create_db( "elasticsearch", "https://user:pass@localhost:9200?index=my_index&ca_certs=/path/to/ca.crt" ) ``` -------------------------------- ### Initialize ElasticsearchDBAdapter Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Instantiate the ElasticsearchDBAdapter by providing the database URI, index name, and optionally CA certificates path for SSL connections. ```python from db_query_mcp.db_adapters.elasticsearch_db_adapter import ElasticsearchDBAdapter # Initialize adapter with ElasticSearch URI and index adapter = ElasticsearchDBAdapter( db_uri="https://localhost:9200", index="logs", ca_certs="/path/to/ca.crt" ) ``` -------------------------------- ### Initialize RelationalDBAdapter Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Instantiate the RelationalDBAdapter by providing the database connection URI. This adapter is for SQL databases and prevents write operations. ```python from db_query_mcp.db_adapters.relational_db_adapter import RelationalDBAdapter # Initialize adapter with database URI adapter = RelationalDBAdapter("sqlite:///company.db") ``` -------------------------------- ### Create Database Adapter using Factory Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Use the factory module to dynamically create database adapters based on provided type and URI. This is the recommended method for programmatic use. ```python from db_query_mcp import factory # Create a database adapter based on type and URI ``` -------------------------------- ### Execute SELECT Query with RelationalDBAdapter Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Execute a SELECT query using the RelationalDBAdapter. The results are returned as a markdown table. ```python # Execute a SELECT query result = adapter.query('SELECT "id", "name" FROM "employees" LIMIT 5') # Returns markdown table with results ``` -------------------------------- ### Generate LLM Prompts Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Generate schema-aware prompts for LLM-assisted query generation based on the connected database. ```python query_prompt, export_prompt = factory.create_sql_prompt( db_type=db.get_db_type(), db_schema=db.get_db_schema() ) ``` -------------------------------- ### Factory Functions Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Provides factory functions to dynamically create database adapters based on configuration, recommended for programmatic usage. ```APIDOC ### Factory Functions Use the factory module to create database adapters dynamically based on configuration. This is the recommended approach for programmatic usage. ```python from db_query_mcp import factory # Create a database adapter based on type and URI ``` -------------------------------- ### RelationalDBAdapter Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Adapter class for SQL databases, supporting query execution, schema inspection, and data export. Write operations are blocked for security. ```APIDOC ## Python API ### RelationalDBAdapter The adapter class for all SQL databases. It provides query execution, schema inspection, and data export with built-in security checks that prevent write operations. ```python from db_query_mcp.db_adapters.relational_db_adapter import RelationalDBAdapter # Initialize adapter with database URI adapter = RelationalDBAdapter("sqlite:///company.db") # Get database type db_type = adapter.get_db_type() # Returns: "sqlite" # Get full database schema (tables, columns, primary keys, foreign keys) schema = adapter.get_db_schema() # Returns markdown-formatted schema: # ### Table name: `employees` # | Column Name | Data Type | Nullable | Default Value | Primary Key | Comment | # |---|---|---|---|---|---| # | id | INTEGER | ✗ | - | ✓ | - | # | name | VARCHAR(100) | ✗ | - | ✗ | - | # | department | VARCHAR(50) | ✓ | - | ✗ | - | # Execute a SELECT query result = adapter.query('SELECT "id", "name" FROM "employees" LIMIT 5') # Returns markdown table with results # Export query results to CSV adapter.export( 'SELECT * FROM "employees"', '/path/to/export/employees.csv' ) # Creates CSV file with query results # Security: Write operations are blocked try: adapter.query('DELETE FROM employees WHERE id = 1') except Exception as e: print(e) # "Only support query operations." ``` ``` -------------------------------- ### Configure MCP Server for Databases Source: https://context7.com/newtoolai/db-query-mcp/llms.txt JSON configuration blocks for integrating various database types into the MCP server. ```json { "mcpServers": { "sqlite_db_mcp": { "command": "uvx", "args": [ "db-query-mcp", "--db", "sqlite", "--uri", "sqlite:///path/to/database.db" ] } } } ``` ```json { "mcpServers": { "mysql_db_mcp": { "command": "db-query-mcp", "args": [ "--db", "mysql", "--uri", "mysql+pymysql://user:password@localhost/dbname" ] } } } ``` ```json { "mcpServers": { "postgres_db_mcp": { "command": "db-query-mcp", "args": [ "--db", "postgresql", "--uri", "postgresql://user:password@localhost:5432/dbname" ] } } } ``` ```json { "mcpServers": { "es_db_mcp": { "command": "uvx", "args": [ "db-query-mcp", "--db", "elasticsearch", "--uri", "https://user:password@localhost:9200?index=my_index&ca_certs=/path/to/http_ca.crt" ] } } } ``` -------------------------------- ### Export Query Results to CSV with RelationalDBAdapter Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Export the results of a query from a relational database to a CSV file using the export method of RelationalDBAdapter. ```python # Export query results to CSV adapter.export( 'SELECT * FROM "employees"', '/path/to/export/employees.csv' ) # Creates CSV file with query results ``` -------------------------------- ### RelationalDBAdapter Security - Blocked Write Operations Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Demonstrates that the RelationalDBAdapter prevents write operations by raising an exception if a query attempts to modify data. ```python # Security: Write operations are blocked try: adapter.query('DELETE FROM employees WHERE id = 1') except Exception as e: print(e) # "Only support query operations." ``` -------------------------------- ### Parse Connection URIs Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Extract base URI and query parameters from a connection string. ```python uri, args = factory.parse_uri( "https://localhost:9200?index=logs&ca_certs=/certs/ca.crt" ) ``` -------------------------------- ### Execute export_database Tool Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Parameters for the export_database tool, which saves query results to CSV or JSON files. ```python # MCP Tool: export_database # Parameters: # query (str): The natural language query from the user # statement (str|dict): The SQL statement or ElasticSearch DSL query # path (str): The file path to export the data ``` -------------------------------- ### ElasticsearchDBAdapter Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Adapter class for Elasticsearch clusters, supporting DSL query execution, index mapping inspection, and JSON export. ```APIDOC ### ElasticsearchDBAdapter The adapter class for ElasticSearch clusters. It provides DSL query execution, index mapping inspection, and JSON export capabilities. ```python from db_query_mcp.db_adapters.elasticsearch_db_adapter import ElasticsearchDBAdapter # Initialize adapter with ElasticSearch URI and index adapter = ElasticsearchDBAdapter( db_uri="https://localhost:9200", index="logs", ca_certs="/path/to/ca.crt" ) # Get database type db_type = adapter.get_db_type() # Returns: "elasticsearch" # Get index mapping schema schema = adapter.get_db_schema() # Returns JSON string with index mapping # Execute a search query with DSL result = adapter.query({ "query": { "bool": { "must": [ {"match": {"level": "error"}}, {"range": {"timestamp": {"gte": "now-7d"}}} ] } }, "aggs": { "errors_by_service": { "terms": {"field": "service.keyword"} } }, "size": 100, "sort": [{"timestamp": "desc"}] }) # Returns JSON string with search results and aggregations # Export search results to JSON file adapter.export( query={"query": {"match_all": {}}, "size": 1000}, output="/path/to/export/all_logs.json" ) # Creates JSON file with search results ``` ``` -------------------------------- ### Execute Elasticsearch DSL Query Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Execute a search query using Elasticsearch DSL with the ElasticsearchDBAdapter. Results and aggregations are returned as a JSON string. ```python # Execute a search query with DSL result = adapter.query({ "query": { "bool": { "must": [ {"match": {"level": "error"}}, {"range": {"timestamp": {"gte": "now-7d"}}} ] } }, "aggs": { "errors_by_service": { "terms": {"field": "service.keyword"} } }, "size": 100, "sort": [{"timestamp": "desc"}] }) # Returns JSON string with search results and aggregations ``` -------------------------------- ### Export Relational Database Data to CSV Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Use the export_database function to export query results from a relational database to a CSV file. Specify the query statement and the output path. ```python export_database( query="Export all customer orders from 2024", statement='SELECT "order_id", "customer_name", "total", "order_date" FROM "orders" WHERE "order_date" >= \'2024-01-01\'', path="/path/to/orders_2024.csv" ) ``` -------------------------------- ### query_database Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Executes read-only queries against a configured database. Accepts SQL SELECT statements for relational databases or DSL query objects for ElasticSearch. ```APIDOC ## query_database ### Description Executes a read-only query against the configured database. Results are returned in markdown table format for relational databases or JSON for ElasticSearch. ### Parameters - **query** (str) - Required - The natural language query from the user. - **statement** (str|dict) - Required - The SQL statement (for relational databases) or ElasticSearch DSL query object. ### Request Example { "query": "Show all employees with salary over 50000", "statement": "SELECT \"id\", \"name\", \"department\", \"salary\" FROM \"employees\" WHERE \"salary\" > 50000 ORDER BY \"salary\" DESC" } ### Response #### Success Response (200) - **result** (string/object) - The query results in markdown table format or JSON. ``` -------------------------------- ### export_database Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Executes a query and exports the results to a specified file path. Supports CSV export for relational databases and JSON export for ElasticSearch. ```APIDOC ## export_database ### Description Executes a query and exports the results to a file. Prevents overwriting existing files. ### Parameters - **query** (str) - Required - The natural language query from the user. - **statement** (str|dict) - Required - The SQL statement or ElasticSearch DSL query. - **path** (str) - Required - The file path to export the data. ### Request Example { "query": "Export active users", "statement": "SELECT * FROM users WHERE status = 'active'", "path": "/exports/active_users.csv" } ``` -------------------------------- ### Export Elasticsearch Search Results to JSON Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Export search results from Elasticsearch to a JSON file using the export method of ElasticsearchDBAdapter. The query can be a standard search query. ```python # Export search results to JSON file adapter.export( query={"query": {"match_all": {}}, "size": 1000}, output="/path/to/export/all_logs.json" ) # Creates JSON file with search results ``` -------------------------------- ### Export Elasticsearch Data to JSON Source: https://context7.com/newtoolai/db-query-mcp/llms.txt Use the export_database function to export search results from Elasticsearch to a JSON file. The statement can be an Elasticsearch DSL query. ```python export_database( query="Export all error logs from today", statement={ "query": { "bool": { "must": [ {"match": {"level": "error"}}, {"range": {"timestamp": {"gte": "now-1d/d"}}} ] } }, "size": 1000 }, path="/path/to/error_logs.json" ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.