Metadata-Version: 2.4
Name: mcp-key-rotator
Version: 0.3.0
Summary: Guided provider-agnostic API-key rotation for stdio and HTTP MCP servers
Author: MCP Key Rotator contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/pawandeep006-rgb/mcp-key-rotator
Project-URL: Repository, https://github.com/pawandeep006-rgb/mcp-key-rotator
Project-URL: Issues, https://github.com/pawandeep006-rgb/mcp-key-rotator/issues
Keywords: mcp,api-keys,rotation,quota,proxy
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyYAML<7,>=6.0
Requires-Dist: httpx<1,>=0.28
Requires-Dist: keyring<26,>=25
Requires-Dist: platformdirs<5,>=4
Requires-Dist: starlette<2,>=1.3.1
Requires-Dist: textual<9,>=3
Requires-Dist: tomli-w<2,>=1.2
Requires-Dist: uvicorn<1,>=0.35
Requires-Dist: tzdata>=2024.1; platform_system == "Windows"
Provides-Extra: dev
Requires-Dist: build<2,>=1.2; extra == "dev"
Requires-Dist: ruff<1,>=0.8; extra == "dev"
Dynamic: license-file

# MCP Key Rotator

[![CI](https://github.com/pawandeep006-rgb/mcp-key-rotator/actions/workflows/ci.yml/badge.svg)](https://github.com/pawandeep006-rgb/mcp-key-rotator/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](pyproject.toml)

Provider-agnostic API-key rotation and quota management for **stdio, Streamable HTTP, and
legacy HTTP+SSE MCP servers**. One local session receives one credential and keeps it for that
session's lifetime—no mid-session account changes and no automatic replay of tool calls.

**v0.2.0** adds guided setup, AI-agent automation, an interactive dashboard, OS credential
vault support, native HTTP transports, catalog-driven client integrations, optional process-tree
cleanup, and local structured telemetry.

## Install in one prompt

Give an AI coding agent the prompt in **[docs/AI_AGENT_INSTALL.md](docs/AI_AGENT_INSTALL.md)**.
It installs the released package, detects supported clients and credential variable names,
reuses existing upstream MCP servers, applies safe changes with backups, and runs offline
diagnostics. It never needs credential values in chat.

## Install manually

```bash
# Install uv first if needed: https://docs.astral.sh/uv/getting-started/installation/
uv tool install mcp-key-rotator
mkr setup
```

`uv` manages Python automatically. `pipx install mcp-key-rotator` and
`python -m pip install mcp-key-rotator` are supported fallbacks. The guided wizard works on
Windows, macOS, and Linux. It discovers credential-bearing MCP servers from the clients you
select, then prints manual setup commands without collecting secrets or changing files.

See the **[illustrated installation guide](docs/INSTALL.md)** for platform commands, credential
vault setup, upgrades, and uninstall.

## Everyday commands

| Command | Purpose |
| --- | --- |
| `mkr` | Open the keyboard-accessible key-health dashboard. |
| `mkr setup` | Select clients, discover configured MCP credentials, and print manual commands. |
| `mkr setup --agent --apply --json` | Noninteractive AI-agent setup; no secret prompts. |
| `mkr doctor [--json]` | Offline diagnostics and plain-language repair guidance. |
| `mkr status [--json]` | Redacted key health, eligibility, counters, cooldowns, and resets. |
| `mkr keys ...` | List, add, reset, disable, enable, or reclassify keys. |
| `mkr clients ...` | Detect, add, remove, or generate generic client configuration. |
| `mkr config ...` | Locate, validate, or display redacted configuration. |
| `mkr check PROVIDER` | Explicit read-only quota probe where supported; never automatic. |
| `mkr run PROVIDER` | Session-pinned stdio connector used by client registrations. |
| `mkr serve PROVIDER` | Advanced authenticated loopback Streamable HTTP endpoint. |
| `mkr update` / `mkr upgrade` | Update the package with the installer that manages it. |
| `mkr uninstall` | Confirm and remove managed client entries and the package. |
| `mkr uninstall --yes --data` | Noninteractive uninstall that also removes config and state. |

## Architecture

### Stdio upstream

```text
MCP client ── newline-delimited JSON-RPC ──► mkr run PROVIDER
                                                │ select once per client session
                                                │ inject only that key into a minimal environment
                                                ▼
                                      existing MCP server subprocess
```

Traffic is forwarded unchanged. Only JSON-RPC errors, failed MCP tool results, and optionally
stderr are inspected for health. Successful tool content is not scanned.

### HTTP upstream

`mkr run` connects stdio clients to Streamable HTTP or legacy HTTP+SSE upstreams. `mkr serve`
exposes a Streamable HTTP upstream through an authenticated loopback Streamable HTTP listener.
Concurrent local sessions have independent upstream sessions, pinned keys, and translated
`MCP-Session-Id` values. Protocol versions and `Last-Event-ID` are forwarded.

The listener requires `MKR_HTTP_TOKEN` (or `--auth-env NAME`), rejects non-loopback clients,
and validates Host and Origin headers. Prefer stdio when a client cannot securely configure
HTTP authorization. See [TRANSPORTS.md](docs/TRANSPORTS.md).

## Safe defaults

- Environment auto-detection or optional OS credential-vault storage; no secrets in generated
  YAML, client JSON, logs, backups, telemetry, or AI chats.
- Persistent round-robin selection; random selection remains an advanced option.
- SQLite WAL, short `BEGIN IMMEDIATE` transactions, migrations, lock timeouts, and crash-safe
  state transitions in the platform application-data directory.
- Conservative distinction between resettable quota exhaustion, temporary rate limits, invalid
  authentication, billing/credit failures, transient failures, and unknown tool errors.
- Provider reset timestamps, lazy derived resets, manual recovery, custom regex patterns, and
  optional read-only provider quota probes.
- Built-in GitHub, OpenRouter, Tavily, Brave Search, and Exa adapters plus a versioned plugin
  SDK and [offline contract-test kit](docs/ADAPTERS.md).
- Timestamped backups, atomic client/YAML writes, concurrent-edit refusal, idempotent setup,
  and complete per-invocation rollback.

Keys need **independent quota pools** for rotation to increase capacity. Multiple keys on one
account may share credits or rate limits.

### Add keys without environment variables

Store a key directly in the OS credential vault; only its vault reference is added to YAML:

```bash
# Recommended: hidden input, with an optional friendly key name
mkr keys add openrouter --name work

# Convenience: pass the value directly
mkr keys add openrouter ACTUAL_KEY --name work
```

Omit `--name` to generate names such as `key-2` and vault references such as
`openrouter/key-2`. Direct command arguments may be saved in shell history or exposed in process
listings, so hidden input is safer. Existing sources remain available:

```bash
mkr keys add openrouter --env OPENROUTER_KEY_2
mkr keys add openrouter --keyring openrouter/secondary
```

## Configuration v2

A generated configuration can be as small as:

```yaml
version: 2
providers:
  github:
    keys:
      - env: GITHUB_TOKEN_1
      - keyring: github/secondary
    server:
      command: github-mcp-server
      args: [stdio]
```

The adapter, credential injection name, strategy, state path, and reset policy have safe
provider defaults. Generic providers specify `credential_env`; advanced stdio environment,
process cleanup, HTTP headers, and quota patterns remain available when genuinely needed.
See [CONFIGURATION.md](docs/CONFIGURATION.md) and [examples/](examples/).

Configuration v2 is an intentional clean break from v0.1. Setup backs up legacy files before
replacing them and never deletes existing SQLite health history. The v0.1 MVP remains available
at tag `v0.1.0`.

## Client compatibility

Automatic configuration supports **15 catalogued coding clients plus Claude Desktop**. The
versioned catalog in `src/mcp_key_rotator/mcp_clients.json` records Windows, macOS, and Linux
paths, formats, executables, and documentation sources. A generic JSON generator supports other
clients. See the [compatibility matrix](docs/CLIENTS.md) for formats and validation boundaries.

## Health semantics

| Observation | Stored effect | Future sessions |
| --- | --- | --- |
| Resettable spending/monthly quota exhausted | `exhausted` with reset timestamp | Excluded until reset or manual recovery |
| HTTP 429 / documented temporary limit | Active with cooldown | Temporarily skipped, **not** monthly exhausted |
| Invalid authentication | `invalid` | Excluded until recovery/replacement |
| Credit, billing, or nonresetting budget failure | `billing` | Excluded pending billing action |
| Transient provider failure | Active with short cooldown | Temporarily skipped |
| Unknown protocol/tool error | No provider-specific transition | Forwarded unchanged |

A failure never switches the current session's key. `mkr check` is on demand because provider
read endpoints can themselves be rate limited. Usage counters count observed MCP tool outcomes,
not provider tokens or credits.

## Telemetry and process cleanup

Set `MKR_TELEMETRY=true` and `MKR_LOG_PATH=/private/path/events.jsonl` to opt into local JSON
operational events. Only allowlisted session lifecycle, key name, classification, return code,
duration, transport, and termination reason fields are accepted. There is no hosted metrics
service or mandatory daemon.

Set `server.cleanup_tree: true` after compatibility testing to place stdio children in a POSIX
process group or Windows job/tree. The default remains direct-child supervision.

## Limitations

- Stdio uses newline-delimited JSON-RPC, as required by the supported MCP stdio transport.
- No automatic request replay, reconnect, or cross-key retry: a disconnected or failed tool
  call may already have executed or incurred cost.
- HTTP resumption delegates event replay to the upstream server; the proxy does not maintain
  its own event cache.
- `mkr serve` currently requires an HTTP upstream; use `mkr run` for stdio upstreams.
- OAuth-only remote MCP authorization is not converted into static API-key rotation.
- Error detection depends on upstream servers preserving useful error details.
- Desktop clients require a restart and some cannot be launched automatically in CI.

## Development and verification

```bash
python -m pip install -e ".[dev]"
ruff check .
python -m unittest discover -v
python -m build
```

Tests use local mocks and subprocesses only; normal CI makes no paid provider calls. The
release pipeline covers Windows/macOS/Linux, Python 3.11–3.14, exact-wheel uv/pipx installs,
secret and dependency scans, package/Docker execution, SBOMs, and provenance attestations.

See [CONTRIBUTING.md](CONTRIBUTING.md), [ARCHITECTURE.md](docs/ARCHITECTURE.md),
[PROVIDERS.md](docs/PROVIDERS.md), [SECURITY.md](SECURITY.md), [RELEASING.md](docs/RELEASING.md),
and [CHANGELOG.md](CHANGELOG.md). An [optional Docker image](docs/DOCKER.md) is included; host
installation is generally simpler when wrapping other local runtimes.

## License

[MIT](LICENSE)
