### Example MCP Server Startup Logs Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/CLI_main.md This example shows the typical log output when the MotherDuck MCP Server starts. It includes version, database mode, query limits, timeout settings, and transport information. ```text 🦆 MotherDuck MCP Server v1.0.7 Ready to execute SQL queries via DuckDB/MotherDuck Database mode: in-memory (read-write) Query result limits: 1024 rows, 50,000 characters Query timeout: disabled Switch databases: enabled MCP server initialized in http mode 🦆 Connect to MotherDuck MCP Server at http://127.0.0.1:8000/mcp ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Demonstrates how environment variables are overridden by command-line arguments for configuration settings. ```bash # DB_PATH from env var is overridden by command-line export MCP_DB_PATH="s3://..." mcp-server-motherduck --db-path ":memory:" # Uses :memory: ``` -------------------------------- ### Database Client Initialization Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md Use this to create or configure a database connection. No specific setup is required beyond instantiating the client. ```python DatabaseClient.__init__(...) -> None ``` -------------------------------- ### Server Configuration Header Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/get_instructions.md An example of the server configuration header included in the instructions, detailing database status and access mode. ```text ## Server Configuration - **Database**: In-memory (data will not persist after session ends) - **Access mode**: Read-write - all SQL operations are allowed - **Available tools**: execute_query, list_databases, list_tables, list_columns ``` -------------------------------- ### Start MCP Server in Development Mode Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Starts the server for development with an in-memory, read-write database that allows switching between databases. ```bash mcp-server-motherduck \ --db-path ":memory:" --read-write \ --allow-switch-databases ``` -------------------------------- ### Start MCP Server with MotherDuck Cloud Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Starts the server for MotherDuck cloud access, enabling read-write operations and requiring an authentication token. ```bash mcp-server-motherduck \ --db-path "md:" --motherduck-token "your_token" --read-write ``` -------------------------------- ### CLI Entry Point Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/MANIFEST.txt Documentation for the main CLI entry point function, including all command-line options and usage examples. ```APIDOC ## CLI Entry Point ### Description Documentation for the main CLI entry point, covering all command-line options, environment variable mappings, and usage examples for various scenarios. ``` -------------------------------- ### CLI Invocation Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md Shows how the MCP Server MotherDuck CLI is invoked and which internal function it maps to. ```bash # CLI is invoked as mcp-server-motherduck [options] # Which calls mcp_server_motherduck:main ``` -------------------------------- ### MCP Server Startup Logging Output Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Example output of the MCP Server's startup log, showing version, database mode, query limits, and initialization status. ```text 🦆 MotherDuck MCP Server v1.0.7 Ready to execute SQL queries via DuckDB/MotherDuck Database mode: in-memory (read-write) Query result limits: 1024 rows, 50,000 characters Query timeout: disabled Switch databases: enabled MCP server initialized in stdio mode Waiting for client connection ``` -------------------------------- ### DuckDB Data Persistence Examples Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/get_instructions.md Shows how to persist in-memory DuckDB data to files using ATTACH, COPY, and DETACH commands. ```sql -- Attach a new file-based database ATTACH '/path/to/my_database.db' AS my_db; -- Copy all data from memory to the file COPY FROM DATABASE memory TO my_db; -- Optionally detach when done DETACH my_db; ``` -------------------------------- ### SaaS Mode Indicator Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/get_instructions.md Shows the indicator for SaaS mode being enabled, highlighting restricted local filesystem access for security. ```text - **SaaS mode**: Enabled - local filesystem access is restricted for security ``` -------------------------------- ### main() Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md The main function serves as the command-line interface entry point for starting the MCP server. It is the primary way to launch the server application. ```APIDOC ## main() ### Description CLI entry point for starting the server. ### Function Signature `main() -> None` ``` -------------------------------- ### Example Successful Switch Response Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/types.md An example JSON payload representing a successful database switch operation. ```json { "success": true, "message": "Switched to database: /path/to/database.duckdb", "previousDatabase": ":memory:", "currentDatabase": "/path/to/database.duckdb", "readOnly": true } ``` -------------------------------- ### List tables in a specific schema Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md This example demonstrates how to list tables and views from a particular database and schema. Specify both 'database' and 'schema' parameters for targeted results. ```python # List tables in specific schema result = client.call_tool("list_tables", { "database": "memory", "schema": "main" }) ``` -------------------------------- ### create_mcp_server Function Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/MANIFEST.txt Documentation for the server factory function, detailing tool registration and integration examples. ```APIDOC ## create_mcp_server Function ### Description Factory function to create and configure the MCP server, including registering tools and providing integration examples. ``` -------------------------------- ### Example Failed Switch Response Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/types.md An example JSON payload representing a failed database switch operation due to a missing file. ```json { "success": false, "error": "Database file does not exist: /path/to/missing.duckdb. Set create_if_not_exists=True to create a new database.", "errorType": "FileNotFoundError" } ``` -------------------------------- ### Unsupported Feature Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md This error is returned when using an uninstalled DuckDB extension, an unsupported SQL feature, or an unsupported function. Use core DuckDB features or install necessary extensions via `CREATE EXTENSION`. ```json { "success": false, "error": "Not Implemented Error: Extension not found", "errorType": "NotImplementedException" } ``` -------------------------------- ### Local Development Server Configuration Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Starts the MCP server for local development with an in-memory database, read-write access, and database switching enabled. ```bash mcp-server-motherduck \ --db-path ":memory:" \ --read-write \ --allow-switch-databases \ --transport stdio ``` -------------------------------- ### Run mcp-server-motherduck with In-Memory Database Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/CLI_main.md Use this command for development and testing when no data persistence is required. It starts a server with an in-memory database. ```bash mcp-server-motherduck \ --db-path ":memory:" \ --read-write \ --allow-switch-databases ``` -------------------------------- ### In-Memory Database Validation Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Ensures in-memory databases are started with the required `--read-write` flag. The first example shows an error, while the second demonstrates the correct usage. ```bash # ✗ Error: In-memory databases require the --read-write flag mcp-server-motherduck --db-path ":memory:" ``` ```bash # ✓ Correct mcp-server-motherduck --db-path ":memory:" --read-write ``` -------------------------------- ### Common Python Imports for MCP Server Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md Demonstrates common import patterns for programmatically starting the server, using the database client directly, and accessing utility functions and configurations. ```python # Start the server programmatically from mcp_server_motherduck import main from mcp_server_motherduck.server import create_mcp_server # Use the database client directly from mcp_server_motherduck.database import DatabaseClient, quote_sql_string, quote_sql_identifier # Get instructions from mcp_server_motherduck.instructions import get_instructions # Configuration from mcp_server_motherduck.configs import SERVER_VERSION, SERVER_LOCALHOST # Tools (usually not imported directly, registered by create_mcp_server) from mcp_server_motherduck.tools.execute_query import execute_query from mcp_server_motherduck.tools.list_databases import list_databases from mcp_server_motherduck.tools.list_tables import list_tables from mcp_server_motherduck.tools.list_columns import list_columns from mcp_server_motherduck.tools.switch_database_connection import switch_database_connection ``` -------------------------------- ### Example Server Error Logs Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md These are example log entries that appear on stderr during server operation, indicating various types of errors encountered. ```text [motherduck] ERROR - Parser Error: syntax error in query [motherduck] ERROR - IO Error: Could not open file: /path/to/db.duckdb [motherduck] ERROR - Catalog Error: Table does not exist ``` -------------------------------- ### DuckDB Flexible Query Structure Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/get_instructions.md Illustrates flexible query structures in DuckDB, including starting queries with `FROM` and using `SELECT` without `FROM` for expressions. ```sql - Queries can start with `FROM`: `FROM my_table WHERE condition;` - `SELECT` without `FROM` for expressions: `SELECT 1 + 1 AS result;` - Support for `CREATE TABLE AS` (CTAS): `CREATE TABLE new_table AS SELECT * FROM old_table;` ``` -------------------------------- ### Create new database if it doesn't exist Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Use this snippet to create a new database file if it does not already exist. This requires the server to be started in read-write mode. The result indicates success or provides an error message. ```python result = client.call_tool("switch_database_connection", { "path": "/absolute/path/to/new.duckdb", "create_if_not_exists": true }) if result["success"]: print(f"Switched to: {result['currentDatabase']}") else: print(f"Error: {result['error']}") ``` -------------------------------- ### Example JSON Output for list_tables Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md This JSON structure represents a successful response from the list_tables tool, detailing tables and views within a specified database and schema. ```json { "success": true, "database": "memory", "schema": "all", "tables": [ { "schema": "main", "name": "users", "type": "table", "comment": "User accounts" }, { "schema": "main", "name": "active_users", "type": "view", "comment": null } ], "tableCount": 1, "viewCount": 1 } ``` -------------------------------- ### Execute Query Success Output Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Example JSON output for a successful query execution, including column names, types, rows, row count, and truncation status. ```json { "success": true, "columns": ["column1", "column2"], "columnTypes": ["INTEGER", "VARCHAR"], "rows": [[1, "value1"], [2, "value2"]], "rowCount": 2, "truncated": false } ``` -------------------------------- ### Catalog Error Examples Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md These errors occur when referenced database objects like tables, views, columns, or schemas do not exist. Verify object names using `list_tables`, `list_columns`, or `list_databases` tools and create missing objects if necessary. ```json { "success": false, "error": "Catalog Error: Table with name does_not_exist does not exist!", "errorType": "CatalogException" } ``` ```json { "success": false, "error": "Catalog Error: Duplicate entry in catalog", "errorType": "CatalogException" } ``` -------------------------------- ### Permission Error Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md This error occurs when attempting write operations (INSERT, UPDATE, DELETE, DROP, CREATE TABLE) in read-only mode. Start the server with the `--read-write` flag if writes are necessary, or use read-only mode for data exploration. ```json { "success": false, "error": "Cannot perform write operations in read-only mode", "errorType": "PermissionException" } ``` -------------------------------- ### Feature Configuration Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Configure initialization SQL, allow switching databases, and set MotherDuck connection parameters. ```bash mcp-server-motherduck \ --init-sql "/path/to/setup.sql" \ --allow-switch-databases \ --motherduck-connection-parameters "session_hint=mcp&dbinstance_inactivity_ttl=0s" ``` -------------------------------- ### Create MCP Server with CLI Arguments Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/create_mcp_server.md Shows how to create an MCP server instance within the CLI entry point, passing parameters like database path and MotherDuck token parsed from command-line arguments. ```python # In mcp_server_motherduck/__init__.py main() mcp = create_mcp_server( db_path=db_path, motherduck_token=motherduck_token, # ... other parameters ) ``` -------------------------------- ### Run mcp-server-motherduck with Init SQL File Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/CLI_main.md Initialize the database with SQL commands defined in a separate file. This is useful for setting up tables and initial data. ```bash mcp-server-motherduck \ --db-path ":memory:" \ --read-write \ --init-sql "/path/to/setup.sql" ``` -------------------------------- ### Run mcp-server-motherduck with Inline Init SQL Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/CLI_main.md Initialize the database with inline SQL commands. This is a convenient way to set up simple table structures. ```bash mcp-server-motherduck \ --db-path ":memory:" \ --read-write \ --init-sql "CREATE TABLE users (id INT, name VARCHAR);" ``` -------------------------------- ### Initialization: Load Schema on Startup Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Initialize the database with a schema from an SQL file or inline SQL statements upon startup. This is useful for setting up tables and pre-populating data for testing or demos. ```bash # Using SQL file mcp-server-motherduck \ --db-path ":memory:" --read-write \ --init-sql "/path/to/schema.sql" ``` ```bash # Using inline SQL mcp-server-motherduck \ --db-path ":memory:" --read-write \ --init-sql "CREATE TABLE users (id INT, name VARCHAR); INSERT INTO users VALUES (1, 'Alice');" ``` -------------------------------- ### get_instructions Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/get_instructions.md Generates contextualized server instructions sent to MCP clients during initialization. The instructions provide DuckDB SQL reference material and explain the server's capabilities and limitations based on runtime configuration. ```APIDOC ## Function: get_instructions ### Description Generates contextualized server instructions sent to MCP clients during initialization. The instructions provide DuckDB SQL reference material and explain the server's capabilities and limitations based on runtime configuration. ### Signature ```python def get_instructions( read_only: bool = False, saas_mode: bool = False, db_path: str = ":memory:", allow_switch_databases: bool = False, ) -> str ``` ### Parameters #### Query Parameters - **read_only** (bool) - Optional - Whether server is in read-only mode. Defaults to `False`. - **saas_mode** (bool) - Optional - Whether MotherDuck SaaS mode is enabled. Defaults to `False`. - **db_path** (str) - Optional - The database path being used. Defaults to `:memory:`. - **allow_switch_databases** (bool) - Optional - Whether database switching is enabled. Defaults to `False`. ### Returns **Type:** `str` A complete instructions string combining server configuration summary, DuckDB SQL quick reference, query best practices, and data persistence patterns. ``` -------------------------------- ### Create and Run MCP Server Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/create_mcp_server.md Demonstrates creating an in-memory MCP server with read-write access and running it with both stdio and HTTP transports. Configure max rows and database switching. ```python from mcp_server_motherduck.server import create_mcp_server # Create server for in-memory database with read-write access mcp = create_mcp_server( db_path=":memory:", read_only=False, max_rows=2000, allow_switch_databases=True ) # Run with stdio transport mcp.run(transport="stdio") # Or run with HTTP transport mcp.run(transport="http", host="127.0.0.1", port=8000) ``` -------------------------------- ### Basic Database Configuration Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Configure the database path, MotherDuck token, and home directory. Enable SaaS mode for restricted filesystem access. ```bash mcp-server-motherduck \ --db-path ":memory:" \ --motherduck-token "token_value" \ --home-dir "/path/to/home" \ --motherduck-saas-mode ``` -------------------------------- ### Parser Error Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md This error occurs when the SQL query has invalid syntax. Correct the SQL syntax and retry the query. ```json { "success": false, "error": "Parser Error: syntax error at 'FORM'", "errorType": "ParserException" } ``` -------------------------------- ### Run mcp-server-motherduck with MotherDuck (Read-Write) Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/CLI_main.md Connect to MotherDuck in the cloud with write access. Replace YOUR_TOKEN with your actual MotherDuck token. ```bash mcp-server-motherduck \ --db-path "md:" \ --motherduck-token "YOUR_TOKEN" \ --read-write ``` -------------------------------- ### Initialize DatabaseClient Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/create_mcp_server.md Creates a DatabaseClient instance with various configuration parameters for connecting to a DuckDB database, including MotherDuck specific settings. ```python db_client = DatabaseClient( db_path=db_path, motherduck_token=motherduck_token, home_dir=home_dir, saas_mode=saas_mode, read_only=read_only, ephemeral_connections=ephemeral_connections, max_rows=max_rows, max_chars=max_chars, query_timeout=query_timeout, init_sql=init_sql, motherduck_connection_parameters=motherduck_connection_parameters, ) ``` -------------------------------- ### MCP Server Creation Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md Use `create_mcp_server` to instantiate the MCP server. The `get_instructions` function retrieves necessary operational details. ```python create_mcp_server(...) -> FastMCP ``` ```python get_instructions(...) -> str ``` -------------------------------- ### Execute Query Output with Row Truncation Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Example JSON output when query results are truncated due to the maximum row limit. ```json { "success": true, "columns": ["id", "name"], "columnTypes": ["INTEGER", "VARCHAR"], "rows": [/* first 1024 rows */], "rowCount": 1024, "truncated": true, "warning": "Results limited to 1024 rows. Query returned more data." } ``` -------------------------------- ### Example JSON Output on error Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md This JSON structure indicates an error response from the list_tables tool, typically occurring when a specified database does not exist. ```json { "success": false, "error": "Database 'unknown' does not exist", "errorType": "CatalogException" } ``` -------------------------------- ### DuckDB Complex Data Types Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/get_instructions.md Provides examples of using complex data types in DuckDB, including lists, structs, maps, and JSON. ```sql - Lists: `SELECT [1, 2, 3] AS my_list;` - Structs: `SELECT {'a': 1, 'b': 'text'} AS my_struct;` - Maps: `SELECT MAP([1,2],['one','two']) AS my_map;` - JSON: `json_col->>'key'` (returns text) or `data->'$.user.id'` (returns JSON) ``` -------------------------------- ### List Columns using Client Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Lists columns for a given table, including their names, types, and nullability. Requires the client to be initialized. ```python # List columns result = client.call_tool("list_columns", {"table": "users"}) for col in result["columns"]: print(f"{col['name']}: {col['type']} {'NOT NULL' if not col['nullable'] else ''}") ``` -------------------------------- ### Query Execution Error Response Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/create_mcp_server.md Example JSON structure for a query execution error, indicating success status, error message, and error type. ```json { "success": false, "error": "Parser Error: ...", "errorType": "ParserException" } ``` -------------------------------- ### Initialize DatabaseClient Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/DatabaseClient.md Instantiate DatabaseClient for various database connection types including in-memory, local files, MotherDuck, and S3-hosted databases. Configure read-only, ephemeral connections, and authentication. ```python client = DatabaseClient(db_path=":memory:", read_write=False) ``` ```python client = DatabaseClient( db_path="/absolute/path/to/database.duckdb", read_only=True, ephemeral_connections=True ) ``` ```python client = DatabaseClient( db_path="md:", motherduck_token="your_token_here", read_only=False ) ``` ```python client = DatabaseClient( db_path="s3://bucket-name/path/to/database.duckdb", read_only=True ) ``` -------------------------------- ### List Tables Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/create_mcp_server.md Use list_tables to get a JSON string of tables and views within a specified database and schema. Defaults to the current database if not specified. ```python def list_tables(database: str | None = None, schema: str | None = None) -> str: ``` -------------------------------- ### DuckDB Grouping and Ordering Shortcuts Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/get_instructions.md Demonstrates shortcuts for grouping and ordering in DuckDB, including grouping by all non-aggregated columns and ordering by all columns. ```sql - Group by all non-aggregated columns: `SELECT category, SUM(sales) FROM sales_data GROUP BY ALL;` - Order by all columns: `SELECT * FROM my_table ORDER BY ALL;` ``` -------------------------------- ### CLI Entry Point Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md The `main` function serves as the entry point for the Command Line Interface. It is typically invoked via the `mcp-server-motherduck` command. ```python main(...) -> None ``` -------------------------------- ### Execute Query Output with Character Truncation Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Example JSON output when query results are truncated due to the maximum output size limit (e.g., 50KB). ```json { "success": true, "columns": ["id", "data"], "columnTypes": ["INTEGER", "VARCHAR"], "rows": [/* reduced rows */], "rowCount": 512, "truncated": true, "warning": "Results limited to 512 rows due to 50KB output size limit." } ``` -------------------------------- ### Type Error Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md This error indicates a type mismatch in an operation, comparison, or cast. Ensure operands are compatible or use `CAST()` for explicit type conversion. ```json { "success": false, "error": "Type Error: Cannot implicitly cast VARCHAR to INTEGER", "errorType": "TypeError" } ``` -------------------------------- ### Python: Simple SELECT Query Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Demonstrates calling the 'execute_query' tool for a simple SELECT statement with a LIMIT clause. ```python # Simple select result = client.call_tool("execute_query", {"sql": "SELECT * FROM users LIMIT 10"}) ``` -------------------------------- ### Example JSON Output with schema filter Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md This JSON output illustrates the result of using the 'schema' filter with the list_tables tool, showing only objects within the 'analytics' schema. ```json { "success": true, "database": "memory", "schema": "analytics", "tables": [ { "schema": "analytics", "name": "user_metrics", "type": "table", "comment": null } ], "tableCount": 1, "viewCount": 0 } ``` -------------------------------- ### Generate Server Instructions Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/create_mcp_server.md Generates server instructions based on the provided configuration, including read-only mode, SaaS mode, and database path. ```python instructions = get_instructions( read_only=read_only, saas_mode=saas_mode, db_path=db_path, allow_switch_databases=allow_switch_databases, ) ``` -------------------------------- ### Python: Query with Server-Side Timeout Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Example of executing a query that might exceed the server's configured timeout. The server will enforce the timeout and return an error if exceeded. ```python # Query with timeout enforcement (server applies timeout) result = client.call_tool("execute_query", {"sql": "SELECT * FROM enormous_table"}) # Returns error if execution exceeds --query-timeout setting ``` -------------------------------- ### Python: INSERT Statement Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Shows how to use the 'execute_query' tool to perform an INSERT operation, assuming the server is in read-write mode. ```python # Insert with read-write mode result = client.call_tool("execute_query", {"sql": "INSERT INTO logs (message) VALUES ('test')"}) ``` -------------------------------- ### JSON Representation of NULL Values Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/types.md In JSON responses, SQL NULL values are consistently represented as JSON null. This example shows a typical JSON response structure with NULLs. ```json { "success": true, "columns": ["id", "description"], "columnTypes": ["INTEGER", "VARCHAR"], "rows": [ [1, "description"], [2, null], [3, "another description"] ], "rowCount": 3 } ``` -------------------------------- ### Switch Database Connection Tool Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md Enables switching the database connection to a different path. Supports read-only mode and creating the database if it doesn't exist. ```python # File: tools/switch_database_connection.py def switch_database_connection( path: str, db_client: Any, server_read_only: bool = False, create_if_not_exists: bool = False, ) -> dict[str, Any] DESCRIPTION: str ``` ```python def _is_local_file_path(path: str) -> bool def _validate_path(path: str) -> str | None ``` -------------------------------- ### List Tables using Client Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Lists tables within a specified database, returning their names and types. Assumes the client is initialized and connected. ```python # List tables result = client.call_tool("list_tables", {"database": "memory"}) for table in result["tables"]: print(f"{table['name']} ({table['type']})") ``` -------------------------------- ### Init SQL Execution Failed Error Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md This error occurs if the SQL statements provided during initialization fail to execute. Verify the SQL syntax, ensure referenced tables/schemas exist, and check file permissions if an init SQL file is used. ```bash ValueError: Init SQL execution failed: ``` -------------------------------- ### Query Database and Get JSON Results Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/DatabaseClient.md Execute a SQL query and receive results formatted as a JSON-serializable dictionary. Handles success and error responses, and may truncate results. ```python result = client.query("SELECT * FROM my_table LIMIT 10") if result["success"]: for row in result["rows"]: print(row) else: print(f"Error: {result['error']}") ``` -------------------------------- ### Configure Local DuckDB Development Server Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/README.md Use this JSON configuration to set up a local development server for MCP Server MotherDuck, connecting to a local DuckDB instance. Ensure you replace `` with your actual token. ```json { "mcpServers": { "Local DuckDB (Dev)": { "command": "uv", "args": ["--directory", "/path/to/mcp-server-motherduck", "run", "mcp-server-motherduck", "--db-path", "md:"], "env": { "motherduck_token": "" } } } } ``` -------------------------------- ### Constraint Violation Example Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md This error occurs when data violates table constraints such as PRIMARY KEY, FOREIGN KEY, UNIQUE, or NOT NULL. Check the data being inserted or updated against the table's constraints. ```json { "success": false, "error": "Constraint Error: PRIMARY KEY constraint violation", "errorType": "ConstraintException" } ``` -------------------------------- ### Gemini CLI: Add MotherDuck (Read-Write) Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/README.md Connect the Gemini CLI to MotherDuck with read-write access. Remember to substitute YOUR_TOKEN with your actual MotherDuck token. ```bash gemini mcp add -s user -e motherduck_token=YOUR_TOKEN motherduck uvx mcp-server-motherduck --db-path md: --read-write ``` -------------------------------- ### MotherDuck Read-Only Token Requirement Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Illustrates the correct token usage for MotherDuck in read-only mode. It shows an error case with a read-write token and correct examples using a read-scaling token or read-write mode. ```bash # ✗ Error: MotherDuck requires read-scaling token for read-only mode mcp-server-motherduck --db-path "md:" --motherduck-token "rw_token" ``` ```bash # ✓ Correct: Use read-scaling token mcp-server-motherduck --db-path "md:" --motherduck-token "rs_token" ``` ```bash # ✓ Correct: Use read-write mode with regular token mcp-server-motherduck --db-path "md:" --motherduck-token "rw_token" --read-write ``` -------------------------------- ### DatabaseClient Constructor Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/DatabaseClient.md Initializes a new DatabaseClient instance, allowing configuration for database connections, authentication, and query behavior. ```APIDOC ## DatabaseClient() ### Description Initializes a new DatabaseClient instance. This client can connect to DuckDB, MotherDuck, and S3-hosted databases with various configuration options. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **db_path** (`str | None`) - Optional - Default: `None` - Database connection path: `:memory:`, `md:`, `s3://` URL, or absolute local file path - **motherduck_token** (`str | None`) - Optional - Default: `None` - MotherDuck authentication token (can use env var `motherduck_token` or `MOTHERDUCK_TOKEN`) - **home_dir** (`str | None`) - Optional - Default: `None` - Override HOME directory for DuckDB extensions and config - **saas_mode** (`bool`) - Optional - Default: `False` - Enable MotherDuck SaaS mode (restricts local filesystem access) - **read_only** (`bool`) - Optional - Default: `False` - Enable read-only mode for safety - **ephemeral_connections** (`bool`) - Optional - Default: `True` - Use temporary connections for read-only local files (allows concurrent access) - **max_rows** (`int`) - Optional - Default: `1024` - Maximum number of rows returned from queries - **max_chars** (`int`) - Optional - Default: `50000` - Maximum characters in query results (larger results truncated) - **query_timeout** (`int`) - Optional - Default: `-1` - Query timeout in seconds (-1 disables timeout) - **init_sql** (`str | None`) - Optional - Default: `None` - SQL file path or SQL string to execute on connection startup - **motherduck_connection_parameters** (`str | None`) - Optional - Default: `None` - Additional MotherDuck connection parameters as `key=value` pairs separated by `&` ### Request Example ```python # In-memory database (read-write) client = DatabaseClient(db_path=":memory:", read_write=False) # Local DuckDB file (read-only with ephemeral connections) client = DatabaseClient( db_path="/absolute/path/to/database.duckdb", read_only=True, ephemeral_connections=True ) # MotherDuck (read-write) client = DatabaseClient( db_path="md:", motherduck_token="your_token_here", read_only=False ) # S3-hosted DuckDB (read-only) client = DatabaseClient( db_path="s3://bucket-name/path/to/database.duckdb", read_only=True ) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Cannot Create Database in Read-Only Mode Error Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md This error occurs when trying to create a new database file with 'create_if_not_exists=True' while the server is in read-only mode. Start the server with the '--read-write' flag to enable database creation. ```json { "success": false, "error": "Cannot create new database file in read-only mode. The server must be started with --read-write to create databases.", "errorType": "PermissionError" } ``` -------------------------------- ### Local File Path Validation Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Validates that local file paths used in `switch_database_connection` must be absolute paths. The first example shows an error with a relative path, and the second shows the correct absolute path usage. ```json # ✗ Error: Relative paths not allowed {"path": "./database.duckdb"} ``` ```json # ✓ Correct: Use absolute path {"path": "/absolute/path/to/database.duckdb"} ``` -------------------------------- ### Connect to MotherDuck (Read-Write) Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/README.md Connect to MotherDuck in read-write mode. Ensure you replace '' with your actual token. Refer to command-line parameters and security documentation for more options. ```json { "mcpServers": { "MotherDuck (local, r/w)": { "command": "uvx", "args": ["mcp-server-motherduck", "--db-path", "md:", "--read-write"], "env": { "motherduck_token": "" } } } } ``` -------------------------------- ### MCP Server CLI main() Function Signature Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/CLI_main.md This is the signature for the main() function, which is the CLI entry point for the MCP server. It accepts numerous options for configuring network, transport, database, access control, query limits, and features. ```python import click @click.command() @click.option(...) # (many options defined below) def main( port: int, host: str, transport: str, stateless_http: bool, db_path: str, motherduck_token: str | None, home_dir: str | None, motherduck_saas_mode: bool, read_write: bool, ephemeral_connections: bool, max_rows: int, max_chars: int, query_timeout: int, init_sql: str | None, allow_switch_databases: bool, motherduck_connection_parameters: str | None, saas_mode: bool, # Deprecated read_only: bool, # Deprecated json_response: bool, # Deprecated ) -> None: pass ``` -------------------------------- ### Execute Raw Query and Get Unformatted Results Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/DatabaseClient.md Execute a SQL query to retrieve raw column names, types, and all rows without JSON formatting or row limiting. Primarily used for internal catalog tools. ```python columns, types, rows = client.execute_raw("SELECT * FROM my_table") for i, col in enumerate(columns): print(f"{col}: {types[i]}") ``` -------------------------------- ### Connection Error Examples Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md These errors indicate issues accessing the database file, connecting to S3, authenticating with MotherDuck, or internal DuckDB connection problems. Verify file paths, AWS credentials, MotherDuck tokens, and network connectivity. ```json { "success": false, "error": "IO Error: Could not open file: /path/to/missing.duckdb", "errorType": "IOException" } ``` ```json { "success": false, "error": "Connection Error: Failed to authenticate with MotherDuck", "errorType": "ConnectionException" } ``` -------------------------------- ### Development: In-Memory Database Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Use this configuration for local development with an in-memory database. It provides full read-write access and allows switching databases. ```bash mcp-server-motherduck \ --db-path ":memory:" --read-write \ --allow-switch-databases \ --transport stdio ``` -------------------------------- ### Switch Database Connection using Client Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Switches the client's connection to a different database file path. Reports success and the new current database name. ```python result = client.call_tool("switch_database_connection", { "path": "/absolute/path/to/other.duckdb" }) if result["success"]: print(f"Switched to {result['currentDatabase']}") ``` -------------------------------- ### Invalid Input and Timeout Error Examples Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/errors.md These errors arise from invalid literal values, out-of-range values, incorrect date/time formats, or query execution timeouts. Correct data formats, optimize queries, increase the query timeout, or use `LIMIT`. ```json { "success": false, "error": "Invalid input: could not convert string to number", "errorType": "ValueError" } ``` ```json { "success": false, "error": "Query execution timed out after 30 seconds. Increase timeout with --query-timeout argument when starting the mcp server.", "errorType": "ValueError" } ``` -------------------------------- ### Base Instructions Template Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md Provides the base template string for server instructions. This constant is used internally for generating detailed instructions. ```python INSTRUCTIONS_BASE: str # Base instructions template ``` -------------------------------- ### List Columns in Current Schema Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Use this snippet to list columns for a table within the current database and schema context. Ensure the 'client' object is initialized. ```python result = client.call_tool("list_columns", {"table": "users"}) ``` -------------------------------- ### Add MCP Server MotherDuck to Claude Desktop Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Configuration JSON for adding the MotherDuck server to Claude Desktop. Specifies the command and arguments for launching the server. ```json { "mcpServers": { "DuckDB": { "command": "uvx", "args": [ "mcp-server-motherduck", "--db-path", ":memory:", "--read-write", "--allow-switch-databases" ] } } } ``` -------------------------------- ### Access Control Configuration Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Enable read-write access or configure ephemeral connections for read-only local files. ```bash mcp-server-motherduck \ --read-write \ --ephemeral-connections ``` -------------------------------- ### Run mcp-server-motherduck with MotherDuck SaaS Mode Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/CLI_main.md Use this command for production deployments where local filesystem access must be restricted. It connects to MotherDuck in SaaS mode with write access. ```bash mcp-server-motherduck \ --db-path "md:" \ --motherduck-saas-mode \ --motherduck-token "YOUR_TOKEN" \ --read-write ``` -------------------------------- ### DatabaseClient Class Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/MANIFEST.txt Documentation for the DatabaseClient class, including its constructor, public methods for database interaction, and connection management patterns. ```APIDOC ## DatabaseClient Class ### Description Provides methods to interact with the database, including querying, executing raw SQL, and switching databases. ### Methods - **query(sql: str)**: Executes a SQL query and returns the results. - **execute_raw(sql: str)**: Executes a raw SQL command. - **switch_database(database_name: str)**: Switches the current database connection. ``` -------------------------------- ### get_instructions Function Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/MANIFEST.txt Documentation for the instruction generation function, outlining its output structure, sections, and context-aware configurations. ```APIDOC ## get_instructions Function ### Description Generates instructions based on context-aware configurations, detailing the output structure and its various sections. ``` -------------------------------- ### Transport and Network Configuration Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/configuration.md Configure the transport type (stdio or http), host, port, and stateless HTTP mode. ```bash mcp-server-motherduck \ --transport http \ --host 0.0.0.0 \ --port 8000 \ --stateless-http ``` -------------------------------- ### List Databases Tool Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/API_EXPORTS.md A tool to list all available databases accessible via the provided database client. Returns a dictionary of database names. ```python # File: tools/list_databases.py def list_databases(db_client: Any) -> dict[str, Any] DESCRIPTION: str ``` -------------------------------- ### Add MCP Server MotherDuck to VS Code Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Instructions for adding the MotherDuck server to VS Code. Requires manual configuration in settings.json. ```bash # Install with install links from README, or manually: # ~/.vscode/settings.json - see README for exact config format ``` -------------------------------- ### Switch to MotherDuck database Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/tools.md Use this snippet to switch the active database connection to a MotherDuck database by specifying its name. ```python result = client.call_tool("switch_database_connection", { "path": "md:my_database" }) ``` -------------------------------- ### Execute SQL Query using Client Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Executes a SQL query against the connected database and handles success or error responses. Requires the client to be initialized. ```python # Execute a query result = client.call_tool("execute_query", { "sql": "SELECT * FROM users LIMIT 10" }) if result["success"]: print(f"Got {result['rowCount']} rows") else: print(f"Error: {result['error']}") ``` -------------------------------- ### Codex CLI: Add MotherDuck (Read-Write) Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/README.md Connect the Codex CLI to MotherDuck with read-write capabilities. Replace YOUR_TOKEN with your MotherDuck authentication token. ```bash codex mcp add motherduck --env motherduck_token=YOUR_TOKEN -- uvx mcp-server-motherduck --db-path md: --read-write ``` -------------------------------- ### Switch Database Connection Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/api-reference/create_mcp_server.md The switch_database_connection tool allows changing the active database connection. It supports various path formats and an option to create databases if they don't exist. ```python def switch_database_connection(path: str, create_if_not_exists: bool = False) -> str: ``` -------------------------------- ### Remote HTTP Access Server Configuration Source: https://github.com/motherduckdb/mcp-server-motherduck/blob/main/_autodocs/README.md Sets up the MCP server for remote HTTP access, connecting to MotherDuck, enabling read-write operations, and binding to a specific host and port. ```bash mcp-server-motherduck \ --db-path "md:" \ --motherduck-token "$MOTHERDUCK_TOKEN" \ --read-write \ --transport http \ --host 0.0.0.0 \ --port 8000 ```