### Install and Run MCP Server (stdio) Source: https://context7.com/mariadb/mcp/llms.txt Installs dependencies using uv and runs the MCP server with the default stdio transport for local AI desktop integration. ```bash # Install dependencies pip install uv uv lock && uv sync # Run with stdio transport (default) uv run src/server.py ``` -------------------------------- ### Example .env file without Embedding Support Source: https://github.com/mariadb/mcp/blob/main/README.md Configure MariaDB connection settings without enabling any embedding providers. This is a basic setup for database connectivity. ```dotenv DB_HOST=localhost DB_USER=your_db_user DB_PASSWORD=your_db_password DB_PORT=3306 DB_NAME=your_default_database MCP_READ_ONLY=true MCP_MAX_POOL_SIZE=10 ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/mariadb/mcp/blob/main/README.md Installs project dependencies using 'uv'. Run 'uv lock' first to ensure dependencies are locked. ```bash uv lock uv sync ``` -------------------------------- ### Run MariaDB MCP Server (Standard) Source: https://github.com/mariadb/mcp/blob/main/README.md Starts the MariaDB MCP server using 'uv run'. This is the default mode with standard input/output. ```bash uv run server.py ``` -------------------------------- ### Install uv Dependency Manager Source: https://github.com/mariadb/mcp/blob/main/README.md Installs the 'uv' dependency manager using pip. Ensure Python 3.11 is installed. ```bash pip install uv ``` -------------------------------- ### MCP Tool: list_databases Source: https://context7.com/mariadb/mcp/llms.txt Demonstrates how to use the `list_databases` tool to retrieve a list of all accessible databases from the MariaDB server. Requires server initialization and pool setup. ```python # Called by the AI assistant as an MCP tool; equivalent internal invocation: import asyncio from server import MariaDBServer async def demo(): server = MariaDBServer() await server.initialize_pool() databases = await server.list_databases() print(databases) # Expected output: ['information_schema', 'mydb', 'analytics', 'demo'] await server.close_pool() asyncio.run(demo()) ``` -------------------------------- ### Example .env file with SSL/TLS Enabled Source: https://github.com/mariadb/mcp/blob/main/README.md Configure MariaDB connection with SSL/TLS enabled for secure communication. Ensure certificate paths are correct and verification settings match your environment. ```dotenv DB_HOST=your-remote-host.com DB_USER=your_db_user DB_PASSWORD=your_db_password DB_PORT=3306 DB_NAME=your_default_database # Enable SSL DB_SSL=true DB_SSL_CA=~/.mysql/ca-cert.pem DB_SSL_CERT=~/.mysql/client-cert.pem DB_SSL_KEY=~/.mysql/client-key.pem DB_SSL_VERIFY_CERT=true DB_SSL_VERIFY_IDENTITY=false MCP_READ_ONLY=true MCP_MAX_POOL_SIZE=10 ``` -------------------------------- ### Execute Standard SQL Query Source: https://github.com/mariadb/mcp/blob/main/README.md Example of executing a standard SQL query with parameters using the 'execute_sql' tool. ```json { "tool": "execute_sql", "parameters": { "database_name": "test_db", "sql_query": "SELECT * FROM users WHERE id = %s", "parameters": [123] } } ``` -------------------------------- ### Create Vector Store Source: https://github.com/mariadb/mcp/blob/main/README.md Example of creating a new vector store using the 'create_vector_store' tool. Requires database name, desired vector store name, model name, and distance function. ```json { "tool": "create_vector_store", "parameters": { "database_name": "test_db", "vector_store_name": "my_vectors", "model_name": "text-embedding-3-small", "distance_function": "cosine" } } ``` -------------------------------- ### Run MariaDB MCP Server (HTTP Transport) Source: https://github.com/mariadb/mcp/blob/main/README.md Starts the MariaDB MCP server using 'uv run' with streamable HTTP transport. Specify host, port, and path. ```bash uv run server.py --transport http --host 127.0.0.1 --port 9001 --path /mcp ``` -------------------------------- ### Run MCP Server with HTTP Transport Source: https://context7.com/mariadb/mcp/llms.txt Starts the MCP MariaDB Server using the streamable HTTP transport, specifying host, port, and path. ```bash uv run src/server.py --transport http --host 127.0.0.1 --port 9001 --path /mcp ``` -------------------------------- ### Example .env file with Embedding Support (OpenAI) Source: https://github.com/mariadb/mcp/blob/main/README.md Configure MariaDB connection, embedding provider (OpenAI), and associated API keys. Ensure all required environment variables are set for your chosen embedding provider. ```dotenv DB_HOST=localhost DB_USER=your_db_user DB_PASSWORD=your_db_password DB_PORT=3306 DB_NAME=your_default_database MCP_READ_ONLY=true MCP_MAX_POOL_SIZE=10 EMBEDDING_PROVIDER=openai OPENAI_API_KEY=sk-... GEMINI_API_KEY=AI... HB_MODEL="BAAI/bge-m3" ``` -------------------------------- ### Run MCP Server with SSE Transport Source: https://context7.com/mariadb/mcp/llms.txt Starts the MCP MariaDB Server using the SSE (Server-Sent Events) transport, specifying host and port. ```bash uv run src/server.py --transport sse --host 127.0.0.1 --port 9001 ``` -------------------------------- ### Insert Documents into Vector Store Source: https://github.com/mariadb/mcp/blob/main/README.md Example of inserting documents into a vector store using the 'insert_docs_vector_store' tool. Includes sample text and optional metadata. ```json { "tool": "insert_docs_vector_store", "parameters": { "database_name": "test_db", "vector_store_name": "my_vectors", "documents": ["Sample text 1", "Sample text 2"], "metadata": [{"source": "doc1"}, {"source": "doc2"}] } } ``` -------------------------------- ### Run MariaDB MCP Server (SSE Transport) Source: https://github.com/mariadb/mcp/blob/main/README.md Starts the MariaDB MCP server using 'uv run' with Server-Sent Events (SSE) transport. Specify host and port. ```bash uv run server.py --transport sse --host 127.0.0.1 --port 9001 ``` -------------------------------- ### Get Table Schema with MCP Tool Source: https://context7.com/mariadb/mcp/llms.txt Retrieves the schema for a specific table, including column details. Raises FileNotFoundError if the table does not exist. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() schema = await server.get_table_schema("mydb", "users") print(schema) # Expected output: # { # 'id': {'type': 'int(11)', 'nullable': False, 'key': 'PRI', 'default': None, 'extra': 'auto_increment'}, # 'email': {'type': 'varchar(255)', 'nullable': False, 'key': 'UNI', 'default': None, 'extra': ''}, # 'created_at': {'type': 'datetime', 'nullable': True, 'key': '', 'default': None, 'extra': ''} # } await server.close_pool() ``` -------------------------------- ### Get Table Schema with Relations using MCP Tool Source: https://context7.com/mariadb/mcp/llms.txt Retrieves the full table schema, including foreign key relationships. Returns a dictionary with table name and columns. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() result = await server.get_table_schema_with_relations("mydb", "orders") print(result) # Expected output: # { # 'table_name': 'orders', # 'columns': { # 'id': {'type': 'int(11)', 'nullable': False, 'key': 'PRI', ..., 'foreign_key': None}, # 'user_id': { # 'type': 'int(11)', 'nullable': False, 'key': 'MUL', ..., # 'foreign_key': { # 'constraint_name': 'fk_orders_user', # 'referenced_table': 'users', # 'referenced_column': 'id', # 'on_update': 'CASCADE', # 'on_delete': 'RESTRICT' # } # } # } # } await server.close_pool() ``` -------------------------------- ### Perform Semantic Search on Vector Store Source: https://github.com/mariadb/mcp/blob/main/README.md Example of performing a semantic search on a vector store using the 'search_vector_store' tool. Specify the database, vector store name, user query, and number of results (k). ```json { "tool": "search_vector_store", "parameters": { "database_name": "test_db", "vector_store_name": "my_vectors", "user_query": "What is the capital of France?", "k": 5 } } ``` -------------------------------- ### MCP Tool: list_tables Source: https://context7.com/mariadb/mcp/llms.txt Demonstrates how to use the `list_tables` tool to retrieve a list of all tables within a specified database. Includes error handling for invalid database names. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() try: tables = await server.list_tables("mydb") print(tables) # Expected output: ['users', 'orders', 'products', 'categories'] except ValueError as e: print(f"Invalid database name: {e}") await server.close_pool() ``` -------------------------------- ### Run test_multi_statements.py with .env file Source: https://github.com/mariadb/mcp/blob/main/src/tests/README.md Recommended method to run the automated test script. It automatically loads credentials from a `.env` file. ```bash cp .env.example .env # 2. Edit .env and set your credentials # 3. Run the test - it will automatically load from .env uv run python src/tests/test_multi_statements.py ``` -------------------------------- ### Configure MariaDB Server via Direct Command (stdio) Source: https://github.com/mariadb/mcp/blob/main/README.md Configuration for integrating MariaDB MCP server using a direct command with stdio transport. Specifies the command, arguments, and environment file. ```json { "mcpServers": { "MariaDB_Server": { "command": "uv", "args": [ "--directory", "path/to/mariadb-mcp-server/", "run", "server.py" ], "envFile": "path/to/mcp-server-mariadb-vector/.env" } } } ``` -------------------------------- ### Create Database with MCP Tool Source: https://context7.com/mariadb/mcp/llms.txt Creates a new MariaDB database if it doesn't exist. Returns a status indicating success or if the database already exists. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() result = await server.create_database("new_project") print(result) # Success: {'status': 'success', 'message': "Database 'new_project' created successfully.", 'database_name': 'new_project'} result = await server.create_database("new_project") # already exists print(result) # {'status': 'exists', 'message': "Database 'new_project' already exists.", 'database_name': 'new_project'} await server.close_pool() ``` -------------------------------- ### Claude Desktop Configuration Source: https://context7.com/mariadb/mcp/llms.txt JSON configuration for integrating the MCP MariaDB Server with Claude Desktop using the stdio transport. ```json // claude_desktop_config.json — Claude Desktop integration { "mcpServers": { "MariaDB_Server": { "command": "uv", "args": [ "--directory", "/path/to/mariadb-mcp-server", "run", "src/server.py" ], "envFile": "/path/to/mariadb-mcp-server/.env" } } } ``` -------------------------------- ### Run MCP Server with Docker Source: https://context7.com/mariadb/mcp/llms.txt Builds and runs the MCP MariaDB Server using Docker Compose, or runs the container standalone connecting to an external MariaDB instance. ```bash # Build and run with Docker Compose (starts MariaDB 11 + MCP server) docker compose up --build # Or run the MCP container standalone (connect to external MariaDB) docker run -i --rm \ -e DB_HOST=host.docker.internal \ -e DB_PORT=3306 \ -e DB_USER=mcp_user \ -e DB_PASSWORD=secret \ -e DB_NAME=mydb \ -p 9001:9001 \ mariadb-mcp-server ``` -------------------------------- ### Run test_multi_statements.py with interactive prompts Source: https://github.com/mariadb/mcp/blob/main/src/tests/README.md Alternative method to run the automated test script. It will prompt for missing credentials interactively if not found in `.env` or environment variables. ```bash uv run python src/tests/test_multi_statements.py ``` -------------------------------- ### Create Vector Store in MariaDB Source: https://context7.com/mariadb/mcp/llms.txt Initializes a connection pool and creates a new vector store table. Requires EMBEDDING_PROVIDER to be set in .env. The model_name and distance_function parameters are optional. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() result = await server.create_vector_store( database_name="mydb", vector_store_name="product_docs", model_name="text-embedding-3-small", # optional; defaults to provider default distance_function="cosine" # optional; default is cosine ) print(result) # { # 'status': 'success', # 'message': "Vector store 'product_docs' created successfully in database 'mydb' with COSINE distance.", # 'database_name': 'mydb', # 'vector_store_name': 'product_docs' # } # Underlying DDL executed: # CREATE TABLE IF NOT EXISTS `product_docs` ( # id VARCHAR(36) NOT NULL DEFAULT UUID_v7() PRIMARY KEY, # document TEXT NOT NULL, # embedding VECTOR(1536) NOT NULL, # metadata JSON NOT NULL, # VECTOR INDEX (embedding) DISTANCE=COSINE # ); await server.close_pool() ``` -------------------------------- ### create_database Source: https://context7.com/mariadb/mcp/llms.txt Creates a new MariaDB database. If the database already exists, it returns an 'exists' status. ```APIDOC ## MCP Tool: `create_database` ### Description Creates a new MariaDB database if it does not already exist. Returns a status dict with `"success"` or `"exists"`. ### Method Signature `async def create_database(database_name: str) -> dict` ### Parameters #### Path Parameters - **database_name** (str) - Required - The name for the new database. ### Response Example ```json # Success: {'status': 'success', 'message': "Database 'new_project' created successfully.", 'database_name': 'new_project'} # Already exists: {'status': 'exists', 'message': "Database 'new_project' already exists.", 'database_name': 'new_project'} ``` ``` -------------------------------- ### Create Vector Store with MCP Tool Source: https://context7.com/mariadb/mcp/llms.txt Creates a MariaDB table with a vector store schema, including UUID v7 PK, TEXT document, VECTOR embedding, and JSON metadata. Supports 'cosine' or 'euclidean' distance functions. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() # Example for creating a vector store (requires EMBEDDING_PROVIDER) # await server.create_vector_store( # store_name="my_vector_store", # embedding_provider="openai", # or other provider # distance_function="cosine" # or "euclidean" # ) await server.close_pool() ``` -------------------------------- ### Execute SQL Query with MCP Tool Source: https://context7.com/mariadb/mcp/llms.txt Executes parameterized SQL queries, supporting SELECT, SHOW, and DESCRIBE. Blocks DML and DDL in read-only mode, raising PermissionError. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() # Simple SELECT rows = await server.execute_sql( sql_query="SELECT id, email, created_at FROM users WHERE id = %s", database_name="mydb", parameters=[42] ) print(rows) # [{'id': 42, 'email': 'alice@example.com', 'created_at': datetime(...)}] # Aggregation query stats = await server.execute_sql( sql_query="SELECT COUNT(*) AS total, MAX(created_at) AS latest FROM orders", database_name="mydb" ) print(stats) # [{'total': 1523, 'latest': datetime(2024, 11, 30, ...)}] # SHOW command indexes = await server.execute_sql( sql_query="SHOW INDEX FROM users", database_name="mydb" ) # Blocked in read-only mode — raises PermissionError try: await server.execute_sql("DELETE FROM users WHERE id = 1", "mydb") except PermissionError as e: print(e) # "Operation forbidden: Server is in read-only mode." await server.close_pool() ``` -------------------------------- ### Run test_multi_statements.py with exported environment variables Source: https://github.com/mariadb/mcp/blob/main/src/tests/README.md Method to run the automated test script by exporting credentials as environment variables before execution. ```bash export DB_HOST=localhost export DB_PORT=3306 export DB_USER=root export DB_PASSWORD=your_password export DB_NAME=test uv run python src/tests/test_multi_statements.py ``` -------------------------------- ### MCP MariaDB Server Configuration (.env) Source: https://context7.com/mariadb/mcp/llms.txt Environment variables for configuring the MariaDB connection, read-only enforcement, SSL/TLS, embedding providers, network access control, and logging. ```dotenv # .env — minimum required for standard SQL use DB_HOST=localhost DB_PORT=3306 DB_USER=mcp_user DB_PASSWORD=secret DB_NAME=mydb # Read-only enforcement (default: true) MCP_READ_ONLY=true MCP_MAX_POOL_SIZE=10 # Optional: SSL/TLS DB_SSL=true DB_SSL_CA=~/.mysql/ca-cert.pem DB_SSL_CERT=~/.mysql/client-cert.pem DB_SSL_KEY=~/.mysql/client-key.pem DB_SSL_VERIFY_CERT=true DB_SSL_VERIFY_IDENTITY=false # Optional: Enable vector/embedding tools (choose one provider) EMBEDDING_PROVIDER=openai # or: gemini, huggingface OPENAI_API_KEY=sk-... GEMINI_API_KEY=AI... Hf_MODEL=BAAI/bge-m3 # required when EMBEDDING_PROVIDER=huggingface # Optional: Network access control (SSE/HTTP transports only) ALLOWED_ORIGINS=http://localhost,https://myapp.com ALLOWED_HOSTS=localhost,127.0.0.1 # Optional: Logging LOG_LEVEL=INFO LOG_FILE=logs/mcp_server.log LOG_MAX_BYTES=10485760 LOG_BACKUP_COUNT=5 ``` -------------------------------- ### AI Client Configuration for HTTP Source: https://context7.com/mariadb/mcp/llms.txt JSON configuration for an AI client to connect to the MCP MariaDB Server via streamable HTTP transport. ```json { "servers": { "mariadb-mcp-server": { "url": "http://127.0.0.1:9001/mcp", "type": "streamable-http" } } } ``` -------------------------------- ### Configure MariaDB Server via Docker Container Source: https://github.com/mariadb/mcp/blob/main/README.md Configuration for running the MariaDB MCP server within a Docker container. Includes port mapping and environment variables for database connection. ```json { "servers": { "mariadb-mcp-server": { "command": "docker", "args": [ "run", "-i", "--rm", "-p", "9001:9001", "-e", "DB_HOST=", "-e", "DB_PORT=", "-e", "DB_USER=", "-e", "DB_PASSWORD=", "-e", "DB_NAME=", "mariadb-mcp-server", "python", "src/server.py", "--host", "0.0.0.0", "--transport", "stdio" ] } } } ``` -------------------------------- ### Run test_multi_statements.py with inline environment variable Source: https://github.com/mariadb/mcp/blob/main/src/tests/README.md Method to run the automated test script by specifying credentials directly as inline environment variables. ```bash DB_PASSWORD=your_password uv run python src/tests/test_multi_statements.py ``` -------------------------------- ### Standard Database Tools Source: https://github.com/mariadb/mcp/blob/main/README.md Tools for standard database operations like listing databases, tables, retrieving schemas, and executing read-only SQL queries. ```APIDOC ## list_databases ### Description Lists all accessible databases. ### Method APICALL ### Parameters _None_ ### Response #### Success Response (200) - **databases** (list of strings) - List of database names. ``` ```APIDOC ## list_tables ### Description Lists all tables in a specified database. ### Method APICALL ### Parameters #### Path Parameters - **database_name** (string) - Required - The name of the database. ### Response #### Success Response (200) - **tables** (list of strings) - List of table names. ``` ```APIDOC ## get_table_schema ### Description Retrieves schema for a table (columns, types, keys, etc.). ### Method APICALL ### Parameters #### Path Parameters - **database_name** (string) - Required - The name of the database. - **table_name** (string) - Required - The name of the table. ### Response #### Success Response (200) - **schema** (object) - Table schema details. ``` ```APIDOC ## get_table_schema_with_relations ### Description Retrieves schema with foreign key relations for a table. ### Method APICALL ### Parameters #### Path Parameters - **database_name** (string) - Required - The name of the database. - **table_name** (string) - Required - The name of the table. ### Response #### Success Response (200) - **schema** (object) - Table schema details including relations. ``` ```APIDOC ## execute_sql ### Description Executes a read-only SQL query (`SELECT`, `SHOW`, `DESCRIBE`). ### Method APICALL ### Parameters #### Request Body - **sql_query** (string) - Required - The SQL query to execute. - **database_name** (string) - Optional - The database to execute the query against. - **parameters** (list) - Optional - Parameters for the SQL query. ### Response #### Success Response (200) - **results** (list of objects) - The results of the SQL query. ### Note Enforces read-only mode if `MCP_READ_ONLY` is enabled. ``` ```APIDOC ## create_database ### Description Creates a new database if it doesn't exist. ### Method APICALL ### Parameters #### Request Body - **database_name** (string) - Required - The name of the database to create. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` -------------------------------- ### AI Client Configuration for SSE Source: https://context7.com/mariadb/mcp/llms.txt JSON configuration for an AI client to connect to the MCP MariaDB Server via SSE transport. ```json // AI client config for SSE { "servers": { "mariadb-mcp-server": { "url": "http://127.0.0.1:9001/sse", "type": "sse" } } } ``` -------------------------------- ### list_vector_stores Source: https://context7.com/mariadb/mcp/llms.txt Lists all tables in a database that qualify as vector stores. ```APIDOC ## list_vector_stores ### Description Lists all tables in a database that qualify as vector stores — tables having an indexed `embedding` column of type `VECTOR`. ### Method ```python async def list_vector_stores(database_name: str) ``` ### Parameters #### Path Parameters - **database_name** (str) - Required - The name of the database to list vector stores from. ### Request Example ```python stores = await server.list_vector_stores("mydb") ``` ### Response #### Success Response (200) - **stores** (list[str]) - A list of vector store names found in the database. #### Response Example ```json ['product_docs', 'support_tickets', 'knowledge_base'] ``` ### Notes Non-existent databases return an empty list without raising an exception. ``` -------------------------------- ### List Vector Stores in MariaDB Source: https://context7.com/mariadb/mcp/llms.txt Lists all tables in a specified database that are recognized as vector stores. Requires EMBEDDING_PROVIDER to be set. Returns an empty list if the database does not exist or contains no vector stores. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() stores = await server.list_vector_stores("mydb") print(stores) # ['product_docs', 'support_tickets', 'knowledge_base'] # Non-existent database returns empty list (no exception) stores = await server.list_vector_stores("nonexistent_db") print(stores) # [] await server.close_pool() ``` -------------------------------- ### Secure Database Connections with SafeConnection and SafePool Source: https://context7.com/mariadb/mcp/llms.txt These classes enhance security by disabling multi-statement SQL injection and optionally stripping LOCAL_FILES capability. Use `safe_connect` for direct connections and `create_safe_pool` for connection pools. ```python import asyncio from custom_connection import create_safe_pool, safe_connect async def demo(): # Direct safe connection (no MULTI_STATEMENTS, no LOCAL_FILES in read-only mode) conn = await safe_connect( host="localhost", port=3306, user="mcp_user", password="secret", db="mydb" ) async with conn.cursor() as cur: await cur.execute("SELECT VERSION()") row = await cur.fetchone() print(row) # ('10.11.x-MariaDB',) conn.close() # Pool with safety guarantees — all connections have MULTI_STATEMENTS disabled async with create_safe_pool( host="localhost", port=3306, user="mcp_user", password="secret", db="mydb", minsize=1, maxsize=5, pool_recycle=3600 ) as pool: async with pool.acquire() as conn: async with conn.cursor() as cur: # Multi-statement queries are blocked at the protocol level try: await cur.execute("SELECT 1; DROP TABLE users;") except Exception as e: print(f"Blocked: {e}") # Single statements work normally await cur.execute("SELECT COUNT(*) FROM users") print(await cur.fetchone()) # (42,) asyncio.run(demo()) ``` -------------------------------- ### execute_sql Source: https://context7.com/mariadb/mcp/llms.txt Executes a parameterized SQL query (SELECT, SHOW, DESCRIBE) against a database using %s placeholders. In read-only mode, it blocks write operations. ```APIDOC ## MCP Tool: `execute_sql` ### Description Executes a parameterized SQL query (`SELECT`, `SHOW`, `DESCRIBE`) against a database. Supports `%s` placeholders. In read-only mode, blocks `INSERT`, `UPDATE`, `DELETE`, DDL statements, `LOAD_FILE()`, and `SELECT INTO OUTFILE/DUMPFILE`. ### Method Signature `async def execute_sql(sql_query: str, database_name: str, parameters: list = None) -> list` ### Parameters #### Body Parameters - **sql_query** (str) - Required - The SQL query to execute. - **database_name** (str) - Required - The name of the database to execute the query against. - **parameters** (list, optional) - A list of parameters to substitute into the SQL query using `%s` placeholders. ### Request Example ```python # Simple SELECT await server.execute_sql(sql_query="SELECT id, email, created_at FROM users WHERE id = %s", database_name="mydb", parameters=[42]) # Aggregation query await server.execute_sql(sql_query="SELECT COUNT(*) AS total, MAX(created_at) AS latest FROM orders", database_name="mydb") # SHOW command await server.execute_sql(sql_query="SHOW INDEX FROM users", database_name="mydb") ``` ### Response Example ```json # For SELECT query: [{'id': 42, 'email': 'alice@example.com', 'created_at': datetime(...) }] # For Aggregation query: [{'total': 1523, 'latest': datetime(2024, 11, 30, ...)}] # For SHOW command: # [{'column1': 'value1', 'column2': 'value2'}] ``` ### Error Handling - Raises `PermissionError` if attempting to execute a write operation in read-only mode. ``` -------------------------------- ### create_vector_store Source: https://context7.com/mariadb/mcp/llms.txt Creates a new vector store in the specified database. Optionally, you can specify the model name and distance function. ```APIDOC ## create_vector_store ### Description Creates a new vector store in the specified database. Optionally, you can specify the model name and distance function. ### Method ```python async def create_vector_store( database_name: str, vector_store_name: str, model_name: str = None, # optional; defaults to provider default distance_function: str = "cosine" # optional; default is cosine ) ``` ### Parameters #### Path Parameters - **database_name** (str) - Required - The name of the database. - **vector_store_name** (str) - Required - The name of the vector store to create. - **model_name** (str) - Optional - The name of the embedding model to use. - **distance_function** (str) - Optional - The distance function to use (e.g., 'cosine'). Defaults to 'cosine'. ### Request Example ```python result = await server.create_vector_store( database_name="mydb", vector_store_name="product_docs", model_name="text-embedding-3-small", distance_function="cosine" ) ``` ### Response #### Success Response (200) - **status** (str) - Indicates the status of the operation (e.g., 'success'). - **message** (str) - A confirmation message. - **database_name** (str) - The name of the database where the vector store was created. - **vector_store_name** (str) - The name of the created vector store. #### Response Example ```json { "status": "success", "message": "Vector store 'product_docs' created successfully in database 'mydb' with COSINE distance.", "database_name": "mydb", "vector_store_name": "product_docs" } ``` ``` -------------------------------- ### Vector Store & Embedding Tools Source: https://github.com/mariadb/mcp/blob/main/README.md Tools for managing vector stores and performing semantic searches, available when an embedding provider is configured. ```APIDOC ## create_vector_store ### Description Creates a new vector store (table) for embeddings. ### Method APICALL ### Parameters #### Request Body - **database_name** (string) - Required - The name of the database. - **vector_store_name** (string) - Required - The name of the vector store. - **model_name** (string) - Optional - The name of the embedding model. - **distance_function** (string) - Optional - The distance function to use (default: cosine). ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` ```APIDOC ## delete_vector_store ### Description Deletes a vector store (table). ### Method APICALL ### Parameters #### Request Body - **database_name** (string) - Required - The name of the database. - **vector_store_name** (string) - Required - The name of the vector store to delete. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` ```APIDOC ## list_vector_stores ### Description Lists all vector stores in a database. ### Method APICALL ### Parameters #### Path Parameters - **database_name** (string) - Required - The name of the database. ### Response #### Success Response (200) - **vector_stores** (list of strings) - List of vector store names. ``` ```APIDOC ## insert_docs_vector_store ### Description Batch inserts documents (and optional metadata) into a vector store. ### Method APICALL ### Parameters #### Request Body - **database_name** (string) - Required - The name of the database. - **vector_store_name** (string) - Required - The name of the vector store. - **documents** (list of strings) - Required - The documents to insert. - **metadata** (list of objects) - Optional - Metadata for each document. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` ```APIDOC ## search_vector_store ### Description Performs semantic search for similar documents using embeddings. ### Method APICALL ### Parameters #### Request Body - **database_name** (string) - Required - The name of the database. - **vector_store_name** (string) - Required - The name of the vector store. - **user_query** (string) - Required - The user's search query. - **k** (integer) - Optional - The number of results to return (default: 7). ### Response #### Success Response (200) - **results** (list of objects) - Search results, including similar documents. ``` -------------------------------- ### Perform Semantic Search with `search_vector_store` Source: https://context7.com/mariadb/mcp/llms.txt Use this function to perform semantic similarity searches over a vector store. It requires the EMBEDDING_PROVIDER to be set. The results are ordered by cosine distance and limited by k. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() results = await server.search_vector_store( user_query="How does vector similarity search work?", database_name="mydb", vector_store_name="knowledge_base", k=3 # number of top results; default is 7 ) for row in results: print(f"[distance={row['distance']:.4f}] {row['document'][:80]}") print(f" metadata: {row['metadata']}") # [distance=0.0812] Cosine similarity measures the angle between two embedding vectors. # metadata: {'source': 'ml_primer', 'page': 12} # [distance=0.1543] MariaDB supports native vector storage via the VECTOR column type. # metadata: {'source': 'mariadb_docs', 'page': 1} # [distance=0.2301] The MCP protocol allows AI assistants to call external tools. # metadata: {'source': 'mcp_spec', 'page': 5} await server.close_pool() ``` -------------------------------- ### insert_docs_vector_store Source: https://context7.com/mariadb/mcp/llms.txt Batch-inserts documents and optional metadata into a vector store, generating embeddings. ```APIDOC ## insert_docs_vector_store ### Description Batch-inserts documents (and optional metadata) into a vector store. Generates embeddings for each document using the configured provider, then inserts via `VEC_FromText()`. Returns a status dict with insertion count and any per-row errors. ### Method ```python async def insert_docs_vector_store( database_name: str, vector_store_name: str, documents: list[str], metadata: list[dict] = None # optional; defaults to [{}] per document ) ``` ### Parameters #### Path Parameters - **database_name** (str) - Required - The name of the database containing the vector store. - **vector_store_name** (str) - Required - The name of the vector store to insert documents into. - **documents** (list[str]) - Required - A list of documents to insert. - **metadata** (list[dict]) - Optional - A list of metadata dictionaries, one for each document. Defaults to an empty dictionary for each document if not provided. ### Request Example ```python documents = [ "MariaDB supports native vector storage via the VECTOR column type.", "The MCP protocol allows AI assistants to call external tools.", "Cosine similarity measures the angle between two embedding vectors." ] metadata = [ {"source": "mariadb_docs", "page": 1}, {"source": "mcp_spec", "page": 5}, {"source": "ml_primer", "page": 12} ] result = await server.insert_docs_vector_store( database_name="mydb", vector_store_name="knowledge_base", documents=documents, metadata=metadata ) ``` ### Response #### Success Response (200) - **status** (str) - Indicates the status of the operation (e.g., 'success', 'partial'). - **inserted** (int) - The number of documents successfully inserted. - **errors** (list[str]) - Optional. A list of error messages if the status is 'partial'. #### Response Example ```json {'status': 'success', 'inserted': 3} ``` #### Partial Failure Response Example ```json {'status': 'partial', 'inserted': 2, 'errors': ['...error message...']} ``` ``` -------------------------------- ### Insert Documents into Vector Store Source: https://context7.com/mariadb/mcp/llms.txt Performs a batch insertion of documents and optional metadata into a specified vector store. Embeddings are generated using the configured provider. Requires EMBEDDING_PROVIDER to be set. Returns a status indicating success, partial success, or failure, along with the count of inserted documents. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() documents = [ "MariaDB supports native vector storage via the VECTOR column type.", "The MCP protocol allows AI assistants to call external tools.", "Cosine similarity measures the angle between two embedding vectors." ] metadata = [ {"source": "mariadb_docs", "page": 1}, {"source": "mcp_spec", "page": 5}, {"source": "ml_primer", "page": 12} ] result = await server.insert_docs_vector_store( database_name="mydb", vector_store_name="knowledge_base", documents=documents, metadata=metadata # optional; defaults to [{}] per document ) print(result) # {'status': 'success', 'inserted': 3} # On partial failure: {'status': 'partial', 'inserted': 2, 'errors': ['...error message...']} await server.close_pool() ``` -------------------------------- ### Configure MariaDB Server via SSE Transport Source: https://github.com/mariadb/mcp/blob/main/README.md Configuration for integrating MariaDB MCP server using SSE transport. Specifies the server URL and type. ```json { "servers": { "mariadb-mcp-server": { "url": "http://{host}:9001/sse", "type": "sse" } } } ``` -------------------------------- ### Configure MariaDB Server via HTTP Transport Source: https://github.com/mariadb/mcp/blob/main/README.md Configuration for integrating MariaDB MCP server using streamable HTTP transport. Specifies the server URL and type. ```json { "servers": { "mariadb-mcp-server": { "url": "http://{host}:9001/mcp", "type": "streamable-http" } } } ``` -------------------------------- ### get_table_schema_with_relations Source: https://context7.com/mariadb/mcp/llms.txt Retrieves the full table schema including foreign key relationships, such as constraint name, referenced table/column, and ON UPDATE/ON DELETE rules. Returns a dictionary with 'table_name' and 'columns' keys. ```APIDOC ## MCP Tool: `get_table_schema_with_relations` ### Description Retrieves full table schema including foreign key relationships (constraint name, referenced table/column, `ON UPDATE`/`ON DELETE` rules). Returns a dict with `table_name` and `columns` keys. ### Method Signature `async def get_table_schema_with_relations(database_name: str, table_name: str) -> dict` ### Parameters #### Path Parameters - **database_name** (str) - Required - The name of the database. - **table_name** (str) - Required - The name of the table. ### Response Example ```json { "table_name": "orders", "columns": { "id": {"type": "int(11)", "nullable": false, "key": "PRI", "foreign_key": null}, "user_id": { "type": "int(11)", "nullable": false, "key": "MUL", "foreign_key": { "constraint_name": "fk_orders_user", "referenced_table": "users", "referenced_column": "id", "on_update": "CASCADE", "on_delete": "RESTRICT" } } } } ``` ``` -------------------------------- ### get_table_schema Source: https://context7.com/mariadb/mcp/llms.txt Retrieves the schema for a specific table, including column names, data types, nullability, key type, default values, and extras like auto_increment. Raises FileNotFoundError if the table does not exist. ```APIDOC ## MCP Tool: `get_table_schema` ### Description Retrieves the schema for a specific table — column names, data types, nullability, key type, default values, and extras (e.g., `auto_increment`). Raises `FileNotFoundError` if the table does not exist. ### Method Signature `async def get_table_schema(database_name: str, table_name: str) -> dict` ### Parameters #### Path Parameters - **database_name** (str) - Required - The name of the database. - **table_name** (str) - Required - The name of the table. ### Response Example ```json { "id": {"type": "int(11)", "nullable": false, "key": "PRI", "default": null, "extra": "auto_increment"}, "email": {"type": "varchar(255)", "nullable": false, "key": "UNI", "default": null, "extra": ""}, "created_at": {"type": "datetime", "nullable": true, "key": "", "default": null, "extra": ""} } ``` ``` -------------------------------- ### Utilize EmbeddingService for Text Embeddings Source: https://context7.com/mariadb/mcp/llms.txt The EmbeddingService generates text embeddings and looks up vector dimensions. It supports multiple providers and models. Ensure EMBEDDING_PROVIDER is set for instantiation. It raises a ValueError for disallowed models. ```python import asyncio from embeddings import EmbeddingService # Provider selected via EMBEDDING_PROVIDER env var async def demo(): svc = EmbeddingService() # Inspect available models print(svc.get_default_model()) # e.g. "text-embedding-3-small" print(svc.get_allowed_models()) # e.g. ["text-embedding-3-small", "text-embedding-3-large"] # Get vector dimension for a model dim = await svc.get_embedding_dimension("text-embedding-3-small") print(dim) # 1536 # Embed a single string → List[float] vector = await svc.embed("What is the capital of France?") print(len(vector), type(vector[0])) # 1536 # Embed a batch → List[List[float]] vectors = await svc.embed( ["Paris is the capital of France.", "Berlin is in Germany."], model_name="text-embedding-3-large" # override default model ) print(len(vectors), len(vectors[0])) # 2 3072 # ValueError on disallowed model try: await svc.embed("test", model_name="gpt-4") except ValueError as e: print(e) # "Model 'gpt-4' is not allowed..." asyncio.run(demo()) ``` -------------------------------- ### delete_vector_store Source: https://context7.com/mariadb/mcp/llms.txt Drops a vector store table after validating it is a genuine vector store. ```APIDOC ## delete_vector_store ### Description Drops a vector store table. Validates that the table exists and is a genuine vector store (has an indexed `VECTOR` column named `embedding`) before dropping. ### Method ```python async def delete_vector_store(database_name: str, vector_store_name: str) ``` ### Parameters #### Path Parameters - **database_name** (str) - Required - The name of the database containing the vector store. - **vector_store_name** (str) - Required - The name of the vector store to delete. ### Request Example ```python result = await server.delete_vector_store("mydb", "product_docs") ``` ### Response #### Success Response (200) - **status** (str) - Indicates the status of the operation (e.g., 'success'). - **message** (str) - A confirmation message. #### Response Example ```json {'status': 'success', 'message': "Vector store 'product_docs' deleted successfully...", ...} ``` ### Error Handling - **status: not_found** - If the specified table does not exist. - **status: not_vector_store** - If the specified table exists but is not a valid vector store. ``` -------------------------------- ### Delete Vector Store in MariaDB Source: https://context7.com/mariadb/mcp/llms.txt Drops a specified vector store table from a database. Requires EMBEDDING_PROVIDER to be set. The function validates that the table exists and is a vector store before deletion. Handles cases where the table does not exist or is not a valid vector store. ```python async def demo(): server = MariaDBServer() await server.initialize_pool() result = await server.delete_vector_store("mydb", "product_docs") print(result) # {'status': 'success', 'message': "Vector store 'product_docs' deleted successfully...", ...} # Table doesn't exist result = await server.delete_vector_store("mydb", "nonexistent") print(result) # {'status': 'not_found', 'message': "...'nonexistent' does not exist...", 'type': 'table'} # Table exists but is not a vector store result = await server.delete_vector_store("mydb", "regular_table") print(result) # {'status': 'not_vector_store', 'message': "Table 'regular_table'...is not a valid vector store..."} await server.close_pool() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.