New advertisers: 50% off your first month with code FIRSTMONTHSee slots

Claude Code plugin that connects agents to CockroachDB for schema, SQL, query, and cluster work.

GitHub stars
36.5K

What it does

  • Adds 3 agents (cockroachdb-dba, cockroachdb-developer, cockroachdb-operator) and 12 skills spanning schema design, performance, security, and disaster recovery
  • Provides MCP backends for self-hosted MCP Toolbox over stdio or HTTP and the managed CockroachDB Cloud MCP Server
  • Uses ccloud shell commands with -o json output for cluster provisioning, backups, replication, and networking
  • Designed for developers and operators who want an AI coding agent to inspect and change live CockroachDB databases directly

CockroachDB plugin for Claude Code — explore schemas, write optimized SQL, debug queries, and manage distributed database clusters directly from your AI coding agent.

Add marketplace

/plugin marketplace add anthropics/knowledge-work-plugins

Run it inside Claude Code once, then install the plugin below.

Install

/plugin install cockroachdb@knowledge-work-plugins

Run it inside Claude Code after adding the marketplace.

Files

Discovered from source

Benchmarking Transaction Patterns

Guides users through benchmarking, explaining, and comparing two formulations of the same transactional business workflow in CockroachDB: explicit multi-statement transactions versus single-statement CTE transactions. Focuses on performance under contention, fair test methodology, and result interpretation.

Complement to design skills: For general transaction design principles, see designing-application-transactions. For SQL syntax and query patterns, see cockroachdb-sql.

Core Concept

Under contention, the transaction formulation itself is a primary performance lever. The explicit model (multi-statement BEGIN/COMMIT) keeps the transaction open across round trips, widening the contention window. The CTE model (single-statement) collapses the same logic into one atomic statement, reducing transaction duration and retries.

Explicit Transaction Model

BEGIN;
SELECT balance FROM accounts WHERE id = $1;
-- Application decides whether transfer is allowed
UPDATE accounts SET balance = balance - $2 WHERE id = $1;
UPDATE accounts SET balance = balance + $2 WHERE id = $3;
INSERT INTO transfers (from_acct, to_acct, amount, created_at)
VALUES ($1, $3, $2, now());
COMMIT;

CTE Transaction Model

CockroachDB rejects multiple mutations of the same table in a single statement by default (sql.multiple_modifications_of_table.enabled), so the debit and credit are folded into one UPDATE using CASE.

WITH funded AS (
  SELECT 1 FROM accounts WHERE id = $1 AND balance >= $2
), upd AS (
  UPDATE accounts
  SET balance = CASE WHEN id = $1 THEN balance - $2 ELSE balance + $2 END
  WHERE id IN ($1, $3) AND EXISTS (SELECT 1 FROM funded)
  RETURNING id
), ins AS (
  INSERT INTO transfers (from_acct, to_acct, amount, created_at)
  SELECT $1, $3, $2, now() WHERE (SELECT count(*) FROM upd) = 2
  RETURNING id
)
SELECT id FROM ins;

Steps

1. Prepare the Benchmark Environment

Set up a dedicated test database and schema. Do not mix benchmark workloads with other traffic.

CREATE DATABASE IF NOT EXISTS bankbench;
USE bankbench;

CREATE TABLE accounts (
  id INT PRIMARY KEY,
  balance DECIMAL(18,2) NOT NULL DEFAULT 0
);

CREATE TABLE transfers (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  from_acct INT NOT NULL,
  to_acct INT NOT NULL,
  amount DECIMAL(18,2) NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

2. Seed the Test Data

Use multi-row UPSERT for efficient seeding. Single-row inserts distort setup cost.

INSERT INTO accounts (id, balance)
SELECT generate_series(1, 10000), 1000.00
ON CONFLICT (id) DO UPDATE SET balance = 1000.00;

3. Run the Explicit Transaction Benchmark

Execute with realistic concurrency. Example using pgbench (PostgreSQL-compatible):

# Create a pgbench script file: explicit_transfer.sql
# \set from_id random(1, 10000)
# \set to_id random(1, 10000)
# \set amount 10.00
# BEGIN;
# SELECT balance FROM accounts WHERE id = :from_id;
# UPDATE accounts SET balance = balance - :amount WHERE id = :from_id;
# UPDATE accounts SET balance = balance + :amount WHERE id = :to_id;
# INSERT INTO transfers (from_acct, to_acct, amount, created_at) VALUES (:from_id, :to_id, :amount, now());
# COMMIT;

pgbench -n -c 64 -j 8 -T 120 -f explicit_transfer.sql \
  "postgresql://root@localhost:26257/bankbench?sslmode=disable"

Record throughput (tps), retries, p50/p95/p99 latency, max latency, and failures.

4. Reset Between Runs for Fair Comparison

For a fair benchmark, reset account balances between explicit and CTE runs so table size, index size, and account state remain comparable.

UPDATE accounts SET balance = 1000.00;

5. Run the CTE Transaction Benchmark

Execute with the same concurrency, duration, and parameters as the explicit run:

# Create a pgbench script file: cte_transfer.sql containing the CTE query above
pgbench -n -c 64 -j 8 -T 120 -f cte_transfer.sql \
  "postgresql://root@localhost:26257/bankbench?sslmode=disable"

6. Compare Results

Always compare these metrics side by side:

MetricWhat to Look For
Throughput (txn/s)Higher is better; CTE typically sustains better under contention
Total retriesCTE often reduces to near-zero
p50 latencyMedian transaction time
p95 latencyTail latency under moderate contention
p99 latencyWorst-case tail; explicit model often shows spikes
Max latencyOutlier behavior
FailuresNon-retryable errors

7. Validate Benchmark Integrity

Before interpreting results, verify the benchmark ran cleanly:

-- Confirm expected transfer volume
SELECT COUNT(*) AS total_transfers FROM transfers;
# Check node liveness and start times (no node restarts mid-benchmark)
cockroach node status --certs-dir=<certs-dir>     # or --insecure for an insecure cluster

Benchmark Reference Results

In a reported high-contention run comparing the two models:

MetricExplicitCTEChange
Throughput591.1 txn/s1,035.1 txn/s+75.1%
Wall time216.5s123.7s-42.9%
Average latency202.2 ms111.3 ms-45.0%
Total retries2,270,9770-100%

Extended runs preserved the same directional result at higher total volume, with the explicit model continuing to accumulate retries and occasional failures while the CTE model stayed at zero retries and zero failures.

Impact Summary

DimensionExplicit Multi-StatementSingle-Statement CTE
Round tripsMultiple client/server interactionsSingle request
Transaction lifetimeLongerShorter
Client retry complexityHigherLower
Atomic invariant enforcementSpread across statements/app logicContained in SQL
Expected throughputLower under contentionHigher under contention
Client-visible retriesMore likelyOften reduced

Decision Guidance

Prefer the Explicit Pattern When

  • The business workflow truly cannot be expressed cleanly in one SQL statement
  • Readability or staged business logic matters more than peak throughput
  • The contention level is low enough that retry amplification is not the dominant cost

Prefer the CTE Pattern When

  • The workflow is contention-heavy
  • The operation is naturally atomic
  • The application currently performs read-decide-write across multiple statements
  • The main goal is higher throughput, lower retries, and more stable p95/p99 latency

Fair Benchmark Rules

  1. Reset between runs for fair comparison so balances, table size, and index size stay consistent
  2. Treat no-reset runs as a demo, not an apples-to-apples benchmark
  3. Use --batch-size=1 when you want one business unit of work at a time for clean comparison
  4. Compare the right metrics — always include throughput, retries, p50, p95, p99, max latency, and failures
  5. Use multi-row UPSERT for seeding — single-row seeding distorts setup cost

Common Misconceptions

  • "CTE always wins" — Only when the workflow is contention-sensitive and expressible as a single atomic statement.
  • "SQL Activity showing waiting means CTE failed" — CTE reduces but does not eliminate contention. Compare throughput, tail latency, and retry profile.
  • "Single-statement means no contention" — CTE narrows the contention window but does not eliminate it.

Safety Considerations

  • Run benchmarks on dedicated test clusters, not production
  • Reset data between runs for fair comparison
  • Monitor cluster health during benchmark execution
  • Use realistic but not destructive concurrency levels
  • Validate that benchmark results transfer to your specific workload before making production changes

References

Readme

CockroachDB Plugin for Claude Code

Release Please License

Connect Claude Code directly to your CockroachDB clusters for hands-on database work — explore schemas, write optimized SQL, debug queries, and manage distributed database clusters. This plugin provides tools across MCP backends (self-hosted MCP Toolbox and managed CockroachDB Cloud MCP Server), specialized agents (DBA, Developer, Operator), skills across operational domains, and built-in safety hooks.

Installation

Install from the Claude Marketplace, or in Claude Code run:

/plugin install cockroachdb@claude-plugins-official

To install from this repository's own marketplace instead:

/plugin marketplace add cockroachdb/claude-plugin
/plugin install cockroachdb@cockroachdb-claude-plugin

Local development

claude --plugin-dir /path/to/claude-plugin

Prerequisites

The skills, agents, and hooks work without any setup. Each of the plugin's MCP servers needs its own:

  • cockroachdb-toolbox (any self-hosted or Cloud cluster) needs MCP Toolbox for Databases v1.0.0 or later on your PATH, and a running CockroachDB cluster it can reach. Toolbox connects when the session starts, so without a reachable cluster this server fails to start. If you don't run a cluster, turn the server off.
  • cockroachdb-cloud (CockroachDB Cloud) needs a CockroachDB Cloud account. Run /mcp and select the server to sign in.
Install MCP Toolbox

macOS or Linux:

brew install mcp-toolbox

Windows: download toolbox.exe into a folder on your PATH. In PowerShell, set the version to the latest one on the Toolbox releases page, and use windows/arm64 in the URL on Arm devices:

$VERSION = "1.14.0"
curl.exe -o toolbox.exe "https://storage.googleapis.com/mcp-toolbox-for-databases/v$VERSION/windows/amd64/toolbox.exe"

Restart Claude after changing your PATH, then confirm the install with toolbox --version. For other platforms, the container image, and building from source, see Install Toolbox.

Configuration

Self-hosted clusters (MCP Toolbox)

The cockroachdb-toolbox server reads its connection settings from environment variables. Each one is optional, and an unset variable falls back to its default:

VariableDefaultNotes
COCKROACHDB_HOSTlocalhost
COCKROACHDB_PORT26257
COCKROACHDB_USERroot
COCKROACHDB_PASSWORD(empty)
COCKROACHDB_DATABASEdefaultdb
COCKROACHDB_SSLMODErequireUse disable for a local --insecure cluster, verify-full for production

Set them in the environment Claude starts from. On macOS or Linux, add them to your shell profile:

export COCKROACHDB_HOST="your-cluster-host"
export COCKROACHDB_PORT="26257"
export COCKROACHDB_USER="your-user"
export COCKROACHDB_PASSWORD="your-password"
export COCKROACHDB_DATABASE="your-database"
export COCKROACHDB_SSLMODE="verify-full"

On Windows, set them as user environment variables, for example setx COCKROACHDB_HOST "your-cluster-host", then restart Claude.

For a CockroachDB Cloud cluster, find the connection details in the Cloud Console.

Toolbox runs in read-only mode: SELECT, SHOW, and EXPLAIN work, and writes and schema changes are rejected. To allow writes, run Toolbox with your own copy of tools.yaml that sets enableWriteMode: true, configured as your own MCP server, and turn off the plugin's cockroachdb-toolbox server.

CockroachDB Cloud

The cockroachdb-cloud server connects to the managed MCP server that Cockroach Labs hosts. Run /mcp, select cockroachdb-cloud, and sign in. The consent screen asks you to grant read access, write access, or both.

By default the connection can reach every cluster your CockroachDB Cloud role allows. To limit it to one cluster, set COCKROACHDB_CLUSTER_ID to that cluster's ID.

Turn off a server you don't use

Claude Code starts both MCP servers in every session. If you only use one of them, open /mcp, select the other, and disable it. Claude Code remembers the choice for each project.

Alternative MCP Backends

The plugin ships with the MCP Toolbox (stdio) and CockroachDB Cloud MCP backends active by default. To add another backend, put its entry in your own MCP configuration (for example a project .mcp.json) or add it with claude mcp add:

MCP Toolbox via HTTP (remote/multi-user)
{
  "mcpServers": {
    "cockroachdb-toolbox-http": {
      "type": "http",
      "url": "http://your-toolbox-host:5000/mcp"
    }
  }
}

Or via CLI: claude mcp add --transport http cockroachdb-toolbox-http http://your-toolbox-host:5000/mcp

Run Toolbox in HTTP mode: toolbox --config tools.yaml --address 0.0.0.0 --port 5000

Run Toolbox with the built-in web UI: toolbox --config tools.yaml --ui --port 5000 (opens at http://127.0.0.1:5000/ui)

Note: Toolbox must successfully connect to CockroachDB on startup. If the database is unreachable (wrong host/port, env vars not set), the server will hang during initialization and the UI will be stuck on "Fetching tools...". Make sure your COCKROACHDB_* environment variables are set and the database is accessible before starting.

CockroachDB MCP Server (first-party, self-hosted)

CockroachDB MCP Server is Cockroach Labs' own MCP server for clusters you run yourself. By default it registers only read-only tools, such as list_databases, list_tables, get_table_schema, select_query, explain_query, show_statement, and show_running_queries. Setting CRDB_MCP_ENABLE_WRITE_QUERIES=true adds create_database, create_table, insert_rows, update_rows, and delete_rows, and the server refuses an UPDATE or DELETE without a WHERE clause.

Install: go install github.com/cockroachdb/cockroachdb-mcp-server@latest (Go 1.26+). Linux and Windows binaries and a Docker image are listed on the releases page. There are no prebuilt macOS binaries, so on macOS use go install or Docker.

Configure with certificate authentication (recommended):

{
  "mcpServers": {
    "cockroachdb-mcp-server": {
      "command": "cockroachdb-mcp-server",
      "env": {
        "CRDB_HOST": "your-cluster-host",
        "CRDB_USERNAME": "ai_agent",
        "CRDB_SSL_MODE": "verify-full",
        "CRDB_SSL_CA_PATH": "/certs/ca.crt",
        "CRDB_SSL_CERTFILE": "/certs/client.ai_agent.crt",
        "CRDB_SSL_KEYFILE": "/certs/client.ai_agent.key"
      }
    }
  }
}

For a local --insecure development cluster:

claude mcp add cockroachdb-mcp-server -e CRDB_DATABASE_URL="postgresql://root@localhost:26257/defaultdb?sslmode=disable" -e CRDB_MCP_ALLOW_INSECURE_DB=true -- cockroachdb-mcp-server

Password authentication is off unless you set CRDB_MCP_ALLOW_PASSWORD_AUTH=true. Desktop apps may not search ~/go/bin, so give the binary's absolute path as the command if the server doesn't start. The plugin's SQL safety hook applies to the bundled Toolbox server; this server enforces its own guardrails. See the server's README for every setting.

ccloud CLI (cluster lifecycle, backups, DR, networking)

The ccloud CLI is an agent-ready command-line tool for full cluster lifecycle management. AI agents call ccloud directly via shell commands (not MCP protocol) -- every command supports -o json for structured output.

Install: brew install cockroachdb/tap/ccloud

Authenticate (interactive): ccloud auth login (opens browser; supports SSO via OIDC/SAMLv2)

Authenticate (org-scoped): ccloud auth login --org {organization-label}

Authenticate (headless/CI): ccloud auth login --no-redirect or use a service account API key as a bearer token.

Example agent commands:

# Provision
ccloud cluster create serverless my-cluster us-east-1 --cloud AWS -o json
ccloud cluster database create my-cluster myapp -o json

# Connect
ccloud cluster connection-string my-cluster --database myapp --sql-user maxroach -o json
# Composable: pipe into jq + psql
ccloud cluster connection-string my-cluster --database myapp --sql-user maxroach -o json \
  | jq -r '.connection_url' | xargs -I{} psql {} -c "SELECT count(*) FROM users"

# Operate
ccloud cluster list -o json
ccloud cluster info my-cluster -o json
ccloud cluster backup config update my-cluster --frequency 60 --retention 60

# Observe
ccloud audit list --limit 10 -o json
ccloud cluster versions -o json
ccloud cluster cmek get my-cluster -o json

# Scale & DR
ccloud replication create --primary-cluster prod-east --standby-cluster dr-west
ccloud cluster networking allowlist list <cluster-id> -o json

# Organize
ccloud folder create Production -o json
ccloud folder contents <folder-id> -o json

# Test resilience
ccloud cluster disruption set my-cluster --region us-east-1 --whole-region

Coverage: Provision, Connect, Operate, Observe, Scale & DR, Organize, Test resilience. See the ccloud reference for full command list.

CockroachDB Cloud MCP Server (OAuth/API key)

The official managed MCP server is hosted by Cockroach Labs and requires no infrastructure setup. The plugin already includes it as cockroachdb-cloud; use these snippets to configure it yourself, for example with a service account API key. With OAuth 2.1 (PKCE), the consent screen asks you to grant read access, write access, or both (scopes mcp:read and mcp:write).

OAuth (recommended, opens a browser for consent):

{
  "mcpServers": {
    "cockroachdb-cloud": {
      "type": "http",
      "url": "https://cockroachlabs.cloud/mcp"
    }
  }
}

API key (headless or autonomous agents):

{
  "mcpServers": {
    "cockroachdb-cloud": {
      "type": "http",
      "url": "https://cockroachlabs.cloud/mcp",
      "headers": {
        "Authorization": "Bearer {your-service-account-api-key}"
      }
    }
  }
}

Without an mcp-cluster-id header, a connection can reach every cluster your user or service account can access. To limit it to one cluster, add "mcp-cluster-id": "{your-cluster-id}" to headers.

Or via CLI: claude mcp add --transport http cockroachdb-cloud https://cockroachlabs.cloud/mcp, adding --header "mcp-cluster-id: {your-cluster-id}" to limit the connection to one cluster.

See the quickstart guide for detailed setup.

What's Included

MCP Backends

BackendStatusTransportUse Case
cockroachdb-toolboxActivestdioAny CockroachDB cluster via MCP Toolbox
cockroachdb-cloudActiveStreamable HTTPManaged MCP Server — CockroachDB Cloud (OAuth/API key)
cockroachdb-toolbox-httpAvailableHTTPMCP Toolbox remote/multi-user via HTTP (not shipped; add it yourself, see Alternative MCP Backends)
cockroachdb-mcp-serverAvailablestdio, HTTPSFirst-party server for self-hosted clusters (not shipped; add it yourself, see Alternative MCP Backends)

CLI Tools

ToolStatusUse Case
ccloudActiveAgent-ready CLI — cluster lifecycle, backups, DR, networking, audit. Agents call directly via shell.

Tools

MCP Toolbox (self-hosted, any cluster):

ToolDescription
cockroachdb-execute-sqlRun SQL (read-only unless write mode is enabled)
cockroachdb-list-schemasList all schemas in the database
cockroachdb-list-tablesList tables with columns, types, and constraints

CockroachDB Cloud MCP (managed, read tools):

ToolDescription
list_clustersList all accessible clusters
get_clusterGet detailed cluster information
list_databasesList databases in the cluster
list_tablesList tables in a database
get_table_schemaGet detailed schema for a table
select_queryExecute a SELECT statement
explain_queryExecute an EXPLAIN statement
show_running_queriesList currently executing queries

CockroachDB Cloud MCP (managed, write tools — requires write consent):

ToolDescription
create_databaseCreate a new database
create_tableCreate a new table
insert_rowsInsert rows into a table

Skills

Skills are sourced from the cockroachdb-skills submodule via symlinks — a single source of truth shared across CockroachDB agent integrations. A weekly CI workflow auto-detects upstream changes and opens a PR to update.

DomainExamples
Query & Schema Designcockroachdb-sql
Observability & Diagnosticsprofiling-statement-fingerprints, triaging-live-sql-activity
Security & Governanceauditing-cloud-cluster-security, hardening-user-privileges
Onboarding & Migrationsmolt-fetch, molt-verify, molt-replicator
Operations & Lifecyclemanaging-cluster-capacity, upgrading-cluster-version

Agents

AgentDescription
cockroachdb-dbaCockroachDB DBA expert — performance tuning, schema review, cluster diagnostics
cockroachdb-developerApplication developer expert — ORM config, retry logic, transaction patterns
cockroachdb-operatorOperator/SRE expert — cluster operations, monitoring, backups, scaling, incidents

Agents are auto-discovered from the agents/ directory. Claude invokes them automatically based on task context, or you can reference them directly (e.g., "ask the cockroachdb-dba agent to review this schema").

Hooks

HookTriggerWhat It Does
validate-sqlBefore SQL executionBlocks DROP DATABASE, TRUNCATE; warns on SERIAL, multi-DDL transactions
check-sql-filesAfter file Write/EditScans SQL/code files for CockroachDB anti-patterns (SERIAL, SELECT *, missing retry)

Hooks run as Python scripts (Python 3, no external dependencies) and provide automated safety guardrails.

Windows note: the hooks invoke python3, so make sure a python3 is on your PATH. The python.org installer creates python.exe and the py launcher but not python3.exe; on those installs the hooks safely no-op (they never block editing, but the safety checks won't run). Installing Python from the Microsoft Store — or adding a python3 alias — enables them. You do not need to turn on Windows long-path support: the hooks load their scripts through the \\?\ long-path prefix, so they work no matter how deep the plugin cache path is.

Development

Clone the repository:

git clone --recurse-submodules https://github.com/cockroachdb/claude-plugin.git
cd claude-plugin

Test locally:

claude --plugin-dir .

Validate the plugin:

claude plugin validate .

Project Structure

.claude-plugin/
  plugin.json                  # Plugin manifest with component declarations
  marketplace.json             # Marketplace catalog for distribution
.mcp.json                      # MCP server configuration
tools.yaml                     # Toolbox source & tool definitions
agents/
  cockroachdb-dba.md           # DBA agent
  cockroachdb-developer.md     # Developer agent
  cockroachdb-operator.md      # Operator agent
hooks/
  hooks.json                   # Hook configuration
scripts/
  validate-sql.py              # SQL validation hook
  check-sql-files.py           # Anti-pattern linter hook
skills/                        # Skills copied from cockroachdb-skills submodule
submodules/
  cockroachdb-skills/          # Shared skills submodule
assets/
  logo.svg                     # Plugin logo

Releasing

This repo uses Release Please for automated releases.

  1. Use Conventional Commits (feat:, fix:) on main
  2. Release Please opens a Release PR with version bump and changelog
  3. Merge the Release PR to publish

Links

License

Apache-2.0

Details

Marketplace
anthropics/knowledge-work-plugins
Source
https://github.com/cockroachdb/claude-plugin.git
Category
Community
Listed since
Apr 7, 2026

More from anthropics/knowledge-work-plugins

All 123

Similar to cockroachdb

More Databases