Skip to main content
Glama
bpamiri

CockroachDB MCP Server

by bpamiri

connect

Establish a connection to a CockroachDB cluster using environment variables for configuration, returning connection status and cluster information.

Instructions

Connect to the CockroachDB cluster.

Uses configuration from environment variables (CRDB_HOST, CRDB_USER, etc.).

Returns:
    Connection status and cluster information.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool handler for 'connect': thin wrapper that calls connection_manager.connect() and handles exceptions.
    @mcp.tool()
    async def connect() -> dict[str, Any]:
        """Connect to the CockroachDB cluster.
    
        Uses configuration from environment variables (CRDB_HOST, CRDB_USER, etc.).
    
        Returns:
            Connection status and cluster information.
        """
        try:
            return await connection_manager.connect()
        except Exception as e:
            return {"status": "error", "error": str(e)}
  • Core implementation of the connect logic in ConnectionManager.connect(), establishing the AsyncConnection to CockroachDB using config settings, fetching cluster info, and updating state.
    async def connect(self) -> dict[str, Any]:
        """Connect to CockroachDB cluster.
    
        Returns:
            Connection status and cluster info.
        """
        async with self._lock:
            if self._state.connection is not None and not self._state.connection.closed:
                return {
                    "status": "already_connected",
                    "cluster_id": self._state.cluster_id,
                    "version": self._state.version,
                    "database": self._state.database,
                    "connected_at": self._state.connected_at.isoformat()
                    if self._state.connected_at
                    else None,
                }
    
            # Build connection parameters
            conn_params: dict[str, Any] = {
                "host": settings.host,
                "port": settings.port,
                "user": settings.user,
                "dbname": settings.database,
                "row_factory": dict_row,
                "autocommit": True,
            }
    
            if settings.password:
                conn_params["password"] = settings.password
    
            # SSL configuration
            if settings.sslmode != "disable":
                conn_params["sslmode"] = settings.sslmode
                if settings.sslrootcert:
                    conn_params["sslrootcert"] = settings.sslrootcert
    
            # CockroachDB Cloud cluster option
            if settings.cluster:
                conn_params["options"] = f"--cluster={settings.cluster}"
    
            # Connect with timeout
            try:
                conn = await asyncio.wait_for(
                    psycopg.AsyncConnection.connect(**conn_params),
                    timeout=settings.timeout,
                )
    
                # Get cluster info
                async with conn.cursor() as cur:
                    await cur.execute("SELECT version()")
                    version_row = await cur.fetchone()
                    version = version_row["version"] if version_row else None
    
                    await cur.execute("SHOW CLUSTER SETTING cluster.organization")
                    org_row = await cur.fetchone()
                    cluster_id = (
                        org_row["cluster.organization"]
                        if org_row and org_row.get("cluster.organization")
                        else "local"
                    )
    
                self._state.connection = conn
                self._state.connected_at = datetime.now()
                self._state.cluster_id = cluster_id
                self._state.version = version
                self._state.database = settings.database
                self._state.in_transaction = False
    
                return {
                    "status": "connected",
                    "cluster_id": self._state.cluster_id,
                    "version": self._state.version,
                    "database": self._state.database,
                    "host": settings.host,
                    "port": settings.port,
                    "connected_at": self._state.connected_at.isoformat(),
                }
            except asyncio.TimeoutError as e:
                raise ConnectionError(
                    f"Connection to CockroachDB timed out after {settings.timeout}s"
                ) from e
            except Exception as e:
                raise ConnectionError(f"Failed to connect to CockroachDB: {e}") from e
  • The @mcp.tool() decorator registers the connect function as an MCP tool.
    @mcp.tool()
  • Global instance of ConnectionManager used by the connect tool.
    connection_manager = ConnectionManager()
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It adds useful context about using environment variables for configuration and mentions the return content ('Connection status and cluster information'), which helps understand what the tool does beyond basic connectivity. However, it doesn't cover potential errors, timeouts, or other behavioral traits like authentication needs or rate limits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is efficiently structured into three brief sentences: it states the purpose, explains configuration, and describes returns. Each sentence adds value without redundancy, making it front-loaded and easy to parse. There's no wasted text, and it's appropriately sized for a simple connection tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity (0 parameters, no annotations, but has an output schema), the description is reasonably complete. It covers the action, configuration method, and return information, which is sufficient for a connection tool. The output schema likely details the return values, so the description doesn't need to elaborate further, making it adequately complete for the context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0 parameters with 100% coverage, so no parameters need documentation. The description appropriately doesn't discuss parameters, focusing instead on configuration sources and return values. This aligns well with the schema, earning a baseline score of 4 for not introducing unnecessary information.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Connect to the CockroachDB cluster.' It specifies the verb ('connect') and resource ('CockroachDB cluster'), making the action clear. However, it doesn't explicitly differentiate from sibling tools like 'disconnect' or 'cluster_status' beyond the obvious action difference.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by mentioning environment variables for configuration, suggesting it should be used to establish a connection. However, it lacks explicit guidance on when to use this tool versus alternatives (e.g., no mention of prerequisites or timing relative to other tools like 'disconnect'), leaving usage context somewhat implied rather than clearly defined.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/bpamiri/cockroachdb-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server