Skip to main content
Glama

portward

Safe per-alias access to GCP Cloud SQL MySQL and Kubernetes services for Claude Code, through a local MCP server. Claude asks for an environment by alias. portward opens the right tunnel, then enforces the safety rules itself (read-only grants, GET-only APIs, confirmation prompts, an audit log) instead of relying on manual steps.

Install

claude mcp add portward -- uvx portward serve

Requires gcloud, kubectl, cloud-sql-proxy 2.x and Application Default Credentials (gcloud auth application-default login). Check with portward doctor.

Local / development install

portward is not on PyPI yet, so the uvx line above does not work today. Install from a checkout instead:

  1. uv tool install --editable <path-to-checkout> puts portward on PATH (~/.local/bin/portward). Code edits take effect without reinstalling.

  2. Run portward init, then portward doctor <alias>, before starting Claude Code. Without a config, serve exits, and claude mcp list and /mcp show "Failed to connect".

  3. claude mcp add portward --scope user -- ~/.local/bin/portward serve. --scope user registers it for all your projects; the default scope (local) registers it only for the current project.

  4. Restart Claude Code after any config change, because the config is read once at start. Check with /mcp.

Uninstall with claude mcp remove portward --scope user and uv tool uninstall portward.

Allow the portward tools in Claude Code (required)

In auto mode, Claude Code's permission classifier can block portward's tool calls ("Unauthorized Access") until you allow them. The rule mcp__portward allows all of portward's tools. Add it at user scope, which matches the user-scope MCP registration and so works in every project: run /permissions, add an allow rule and save it to user settings, or add it to permissions.allow in ~/.claude/settings.json.

This does not weaken portward's safety: the grants check, confirm prompts, refusals and audit still apply. To have Claude Code keep asking before some tools (for example forward or run_script), allow single tools instead, such as mcp__portward__query and mcp__portward__http.

Next to it, add the deny rules recommended in docs/security-model.md, so the agent cannot go around portward with its own tools:

{
  "permissions": {
    "allow": ["mcp__portward"],
    "deny": [
      "Bash(kubectl port-forward *)",
      "Bash(kubectl * port-forward *)",
      "Bash(cloud-sql-proxy *)",
      "Edit(~/.config/portward/**)"
    ]
  }
}

Edit(...) rules also cover file writes. The middle wildcard catches kubectl --context … port-forward ….

Related MCP server: mysql-mcp-plugin

Config

~/.config/portward/config.yaml (override with PORTWARD_CONFIG), created with portward init or by hand:

envs:
  prod:
    db:
      instance: "my-project:europe-west6:main"   # Cloud SQL connection name
      engine: mysql
      name: app                                 # default database; others are reachable with db.table if granted
      user: claude-ro
      password: "keyring:portward/prod"         # or k8s:<ctx>/<ns>/<secret>/<key>, env:<VAR>
      port: 13306                               # fixed local port, unique across the file
      access: read_only
    api:
      context: gke_my-project_europe-west6_main # always passed as --context
      namespace: app
      service: web
      port: 8080
      local_port: 18080
      health_path: /health
      access: read_only
    confirm: once                               # never | once | always
    inject:                                     # env vars for run_script
      REMOTE_DB_HOST: db.host
      REMOTE_DB_PORT: db.port
      REMOTE_DB_USERNAME: db.user
      REMOTE_DB_PASSWORD: db.password
      REMOTE_DB_NAME: db.name
  test:                                         # a test environment the agent may change
    db:
      instance: "my-test-project:europe-west6:main"
      engine: mysql
      name: app
      user: app
      password: "keyring:portward/test"
      port: 13307                               # its own port
      access: read_write
    confirm: never

inject maps environment variable names of your choice to connection values, for run_script only:

  • Values: db.host, db.port, db.user, db.password, db.name, api.url. api.url is refused on a read_only API (a config error), because a script holding the URL could POST freely.

  • Scope: a run_script call sets the variables only of the aliases named in that call.

  • No shared names: two aliases in one run_script call must not set the same variable; such a call is refused.

  • Custom names: any names work, for example:

        inject:
          PROD_DB_HOST: db.host
          PROD_DB_PORT: db.port
          PROD_DB_USER: db.user
          PROD_DB_PASSWORD: db.password
          PROD_DB_NAME: db.name

The server reads the config once at start, so edits take effect only after the client restarts. No MCP tool writes the config.

Safety model

Full detail, including what portward does not protect against: docs/security-model.md.

  • Read-only DB: every new connection runs SHOW GRANTS. Only SELECT, USAGE and SHOW VIEW pass. Any other privilege, WITH GRANT OPTION, or any granted role (such as cloudsqlsuperuser) is refused. query sessions also run SET SESSION TRANSACTION READ ONLY.

  • Read-write DB (db.access: read_write, for test environments): no grants check and no read-only session. query runs any single statement, including DDL, and run_script children get the credentials. The default confirm mode is never. For anything shared, such as staging, confirm: once is recommended.

  • Read-only API: only GET and HEAD. The forward exists only for the duration of the call.

  • Prompts: confirm: once or always asks through MCP elicitation, which needs an interactive Claude Code terminal. Only an explicit accept with confirm = true proceeds. Decline, cancel (Esc), or a client without elicitation support all mean refuse. On the legacy protocol, no answer within 120 s also means refuse.

  • forward (a raw port) is refused on any read-only alias and under confirm: always.

  • Audit: every tool call appends a line to ~/.local/state/portward/audit.jsonl (override with PORTWARD_STATE_DIR). Lines older than 30 days are pruned. Secrets are never logged and are masked in output.

Creating a read-only Cloud SQL user

This applies only to read_only aliases; a read_write alias uses whatever user you give it.

  1. Create the user with gcloud. gcloud has no --prompt-for-password, so generate one:

    PW=$(openssl rand -base64 24)
    gcloud sql users create claude-ro --instance=<instance> --host=% --password="$PW"

    Store the password in the keyring under the alias (see Storing a keyring: password).

  2. Revoke the role and grant per database, as an admin that has ROLE_ADMIN:

    REVOKE `cloudsqlsuperuser`@`%` FROM 'claude-ro'@'%';
    GRANT SELECT ON app.* TO 'claude-ro'@'%';
    • Why the REVOKE is needed: gcloud and the Admin API add the cloudsqlsuperuser role to every user they create. In the user's own session, MySQL 8 shows that active role expanded into one long GRANT SELECT, INSERT, … ON *.* TO … WITH GRANT OPTION line. That line is what portward doctor quotes.

    • Don't use REVOKE ALL … ON *.*: it fails under partial_revokes (error 3879).

    • Errors: 1227 means the admin lacks ROLE_ADMIN; 3530 means the role is already revoked.

    • Grants are per database: MySQL has no "all except" grant. Databases created later need their own grant; keep customer databases out by not granting them.

    • db.name must be one of the granted databases (see Tools).

  3. Verify with SHOW GRANTS FOR 'claude-ro'@'%'; as the admin: only USAGE and SELECT lines, no role line. Then run portward doctor <alias>.

Storing a keyring: password

The keyring library ships with portward (a dependency), so nothing extra is needed to read passwords. To store one, use any of these:

  • uvx keyring set portward <alias> (recommended: no install, and uv is already required)

  • uv tool install keyring, then keyring set portward <alias>

  • macOS without Python: security add-generic-password -s portward -a <alias> -w (prompts for the password; keyring's macOS backend reads the same item)

It takes two words, the service portward and the alias, and the alias must match the config reference keyring:portward/<alias>. The tool that creates the item is the one the Keychain trusts, so this choice decides which programs get prompted later (see below).

Keychain prompts (macOS)

portward doctor can show macOS Keychain dialogs ("python wants to use your confidential information stored in 'portward'…"), up to one per alias:

  • Why: the Keychain item trusts the program that created it, for example the Python behind the keyring CLI. portward runs under the uv tool's own Python, which macOS treats as a different program.

  • doctor asks on every run: it is a fresh process each time and resolves every alias's password.

  • serve asks at most once per alias per Claude Code start, because it caches each password for its lifetime.

  • Which apps are trusted: open Keychain Access, search portward, then the Access Control tab.

Prefer Allow over Always Allow. "Always Allow" trusts the Python binary, not portward. uv shares its managed interpreters, so other scripts on that interpreter, including ones an agent writes and runs through Bash, could then read the password without a prompt. With "Allow", such an attempt shows a dialog you can deny. The trade-off is more prompts versus silent access.

Tools

Tool

What it does

list_envs()

Aliases, the resources each has, access per resource, and confirm mode. Never secrets.

query(env, sql, max_rows=500)

One statement, 60 s timeout, at most 5000 rows. Returns {columns, rows, row_count, truncated, affected_rows}.

run_script(env, command, cwd=None, timeout_s=1800)

Runs a local command with each alias's inject variables set. env may be a list. Output is trimmed to 20 KB per stream and passwords are masked.

forward(env, target)

A raw 127.0.0.1 port for db or api. Refused on read-only aliases and under confirm: always.

http(env, method, path, body=None, headers=None)

An API call through the forward. Returns {status, headers, body}.

wait_for_rollout(env, image=None, timeout_s=1200)

Waits for the Deployment behind the service and, optionally, for every ready pod to run image. Then restarts the forward and polls health_path.

status()

Running proxies and forwards (port, pid, reconnects, last error) plus the last 20 audit entries.

Which database query uses: db.name is only the default database of each connection. What the user can read is decided by its grants, so other granted databases are reachable with qualified names (other_db.table).

  • Each query call opens a new connection, so USE does not persist between calls: use qualified names.

  • In run_script, REMOTE_DB_NAME (or whatever db.name is injected as) is this default database.

  • The default must be a database the user has grants on, or the connection fails.

portward init

An interactive walk-through: pick GCP projects, then per project a Cloud SQL instance, DB user and database, and/or a GKE cluster, namespace, service and port. It offers get-credentials when the kube context is missing. Then enter the alias, access modes, confirm mode, password reference, local ports and the inject map. The alias is appended to the config. Entering an existing alias name asks before replacing it, and every other alias is left byte-for-byte unchanged.

  • Keys: the project list is a multi-select. Type to filter, Space to tick (●), Enter to confirm. Enter alone submits nothing: init then stops with no project selected (exit code 1) and leaves the config unchanged.

  • One alias per project: init walks through each ticked project in turn, so ticking several projects creates several aliases in one run.

  • Adding more later: run portward init again. New aliases are appended, and existing ones stay byte-identical unless you reuse a name and confirm the replace.

  • Aborting: Esc or Ctrl-C at any prompt keeps the config as it was before that project. Aliases already written for earlier projects in the same run are kept, and init names them.

  • Default database name: the database question sets db.name, the default database only (see Tools); other granted databases stay reachable with qualified names. Pick one the user has grants on.

  • Inject names: init offers only the default REMOTE_DB_* names (yes) or none (no). Answering no prints how to add custom names by hand. Every run that wrote an alias ends with a note: the config file can be edited by hand (aliases, inject names, ports, confirm mode); then run portward doctor and restart Claude Code.

  • Before connecting Claude Code: run portward doctor (all aliases) or portward doctor <alias> afterwards.

portward doctor [alias]

Prints PASS/FAIL per check, each FAIL with a fix hint:

  • gcloud, kubectl and cloud-sql-proxy 2.x are on PATH.

  • ADC credentials are present. It prints the ADC account, which can differ from your active gcloud account.

  • Per alias:

    • the config is valid

    • a proxy handshake to the instance succeeds (reads the MySQL greeting; no credentials used). A failure is retried once after about 2 s, because it is often temporary. If both attempts fail, doctor shows the last lines of the proxy's stderr, which name the real cause, and lists the possible causes (missing roles/cloudsql.client for the ADC account, expired ADC, Cloud SQL Admin API disabled, a private-IP-only instance off the VPC, a wrong connection name, a temporary issue). It suggests re-running doctor, then running cloud-sql-proxy --port 0 <instance> by hand to read the full error.

    • the password reference resolves (the value is never printed)

    • the kube context and the service exist

    • the health path answers

    • for read-only DBs, the grants check passes

CLI

Command

Purpose

portward serve

Run the MCP server over stdio.

portward init

Interactively add an alias. Existing aliases are left untouched.

portward doctor [alias]

Pass/fail checks, each FAIL with a fix hint.

portward log [--alias A] [--since 1d]

Print audit entries.

Development

uv sync
uv run pytest -m 'not live'
uv run ruff check . && uv run ruff format --check .

live tests hit a real test environment (PORTWARD_LIVE_ALIAS, PORTWARD_LIVE_RO_ALIAS). Never run them against production.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables Claude Code to securely interact with PostgreSQL, MySQL, SQLite, and SQL Server databases, featuring read-only mode, query validation, SSH tunneling, and field redaction for production-safe data access.
      4
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides MySQL access with configurable per-connection capabilities, enabling secure read-only or writable database operations through Claude Code and other MCP clients.
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Enables Claude Desktop and Claude Code to inspect a Postgres schema and run read-only SQL queries against a demo database through the tools describe_schema and query_readonly. Every proposed query passes the same deterministic guardrails — SELECT-only, allow-listed tables, enforced row limits, statement timeouts and a read-only role — before execution.
      2
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables Claude Code to inspect and query PostgreSQL, MySQL/MariaDB, IBM Db2, SQLite, and Redis through a small set of tools, with per-connection permission checks, SQL and Redis command guarding, result limits and masking, and audit logging.
      MIT