mcp-server-motherduck

repository·main·Indexed 19 days ago

https://github.com/motherduckdb/mcp-server-motherduck

A Model Context Protocol (MCP) server that connects AI assistants and IDEs to DuckDB and MotherDuck. It enables users to execute SQL queries, browse database catalogs, and manage data across local files, S3, and MotherDuck. The server provides tools such as execute_query, list_databases, list_tables, and list_columns, and supports integration with clients like Claude Desktop, Cursor, and VS Code.

Tokens
8.4K
Snippets
23
Records
31
Agent score
67%

What's inside mcp-server-motherduck

  1. Quick Start: Connect to MotherDuck in Read-Write Mode

    main

    Connect to MotherDuck with read-write access. You must provide your MotherDuck token via the motherduck_token environment variable.

    {
      "mcpServers": {
        "MotherDuck (local, r/w)": {
          "command": "uvx",
          "args": ["mcp-server-motherduck", "--db-path", "md:", "--read-write"],
          "env": {
            "motherduck_token": "<YOUR_MOTHERDUCK_TOKEN>"
          }
        }
      }
    }
  2. Run the MCP Server with Docker

    main

    You can build and run the server using Docker. By default, it runs with an in-memory DuckDB. To connect to MotherDuck, pass the token as an environment variable and override the command to use the HTTP transport.

    # Build and run with default in-memory DuckDB on port 8000
    docker build -t mcp-server-motherduck .
    docker run --rm -p 8000:8000 mcp-server-motherduck
    
    # Connect to MotherDuck via HTTP
    docker run --rm -p 8000:8000 \
      -e motherduck_token="$MOTHERDUCK_TOKEN" \
      mcp-server-motherduck --transport http --db-path md:
  3. Quick Start: Connect to In-Memory DuckDB (Dev Mode)

    main

    For development with full flexibility, connect to an in-memory DuckDB instance. This mode provides read-write access and allows switching between different databases (local files, S3, or MotherDuck) at runtime using the --allow-switch-databases flag.

    {
      "mcpServers": {
        "DuckDB (in-memory, r/w)": {
          "command": "uvx",
          "args": ["mcp-server-motherduck", "--db-path", ":memory:", "--read-write", "--allow-switch-databases"]
        }
      }
    }
  4. Configure MCP Clients (Claude, Cursor, VS Code, etc.)

    main

    The server can be integrated into various MCP-compatible clients. Most clients require adding a JSON configuration block.

    Common Client Config Locations:

    • Claude Desktop: Settings → Developer → Edit Config
    • Cursor: Settings → MCP → Add new global MCP server
    • VS Code: User Settings (JSON)
    • Kiro: ~/.kiro/settings/mcp.json (global) or .kiro/settings/mcp.json (project)

    For CLI-based clients like Claude Code, Codex, or Gemini, use the specific mcp add commands provided in the documentation.

  5. Quick Start: Connect to a Local DuckDB File in Read-Only Mode

    main

    Connect to a specific local DuckDB file in read-only mode. This mode does not hold a file lock, allowing you to use it alongside other write connections to the same file. You can also use S3 URLs (e.g., s3://bucket/path.duckdb) for remote files.

    {
      "mcpServers": {
        "DuckDB (read-only)": {
          "command": "uvx",
          "args": ["mcp-server-motherduck", "--db-path", "/absolute/path/to/your.duckdb"]
        }
      }
    }
  6. Connect to S3 databases via DatabaseClient

    main

    The DatabaseClient supports connecting to S3 via s3:// paths. When an S3 path is provided, the client automatically:

    1. Creates an in-memory DuckDB connection.
    2. Installs and loads the httpfs extension.
    3. Configures S3 credentials using CREATE SECRET based on available environment variables:
      • AWS_ACCESS_KEY_ID
      • AWS_SECRET_ACCESS_KEY
      • AWS_SESSION_TOKEN (if present, uses credential_chain provider)
      • AWS_DEFAULT_REGION (defaults to us-east-1)
      • AWS_ENDPOINT
    4. Attaches the S3 path as a database named s3db (typically in READ_ONLY mode).
  7. Persist In-Memory Data to a Local File

    main

    If you are working with an in-memory database (:memory:) and want to save your work to a persistent file, use the ATTACH and COPY commands:

    1. Attach a new file-based database.
    2. Copy data from the memory database to the attached database.
    3. Detach the database when finished.
    -- 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;
  8. DuckDB SQL Syntax and Querying Guide

    main

    The server uses DuckDB SQL syntax. Key features include:

    Name Qualification

    • Format: database.schema.table, schema.table, or table.
    • The default schema is main (e.g., db.table is equivalent to db.main.table).
    • Use fully qualified names when joining tables across different databases.

    Identifiers and Literals

    • Use double quotes (") for identifiers with spaces, special characters, or case-sensitivity.
    • Use single quotes (') for string literals.

    Advanced Querying

    • Flexible Structure: Queries can start with FROM (e.g., FROM my_table WHERE condition;) or use SELECT without FROM for expressions.
    • Column Selection:
      • Exclude columns: SELECT * EXCLUDE (col_name) FROM table;
      • Replace columns: SELECT * REPLACE (new_val AS col_name) FROM table;
      • Pattern matching: SELECT COLUMNS('pattern.*') FROM table;
    • Grouping/Ordering:
      • GROUP BY ALL groups by all non-aggregated columns.
      • ORDER BY ALL orders by all columns.

    Complex Data Types

    • Lists: [1, 2, 3]
    • Structs: {'a': 1, 'b': 'text'}
    • Maps: MAP([1,2],['one','two'])
    • JSON: Use ->> for text extraction (json_col->>'key') or -> for JSON extraction (data->'$.user.id').

    Date/Time Operations

    • String to timestamp: strptime('2023-07-23', '%Y-%m-%d')::TIMESTAMP
    • Format timestamp: strftime(NOW(), '%Y-%m-%d')
    • Extract parts: EXTRACT(YEAR FROM DATE '2023-07-23')
  9. Troubleshoot MotherDuck MCP issues

    main

    If you encounter issues while running the server, check the following common scenarios:

    • spawn uvx ENOENT error: The system cannot find the uvx executable. Resolve this by specifying the full absolute path to uvx. You can find the path by running which uvx in your terminal.
    • File locked error: This typically happens when a database file is already in use. Ensure that --ephemeral-connections is enabled (this is the default setting: true) and verify that you are not attempting to connect in read-write mode while another process holds a lock.
  10. Run MotherDuck MCP from source (Development Mode)

    main

    To run the server directly from the source code for development purposes, configure your MCP client (e.g., Claude Desktop) with the following JSON configuration. Replace /path/to/mcp-server-motherduck with your actual local path and <YOUR_MOTHERDUCK_TOKEN> with your actual token.

    This configuration uses uv to run the server in an in-memory DuckDB mode (--db-path md:).

    {
      "mcpServers": {
        "Local DuckDB (Dev)": {
          "command": "uv",
          "args": ["--directory", "/path/to/mcp-server-motherduck", "run", "mcp-server-motherduck", "--db-path", "md:"],
          "env": {
            "motherduck_token": "<YOUR_MOTHERDUCK_TOKEN>"
          }
        }
      }
    }
  11. Available MCP Tools

    main

    The server exposes the following tools to the AI assistant. All tools return JSON. By default, results are limited to 1024 rows or 50,000 characters (configurable via --max-rows and --max-chars).

    ToolDescriptionRequired InputsOptional Inputs
    execute_queryExecute SQL query (DuckDB dialect)sql-
    list_databasesList all databases--
    list_tablesList tables and views-database, schema
    list_columnsList columns of a table/viewtabledatabase, schema
    switch_database_connection*Switch to different databasepathcreate_if_not_exists

    *Note: switch_database_connection requires the --allow-switch-databases flag to be enabled.

  12. Configure Environment Variables for MotherDuck MCP

    main

    The MotherDuck MCP server uses several environment variables for authentication and cloud connectivity.

    • Authentication: Use motherduck_token or MOTHERDUCK_TOKEN to provide your MotherDuck access token. This is an alternative to passing the --motherduck-token command-line flag.
    • DuckDB Configuration: DuckDB uses the HOME variable for extensions and configuration. If HOME is not set, you should use the --home-dir command-line flag to specify a directory.
    • AWS/S3 Connectivity: If you are connecting to S3-based databases, provide the following variables:
      • AWS_ACCESS_KEY_ID
      • AWS_SECRET_ACCESS_KEY
      • AWS_SESSION_TOKEN (for temporary credentials like IAM roles or SSO)
      • AWS_DEFAULT_REGION
      • AWS_ENDPOINT
    | Variable | Description |
    |----------|-------------|
    | `motherduck_token` or `MOTHERDUCK_TOKEN` | MotherDuck access token (alternative to `--motherduck-token`) |
    | `HOME` | Used by DuckDB for extensions and config. Override with `--home-dir` if not set. |
    | `AWS_ACCESS_KEY_ID` | AWS access key for S3 database connections |
    | `AWS_SECRET_ACCESS_KEY` | AWS secret key for S3 database connections |
    | `AWS_SESSION_TOKEN` | AWS session token for temporary credentials (IAM roles, SSO, EC2 instance profiles) |
    | `AWS_DEFAULT_REGION` | AWS region for S3 connections |
    | `AWS_ENDPOINT` | AWS endpoint for S3 connections |