AIStoreHub Package Vault: Chroma Vector Database MCP
Package Slug: mcp-server-chroma
Archetype: mcp_server
Upstream Repository: https://github.com/chroma-core/chroma-mcp
Workspace Files & Specifications (12 files)
- aistorehub.json (529 bytes)
{ "name": "Chroma Vector Database MCP", "slug": "mcp-server-chroma", "version": "1.0.0", "type": "mcp_server", "description": "Official Model Context Protocol server for Chroma, exposing semantic embeddings search, vector collection management, and document querying.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/chroma-core/chroma-mcp", "tags": [ "mcp", "rag", "chroma", "vector-db", "embeddings" ], "imported_at": "2026-11-22T00:08:37.995Z" } - CHANGELOG.md (2029 bytes)
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.2.6] - 08/14/2025 - Update chromadb to 1.0.16 - Add tool prompts for regex support - Add new `chroma_fork_collection` tool support ## [0.2.5] - 06/18/2025 - Update chromadb to 1.0.13 - Simplify configuration instantiation - Clarify list_collection success with no collections - Remove Optional parameters, replace with | None ## [0.2.4] - 05/21/2025 ### Changed - Update chromadb to v1.0.10 ## [0.2.2] - 04/08/2025 ### Changed - Update chromadb to v1.0.3 - Fix include on query and get to match chromadb Python client ## [0.2.1] - 04/03/2025 ### Added - The ability to select embedding functions when creating collections (default, cohere, openai, jina, voyageai, roboflow) ### Changed - Upgraded to v1.0.0 of Chroma - Fix dotenv path support during argparse ## [0.2.0] - 04/02/2025 ### Added - New `delete_document` tool for removing documents from collections - New `chroma_update_documents` tool for updating existing documents - Docker deployment support with Dockerfile - Smithery configuration for deployment - Environment variable support in Smithery config ### Changed - Improved error handling across tools - Removed sequential thinking in favor of more direct operations - SSL parsing improvements and fixes ### Security - Enhanced SSL handling and security configurations ## [0.1.11] - 02/21/2025 ### Changed - Version bump ## [0.1.10] - 02/21/2024 ### Added - Initial release - Support for ephemeral, persistent, HTTP, and cloud Chroma clients - Collection management tools - Document operations (add, query, get) - Claude Desktop integration - Environment variable support - Dotenv file support ### Security - SSL support for HTTP and cloud clients - Authentication support for HTTP clients - API key management for cloud deployments
- Dockerfile (482 bytes)
# Generated by https://smithery.ai. See: https://smithery.ai/docs/config#dockerfile FROM python:3.10-slim # set working directory WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends gcc # Copy project files COPY . /app # Install pip dependencies RUN python -m pip install --upgrade pip && \ pip install . # Expose any necessary ports if needed (e.g., 8080) EXPOSE 8080 # Command to run MCP server CMD ["chroma-mcp"] - glama.json (108 bytes)
{ "$schema": "https://glama.ai/mcp/schemas/server.json", "maintainers": [ "jairad26" ] } - INSTRUCTIONS.md (233 bytes)
Run via uvx (in-memory by default, or with HTTP client options): ```bash # In-memory ephemeral mode: uvx chroma-mcp # Or connect to a self-hosted Chroma HTTP server: uvx chroma-mcp --client-type http --host localhost --port 8000 ```
- LICENSE (11357 bytes)
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - pyproject.toml (1520 bytes)
[project] name = "chroma-mcp" version = "0.2.6" description = "Chroma MCP Server - Vector Database Integration for LLM Applications" readme = "README.md" requires-python = ">=3.10" license = "Apache-2.0" keywords = ["chroma", "mcp", "vector-database", "llm", "embeddings"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Topic :: Software Development :: Libraries :: Python Modules" ] dependencies = [ "chromadb>=1.0.16", "cohere>=5.14.2", "httpx>=0.28.1", "mcp[cli]==1.6.0", "openai>=1.70.0", "pillow>=11.1.0", "python-dotenv>=0.19.0", "typing-extensions>=4.13.1", "voyageai>=0.3.2", ] [project.urls] Homepage = "https://github.com/chroma-core/chroma-mcp" Documentation = "https://github.com/chroma-core/chroma-mcp#readme" Issues = "https://github.com/chroma-core/chroma-mcp/issues" [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [project.scripts] chroma-mcp = "chroma_mcp:main" [project.optional-dependencies] sentence-transformers = ["sentence-transformers>=4.1.0"] test = [ "pytest>=8.3.5", "pytest-asyncio>=0.26.0", "pytest-cov>=4.1.0", ] [tool.pytest.ini_options] testpaths = ["tests"] python_files = ["test_*.py"] asyncio_default_fixture_loop_scope = "function" [tool.ruff] select = ["E", "F", "B", "I"] ignore = [] line-length = 100 - README.md (8049 bytes)
<p align="center"> <a href="https://trychroma.com"><img src="https://user-images.githubusercontent.com/891664/227103090-6624bf7d-9524-4e05-9d2c-c28d5d451481.png" alt="Chroma logo"></a> </p> <p align="center"> <b>Chroma - the open-source embedding database</b>. <br /> The fastest way to build Python or JavaScript LLM apps with memory! </p> <p align="center"> <a href="https://discord.gg/MMeYNTmh3x" target="_blank"> <img src="https://img.shields.io/discord/1073293645303795742?cacheSeconds=3600" alt="Discord"> </a> | <a href="https://github.com/chroma-core/chroma/blob/master/LICENSE" target="_blank"> <img src="https://img.shields.io/static/v1?label=license&message=Apache 2.0&color=white" alt="License"> </a> | <a href="https://docs.trychroma.com/" target="_blank"> Docs </a> | <a href="https://www.trychroma.com/" target="_blank"> Homepage </a> </p> # Chroma MCP Server [](https://smithery.ai/server/@chroma-core/chroma-mcp) [The Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol designed for effortless integration between LLM applications and external data sources or tools, offering a standardized framework to seamlessly provide LLMs with the context they require. This server provides data retrieval capabilities powered by Chroma, enabling AI models to create collections over generated data and user inputs, and retrieve that data using vector search, full text search, metadata filtering, and more. This is a MCP server for self-hosting your access to Chroma. If you are looking for [Package Search](https://www.trychroma.com/package-search) you can find the repository for that [here](https://github.com/chroma-core/package-search). ## Features - **Flexible Client Types** - Ephemeral (in-memory) for testing and development - Persistent for file-based storage - HTTP client for self-hosted Chroma instances - Cloud client for Chroma Cloud integration (automatically connects to api.trychroma.com) - **Collection Management** - Create, modify, and delete collections - List all collections with pagination support - Get collection information and statistics - Configure HNSW parameters for optimized vector search - Select embedding functions when creating collections - **Document Operations** - Add documents with optional metadata and custom IDs - Query documents using semantic search - Advanced filtering using metadata and document content - Retrieve documents by IDs or filters - Full text search capabilities ### Supported Tools - `chroma_list_collections` - List all collections with pagination support - `chroma_create_collection` - Create a new collection with optional HNSW configuration - `chroma_peek_collection` - View a sample of documents in a collection - `chroma_get_collection_info` - Get detailed information about a collection - `chroma_get_collection_count` - Get the number of documents in a collection - `chroma_modify_collection` - Update a collection's name or metadata - `chroma_delete_collection` - Delete a collection - `chroma_add_documents` - Add documents with optional metadata and custom IDs - `chroma_query_documents` - Query documents using semantic search with advanced filtering - `chroma_get_documents` - Retrieve documents by IDs or filters with pagination - `chroma_update_documents` - Update existing documents' content, metadata, or embeddings - `chroma_delete_documents` - Delete specific documents from a collection ### Embedding Functions Chroma MCP supports several embedding functions: `default`, `cohere`, `openai`, `jina`, `voyageai`, and `roboflow`. The embedding functions utilize Chroma's collection configuration, which persists the selected embedding function of a collection for retrieval. Once a collection is created using the collection configuration, on retrieval for future queries and inserts, the same embedding function will be used, without needing to specify the embedding function again. Embedding function persistance was added in v1.0.0 of Chroma, so if you created a collection using version <=0.6.3, this feature is not supported. When accessing embedding functions that utilize external APIs, please be sure to add the environment variable for the API key with the correct format, found in [Embedding Function Environment Variables](#embedding-function-environment-variables) ## Usage with Claude Desktop 1. To add an ephemeral client, add the following to your `claude_desktop_config.json` file: ```json "chroma": { "command": "uvx", "args": [ "chroma-mcp" ] } ``` 2. To add a persistent client, add the following to your `claude_desktop_config.json` file: ```json "chroma": { "command": "uvx", "args": [ "chroma-mcp", "--client-type", "persistent", "--data-dir", "/full/path/to/your/data/directory" ] } ``` This will create a persistent client that will use the data directory specified. 3. To connect to Chroma Cloud, add the following to your `claude_desktop_config.json` file: ```json "chroma": { "command": "uvx", "args": [ "chroma-mcp", "--client-type", "cloud", "--tenant", "your-tenant-id", "--database", "your-database-name", "--api-key", "your-api-key" ] } ``` This will create a cloud client that automatically connects to api.trychroma.com using SSL. **Note:** Adding API keys in arguments is fine on local devices, but for safety, you can also specify a custom path for your environment configuration file using the `--dotenv-path` argument within the `args` list, for example: `"args": ["chroma-mcp", "--dotenv-path", "/custom/path/.env"]`. 4. To connect to a [self-hosted Chroma instance on your own cloud provider](https://docs.trychroma.com/ production/deployment), add the following to your `claude_desktop_config.json` file: ```json "chroma": { "command": "uvx", "args": [ "chroma-mcp", "--client-type", "http", "--host", "your-host", "--port", "your-port", "--custom-auth-credentials", "your-custom-auth-credentials", "--ssl", "true" ] } ``` This will create an HTTP client that connects to your self-hosted Chroma instance. ### Demos Find reference usages, such as shared knowledge bases & adding memory to context windows in the [Chroma MCP Docs](https://docs.trychroma.com/integrations/frameworks/anthropic-mcp#using-chroma-with-claude) ### Using Environment Variables You can also use environment variables to configure the client. The server will automatically load variables from a `.env` file located at the path specified by `--dotenv-path` (defaults to `.chroma_env` in the working directory) or from system environment variables. Command-line arguments take precedence over environment variables. ```bash # Common variables export CHROMA_CLIENT_TYPE="http" # or "cloud", "persistent", "ephemeral" # For persistent client export CHROMA_DATA_DIR="/full/path/to/your/data/directory" # For cloud client (Chroma Cloud) export CHROMA_TENANT="your-tenant-id" export CHROMA_DATABASE="your-database-name" export CHROMA_API_KEY="your-api-key" # For HTTP client (self-hosted) export CHROMA_HOST="your-host" export CHROMA_PORT="your-port" export CHROMA_CUSTOM_AUTH_CREDENTIALS="your-custom-auth-credentials" export CHROMA_SSL="true" # Optional: Specify path to .env file (defaults to .chroma_env) export CHROMA_DOTENV_PATH="/path/to/your/.env" ``` #### Embedding Function Environment Variables When using external embedding functions that access an API key, follow the naming convention `CHROMA_<>_API_KEY="<key>"`. So to set a Cohere API key, set the environment variable `CHROMA_COHERE_API_KEY=""`. We recommend adding this to a .env file somewhere and using the `CHROMA_DOTENV_PATH` environment variable or `--dotenv-path` flag to set that location for safekeeping. - SECURITY.md (1019 bytes)
# Security Policy ## Supported Versions | Version | Supported | | ------- | ------------------ | | 0.1.x | :white_check_mark: | ## Reporting a Vulnerability If you discover a security vulnerability within Chroma MCP, please send an email to [your-email]. All security vulnerabilities will be promptly addressed. Please do not publicly disclose the issue until it has been addressed by the maintainers. ## Security Considerations 1. **API Keys and Credentials**: Never commit API keys, credentials, or sensitive configuration to version control. Use environment variables or `.env` files. 2. **SSL/TLS**: When using HTTP or cloud clients, SSL is strongly recommended. For cloud clients, SSL is enforced. 3. **Authentication**: When using HTTP clients, consider using authentication credentials to secure your Chroma instance. 4. **Environment Variables**: Sensitive configuration should be passed via environment variables rather than command line arguments to prevent exposure in process listings.
- smithery.yaml (1978 bytes)
# Smithery configuration file: https://smithery.ai/docs/config#smitheryyaml startCommand: type: stdio configSchema: # JSON Schema defining the configuration options for the MCP. type: object properties: clientType: type: string description: "The type of Chroma client to start: http, cloud, persistent, ephemeral" default: "ephemeral" dataDir: type: string description: "The directory to store the Chroma database if using the persistent client type" host: type: string description: "The host address of the Chroma server if using the http client type" port: type: number description: "The port number of the Chroma server if using the http client type" customAuthCredentials: type: string description: "The custom authentication credentials to use if using the http client type" tenant: type: string description: "The tenant name to use if using the cloud client type" database: type: string description: "The database name to use if using the cloud client type" apiKey: type: string description: "The API key to use if using the cloud client type" ssl: type: boolean description: "Whether to use SSL if using the http client type" default: true commandFunction: # A JS function that produces the CLI command based on the given config to start the MCP on stdio. |- (config) => ({ command: 'chroma-mcp', args: [], env: { CHROMA_CLIENT_TYPE: config.clientType, CHROMA_DATA_DIR: config.dataDir, CHROMA_HOST: config.host, CHROMA_PORT: config.port, CHROMA_CUSTOM_AUTH_CREDENTIALS: config.customAuthCredentials, CHROMA_TENANT: config.tenant, CHROMA_DATABASE: config.database, CHROMA_API_KEY: config.apiKey, CHROMA_SSL: config.ssl, } }) exampleConfig: {} - src/chroma_mcp/__init__.py (71 bytes)
# This file can be empty from .server import main __all__ = ["main"]
- src/chroma_mcp/server.py (26482 bytes)
from typing import Dict, List, TypedDict, Union from enum import Enum import chromadb from mcp.server.fastmcp import FastMCP import os from dotenv import load_dotenv import argparse from chromadb.config import Settings import ssl import uuid import time import json from typing_extensions import TypedDict from chromadb.api.collection_configuration import ( CreateCollectionConfiguration ) from chromadb.api import EmbeddingFunction from chromadb.utils.embedding_functions import ( DefaultEmbeddingFunction, CohereEmbeddingFunction, OpenAIEmbeddingFunction, JinaEmbeddingFunction, VoyageAIEmbeddingFunction, RoboflowEmbeddingFunction, ) # Initialize FastMCP server mcp = FastMCP("chroma") # Global variables _chroma_client = None def create_parser(): """Create and return the argument parser.""" parser = argparse.ArgumentParser(description='FastMCP server for Chroma DB') parser.add_argument('--client-type', choices=['http', 'cloud', 'persistent', 'ephemeral'], default=os.getenv('CHROMA_CLIENT_TYPE', 'ephemeral'), help='Type of Chroma client to use') parser.add_argument('--data-dir', default=os.getenv('CHROMA_DATA_DIR'), help='Directory for persistent client data (only used with persistent client)') parser.add_argument('--host', help='Chroma host (required for http client)', default=os.getenv('CHROMA_HOST')) parser.add_argument('--port', help='Chroma port (optional for http client)', default=os.getenv('CHROMA_PORT')) parser.add_argument('--custom-auth-credentials', help='Custom auth credentials (optional for http client)', default=os.getenv('CHROMA_CUSTOM_AUTH_CREDENTIALS')) parser.add_argument('--tenant', help='Chroma tenant (optional for http client)', default=os.getenv('CHROMA_TENANT')) parser.add_argument('--database', help='Chroma database (required if tenant is provided)', default=os.getenv('CHROMA_DATABASE')) parser.add_argument('--api-key', help='Chroma API key (required if tenant is provided)', default=os.getenv('CHROMA_API_KEY')) parser.add_argument('--ssl', help='Use SSL (optional for http client)', type=lambda x: x.lower() in ['true', 'yes', '1', 't', 'y'], default=os.getenv('CHROMA_SSL', 'true').lower() in ['true', 'yes', '1', 't', 'y']) parser.add_argument('--dotenv-path', help='Path to .env file', default=os.getenv('CHROMA_DOTENV_PATH', '.chroma_env')) return parser def get_chroma_client(args=None): """Get or create the global Chroma client instance.""" global _chroma_client if _chroma_client is None: if args is None: # Create parser and parse args if not provided parser = create_parser() args = parser.parse_args() # Load environment variables from .env file if it exists load_dotenv(dotenv_path=args.dotenv_path) if args.client_type == 'http': if not args.host: raise ValueError("Host must be provided via --host flag or CHROMA_HOST environment variable when using HTTP client") settings = Settings() if args.custom_auth_credentials: settings = Settings( chroma_client_auth_provider="chromadb.auth.basic_authn.BasicAuthClientProvider", chroma_client_auth_credentials=args.custom_auth_credentials ) # Handle SSL configuration try: _chroma_client = chromadb.HttpClient( host=args.host, port=args.port if args.port else None, ssl=args.ssl, settings=settings ) except ssl.SSLError as e: print(f"SSL connection failed: {str(e)}") raise except Exception as e: print(f"Error connecting to HTTP client: {str(e)}") raise elif args.client_type == 'cloud': if not args.tenant: raise ValueError("Tenant must be provided via --tenant flag or CHROMA_TENANT environment variable when using cloud client") if not args.database: raise ValueError("Database must be provided via --database flag or CHROMA_DATABASE environment variable when using cloud client") if not args.api_key: raise ValueError("API key must be provided via --api-key flag or CHROMA_API_KEY environment variable when using cloud client") try: _chroma_client = chromadb.HttpClient( host="api.trychroma.com", ssl=True, # Always use SSL for cloud tenant=args.tenant, database=args.database, headers={ 'x-chroma-token': args.api_key } ) except ssl.SSLError as e: print(f"SSL connection failed: {str(e)}") raise except Exception as e: print(f"Error connecting to cloud client: {str(e)}") raise elif args.client_type == 'persistent': if not args.data_dir: raise ValueError("Data directory must be provided via --data-dir flag when using persistent client") _chroma_client = chromadb.PersistentClient(path=args.data_dir) else: # ephemeral _chroma_client = chromadb.EphemeralClient() return _chroma_client ##### Collection Tools ##### @mcp.tool() async def chroma_list_collections( limit: int | None = None, offset: int | None = None ) -> List[str]: """List all collection names in the Chroma database with pagination support. Args: limit: Optional maximum number of collections to return offset: Optional number of collections to skip before returning results Returns: List of collection names or ["__NO_COLLECTIONS_FOUND__"] if database is empty """ client = get_chroma_client() try: colls = client.list_collections(limit=limit, offset=offset) # Safe handling: If colls is None or empty, return a special marker if not colls: return ["__NO_COLLECTIONS_FOUND__"] # Otherwise iterate to get collection names return [coll.name for coll in colls] except Exception as e: raise Exception(f"Failed to list collections: {str(e)}") from e mcp_known_embedding_functions: Dict[str, EmbeddingFunction] = { "default": DefaultEmbeddingFunction, "cohere": CohereEmbeddingFunction, "openai": OpenAIEmbeddingFunction, "jina": JinaEmbeddingFunction, "voyageai": VoyageAIEmbeddingFunction, "roboflow": RoboflowEmbeddingFunction, } @mcp.tool() async def chroma_create_collection( collection_name: str, embedding_function_name: str = "default", metadata: Dict | None = None, ) -> str: """Create a new Chroma collection with configurable HNSW parameters. Args: collection_name: Name of the collection to create embedding_function_name: Name of the embedding function to use. Options: 'default', 'cohere', 'openai', 'jina', 'voyageai', 'ollama', 'roboflow' metadata: Optional metadata dict to add to the collection """ client = get_chroma_client() embedding_function = mcp_known_embedding_functions[embedding_function_name] configuration=CreateCollectionConfiguration( embedding_function=embedding_function() ) try: client.create_collection( name=collection_name, configuration=configuration, metadata=metadata ) config_msg = f" with configuration: {configuration}" return f"Successfully created collection {collection_name}{config_msg}" except Exception as e: raise Exception(f"Failed to create collection '{collection_name}': {str(e)}") from e @mcp.tool() async def chroma_peek_collection( collection_name: str, limit: int = 5 ) -> Dict: """Peek at documents in a Chroma collection. Args: collection_name: Name of the collection to peek into limit: Number of documents to peek at """ client = get_chroma_client() try: collection = client.get_collection(collection_name) results = collection.peek(limit=limit) return results except Exception as e: raise Exception(f"Failed to peek collection '{collection_name}': {str(e)}") from e @mcp.tool() async def chroma_get_collection_info(collection_name: str) -> Dict: """Get information about a Chroma collection. Args: collection_name: Name of the collection to get info about """ client = get_chroma_client() try: collection = client.get_collection(collection_name) # Get collection count count = collection.count() # Peek at a few documents peek_results = collection.peek(limit=3) return { "name": collection_name, "count": count, "sample_documents": peek_results } except Exception as e: raise Exception(f"Failed to get collection info for '{collection_name}': {str(e)}") from e @mcp.tool() async def chroma_get_collection_count(collection_name: str) -> int: """Get the number of documents in a Chroma collection. Args: collection_name: Name of the collection to count """ client = get_chroma_client() try: collection = client.get_collection(collection_name) return collection.count() except Exception as e: raise Exception(f"Failed to get collection count for '{collection_name}': {str(e)}") from e @mcp.tool() async def chroma_modify_collection( collection_name: str, new_name: str | None = None, new_metadata: Dict | None = None, ) -> str: """Modify a Chroma collection's name or metadata. Args: collection_name: Name of the collection to modify new_name: Optional new name for the collection new_metadata: Optional new metadata for the collection """ client = get_chroma_client() try: collection = client.get_collection(collection_name) collection.modify(name=new_name, metadata=new_metadata) modified_aspects = [] if new_name: modified_aspects.append("name") if new_metadata: modified_aspects.append("metadata") return f"Successfully modified collection {collection_name}: updated {' and '.join(modified_aspects)}" except Exception as e: raise Exception(f"Failed to modify collection '{collection_name}': {str(e)}") from e @mcp.tool() async def chroma_fork_collection( collection_name: str, new_collection_name: str, ) -> str: """Fork a Chroma collection. Args: collection_name: Name of the collection to fork new_collection_name: Name of the new collection to create metadata: Optional metadata dict to add to the new collection """ client = get_chroma_client() try: collection = client.get_collection(collection_name) collection.fork(new_collection_name) return f"Successfully forked collection {collection_name} to {new_collection_name}" except Exception as e: raise Exception(f"Failed to fork collection '{collection_name}': {str(e)}") from e @mcp.tool() async def chroma_delete_collection(collection_name: str) -> str: """Delete a Chroma collection. Args: collection_name: Name of the collection to delete """ client = get_chroma_client() try: client.delete_collection(collection_name) return f"Successfully deleted collection {collection_name}" except Exception as e: raise Exception(f"Failed to delete collection '{collection_name}': {str(e)}") from e ##### Document Tools ##### @mcp.tool() async def chroma_add_documents( collection_name: str, documents: List[str], ids: List[str], metadatas: List[Dict] | None = None ) -> str: """Add documents to a Chroma collection. Args: collection_name: Name of the collection to add documents to documents: List of text documents to add ids: List of IDs for the documents (required) metadatas: Optional list of metadata dictionaries for each document """ if not documents: raise ValueError("The 'documents' list cannot be empty.") if not ids: raise ValueError("The 'ids' list is required and cannot be empty.") # Check if there are empty strings in the ids list if any(not id.strip() for id in ids): raise ValueError("IDs cannot be empty strings.") if len(ids) != len(documents): raise ValueError(f"Number of ids ({len(ids)}) must match number of documents ({len(documents)}).") client = get_chroma_client() try: collection = client.get_or_create_collection(collection_name) # Check for duplicate IDs existing_ids = collection.get(include=[])["ids"] duplicate_ids = [id for id in ids if id in existing_ids] if duplicate_ids: raise ValueError( f"The following IDs already exist in collection '{collection_name}': {duplicate_ids}. " f"Use 'chroma_update_documents' to update existing documents." ) result = collection.add( documents=documents, metadatas=metadatas, ids=ids ) # Check the return value if result and isinstance(result, dict): # If the return value is a dictionary, it may contain success information if 'success' in result and not result['success']: raise Exception(f"Failed to add documents: {result.get('error', 'Unknown error')}") # If the return value contains the actual number added if 'count' in result: return f"Successfully added {result['count']} documents to collection {collection_name}" # Default return return f"Successfully added {len(documents)} documents to collection {collection_name}, result is {result}" except Exception as e: raise Exception(f"Failed to add documents t