{
  "markdown": "[![npm](https://img.shields.io/npm/v/@runcycles/mcp-server)](https://www.npmjs.com/package/@runcycles/mcp-server)\n[![npm Downloads](https://img.shields.io/npm/dm/@runcycles/mcp-server)](https://www.npmjs.com/package/@runcycles/mcp-server)\n[![CI](https://github.com/runcycles/cycles-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/runcycles/cycles-mcp-server/actions)\n[![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)\n[![MCP](https://img.shields.io/badge/MCP-compatible-green)](https://modelcontextprotocol.io)\n[![Coverage](https://img.shields.io/badge/coverage-97%25-brightgreen)](https://github.com/runcycles/cycles-mcp-server/actions)\n[![SafeSkill 97/100](https://img.shields.io/badge/SafeSkill-97%2F100_Verified%20Safe-brightgreen)](https://safeskill.dev/scan/runcycles-cycles-mcp-server)\n\n# Cycles MCP Server — AI agent runtime control over Model Context Protocol\n\n**MCP server that gives any MCP-compatible AI agent (Claude Code, Cursor, Windsurf, custom agents) runtime budget, action, and audit authority — enforce LLM cost limits, tool call caps, action permissions, and audit trails before execution, with zero agent code changes.** Connect via MCP and use the budget tools (`cycles_reserve`, `cycles_commit`, `cycles_release`, `cycles_decide`) directly from the agent's tool-calling loop. Powered by [Cycles](https://runcycles.io). See [Security Model & Enforcement Boundary](#security-model--enforcement-boundary) for what is enforced server-side versus cooperatively in the agent loop.\n\n## Why use this?\n\nAutonomous AI agents (Claude, GPT, custom agents) call LLMs, invoke tools, and hit external APIs — but have no built-in way to cap how much they spend. A single agent loop can burn through hundreds of dollars before anyone notices. Multiply that across tenants and teams, and cost control becomes a real problem.\n\nThis MCP server gives any MCP-compatible agent a **runtime budget authority**: a set of tools to check, reserve, spend, and release budget before and after every costly operation. The agent asks \"can I afford this?\" before acting, and reports what it actually used afterward.\n\n**Who needs this:**\n\n- **Platform teams** building multi-tenant agent systems that need per-customer or per-workspace spend limits\n- **Agent developers** who want agents to self-regulate — degrade to cheaper models when budget is low, skip optional tool calls, reduce retries\n- **Enterprises** deploying AI agents that need guardrails so a runaway agent can't blow through a budget\n\n**Why MCP specifically:**\n\nMCP is the standard protocol that AI hosts (Claude Desktop, Claude Code, Cursor, Windsurf, custom agents) use to discover and call tools. By exposing Cycles as an MCP server, any MCP-compatible agent gets budget awareness as a plug-in — just add the server to your config. No SDK integration in the agent's own code required.\n\nThe server also ships built-in [prompts](#prompts) so an AI assistant can help you design your budget strategy, generate integration code, and diagnose budget overruns — not just enforce budgets at runtime.\n\n## Use Cases\n\n### Coding agent with a per-task dollar cap\n\nYou run a Claude Code agent that writes and iterates on code. Each task should cost no more than $5. The agent calls `cycles_reserve` before every LLM call with a cost estimate in `USD_MICROCENTS`. If the reservation comes back `DENY`, the agent stops and reports \"budget exhausted\" instead of silently racking up charges. When the call completes, `cycles_commit` records the actual token cost so the running total stays accurate.\n\n### Multi-tenant SaaS with per-customer budgets\n\nYour platform lets customers deploy AI assistants. Each customer has a monthly budget. The agent calls `cycles_check_balance` at the start of a conversation to see what's left, then `cycles_reserve` before each tool invocation (web search, code execution, API calls). If customer Acme is near their limit, the decision comes back `ALLOW_WITH_CAPS` — the agent automatically drops to a cheaper model and skips optional tools. Customer budgets are isolated; one customer's heavy usage never affects another.\n\n### Multi-agent pipeline with shared budget\n\nYou have an orchestrator that fans out to specialist agents — a researcher, a coder, and a reviewer. All three draw from the same workflow budget. Each agent calls `cycles_reserve` before its work; the Cycles server tracks concurrent reservations so the total never exceeds the workflow limit. If the researcher burns through 80% of the budget, the coder's next reservation gets `DENY` and the orchestrator can decide to skip the review step instead of going over budget.\n\n### Long-running data pipeline with heartbeats\n\nAn agent processes a large dataset in chunks, each chunk taking several minutes. It calls `cycles_reserve` with a 5-minute TTL before each chunk, then `cycles_extend` every 60 seconds to keep the reservation alive while processing. If the agent crashes, the reservation expires automatically and the locked budget returns to the pool — no manual cleanup needed.\n\n### Fire-and-forget usage metering\n\nYou have an existing system that already makes LLM calls and you just want to track spend, not gate it. After each call completes, the agent fires `cycles_create_event` with the actual cost. No reservation needed — the event is applied atomically to all budget scopes (tenant, workspace, app). You get a real-time spend dashboard without changing your existing call flow.\n\n### Grok Bot with a non-bypassable paid-media action\n\nGrok Bot can call custom MCP tools, but installing the standalone Cycles tools beside a paid-media connector remains cooperative: the Bot could call the other connector directly. The [Grok Bot paid-media gateway](examples/grok-bot-paid-media-gateway/) shows the hard-enforcement shape instead. Its mutation handler derives scope from trusted server configuration, requires a live `RISK_POINTS` reservation, propagates the reservation ID to the downstream API, and conservatively settles ambiguous outcomes.\n\n## Installation\n\n```bash\nnpm install @runcycles/mcp-server\n```\n\n## Setup\n\n### Claude Desktop\n\n**One-click (recommended):** download `cycles-mcp-server-<version>.mcpb` from the [latest release](https://github.com/runcycles/cycles-mcp-server/releases/latest) and open it with Claude Desktop (double-click, or Settings → Extensions → drag it in). Claude Desktop shows a config screen for your Cycles server URL and API key — or enable mock mode to explore the tools without a server (no enforcement).\n\n**Manual (JSON config):** add to your `claude_desktop_config.json`:\n- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`\n- Windows: `%APPDATA%\\Claude\\claude_desktop_config.json`\n\n```json\n{\n  \"mcpServers\": {\n    \"cycles\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@runcycles/mcp-server\"],\n      \"env\": {\n        \"CYCLES_BASE_URL\": \"http://localhost:7878\",\n        \"CYCLES_API_KEY\": \"your-api-key-here\"\n      }\n    }\n  }\n}\n```\n\nFor local development without an API key, use mock mode:\n\n```json\n{\n  \"mcpServers\": {\n    \"cycles\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@runcycles/mcp-server\"],\n      \"env\": {\n        \"CYCLES_MOCK\": \"true\"\n      }\n    }\n  }\n}\n```\n\n### Claude Code\n\n```bash\nclaude mcp add cycles -- npx -y @runcycles/mcp-server\n```\n\nSet your environment variables:\n\n```bash\nexport CYCLES_BASE_URL=http://localhost:7878\nexport CYCLES_API_KEY=your-api-key-here\n```\n\n### Cursor / Windsurf / Other MCP Hosts\n\nUse stdio transport with:\n\n```\ncommand: npx\nargs: [\"-y\", \"@runcycles/mcp-server\"]\nenv: { CYCLES_API_KEY: \"your-key\", CYCLES_BASE_URL: \"http://localhost:7878\" }\n```\n\n## Configuration\n\n```bash\nexport CYCLES_API_KEY=your-api-key-here       # required (unless CYCLES_MOCK=true)\nexport CYCLES_BASE_URL=http://localhost:7878   # required — your Cycles server URL\nexport CYCLES_MOCK=false                       # true disables live enforcement and returns synthetic responses\nexport CYCLES_ALLOW_MOCK_IN_PRODUCTION=false  # must be true to use mock mode with NODE_ENV=production\nexport PORT=3000                               # optional, for HTTP transport\nexport HOST=127.0.0.1                          # optional HTTP bind address; unset binds all interfaces\nexport MCP_HTTP_AUTH_TOKEN=replace-me          # optional bearer token required on /mcp when set\n\n# Optional subject defaults — merged into any tool call that omits the field,\n# so agents can call cycles_reserve with just an action and amount:\nexport CYCLES_DEFAULT_TENANT=acme\nexport CYCLES_DEFAULT_WORKSPACE=prod\nexport CYCLES_DEFAULT_APP=support-bot\nexport CYCLES_DEFAULT_WORKFLOW=\nexport CYCLES_DEFAULT_AGENT=\nexport CYCLES_DEFAULT_TOOLSET=\n```\n\nAgent-ergonomics behavior: explicit subject fields always win over `CYCLES_DEFAULT_*` values, and `cycles_check_balance` accepts an empty call when defaults supply a filter. `idempotencyKey` remains **required on every mutating tool** — same-key replay is the protocol's retry deduplication and evidence-suppression mechanism, and only the caller can hold a key stable across retries. Responses carry plain-text hints after the JSON payload when the budget is under pressure (DENY, `ALLOW_WITH_CAPS`, or under ~15% remaining), so agents self-regulate without host support.\n\nMock mode prints a prominent warning on every startup, and generated mock reservation/event IDs begin with `mock_`. The server refuses to start with `CYCLES_MOCK=true` and `NODE_ENV=production` unless `CYCLES_ALLOW_MOCK_IN_PRODUCTION=true` is also set.\n\nFor HTTP transport, set `MCP_HTTP_AUTH_TOKEN` to require `Authorization: Bearer <token>` on every `/mcp` request. Blank or whitespace-only configured tokens are rejected at startup. `/health` remains public. If no token is configured while HTTP binds to a non-loopback address, the server prints a prominent warning.\n\n**Need an API key?** API keys are created via the Cycles Admin Server (port 7979). See the [deployment guide](https://runcycles.io/quickstart/deploying-the-full-cycles-stack#step-3-create-an-api-key) to create one, or run:\n\n```bash\ncurl -s -X POST http://localhost:7979/v1/admin/api-keys \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-Admin-API-Key: admin-bootstrap-key\" \\\n  -d '{\"tenant_id\":\"acme-corp\",\"name\":\"dev-key\",\"permissions\":[\"reservations:create\",\"reservations:commit\",\"reservations:release\",\"reservations:extend\",\"reservations:list\",\"balances:read\",\"decide\",\"events:create\"]}' | jq -r '.key_secret'\n```\n\nThe key (e.g. `cyc_live_abc123...`) is shown only once — save it immediately. For key rotation and lifecycle details, see [API Key Management](https://runcycles.io/how-to/api-key-management-in-cycles).\n\n> **Individual vs. team use:** For individual use or evaluation, set `CYCLES_MOCK=true` — no server or API key required. If you're deploying agents for multiple users or workspaces, see the [multi-tenant setup guide](https://runcycles.io/how-to/understanding-tenants-scopes-and-budgets-in-cycles).\n\n## Running\n\n```bash\n# stdio transport (default — for Claude Desktop / Claude Code)\nnpx @runcycles/mcp-server\n\n# HTTP transport (Streamable HTTP on port 3000)\nnpx @runcycles/mcp-server --transport http\n```\n\n## Tools\n\n| Tool | Protocol Endpoint | Description |\n|------|-------------------|-------------|\n| `cycles_reserve` | `POST /v1/reservations` | Reserve budget before a costly operation |\n| `cycles_commit` | `POST /v1/reservations/{id}/commit` | Commit actual usage after operation completes |\n| `cycles_release` | `POST /v1/reservations/{id}/release` | Release reservation without committing |\n| `cycles_extend` | `POST /v1/reservations/{id}/extend` | Extend reservation TTL (heartbeat) |\n| `cycles_decide` | `POST /v1/decide` | Lightweight preflight budget check |\n| `cycles_check_balance` | `GET /v1/balances` | Check current budget balance for a scope |\n| `cycles_list_reservations` | `GET /v1/reservations` | List reservations with filters |\n| `cycles_get_reservation` | `GET /v1/reservations/{id}` | Get reservation details by ID |\n| `cycles_create_event` | `POST /v1/events` | Record usage without reserve/commit lifecycle |\n\n## Agent Decision Loop\n\nEvery costly operation follows a reserve → execute → finalize lifecycle:\n\n```\n1. cycles_reserve   → Lock budget before each costly step\n2. Execute          → Perform the operation (respecting any caps)\n3. cycles_commit    → Record actual usage — releases unused portion back to the pool\n   OR cycles_release → Cancel the reservation if the step was skipped\n```\n\nOptionally, before reserving:\n- `cycles_check_balance` — inspect remaining budget to plan your approach\n- `cycles_decide` — lightweight preflight check without locking funds\n\nEvery reservation **must** be finalized with either `cycles_commit` or `cycles_release` — never leave reservations dangling. For long-running operations, use `cycles_extend` to heartbeat the reservation TTL so it doesn't expire mid-operation. See [integration patterns](docs/patterns.md) for detailed examples.\n\n## Security Model & Enforcement Boundary\n\nCycles authority is enforced at two different boundaries, and it matters which one you are relying on.\n\n### Enforced unconditionally (server-side)\n\nEvery `cycles_reserve`, `cycles_commit`, and `cycles_decide` call is a *request for authority*, evaluated by the Cycles runtime against the authenticated tenant's policies and current balances. This holds regardless of what the model generates:\n\n- **Malformed amounts never leave the MCP server.** Input schemas reject negative, fractional, or non-numeric amounts, and any value above JavaScript's safe-integer range (2⁵³ − 1), before a request is made.\n- **A well-formed but excessive reservation is refused by the Cycles server** with a `BUDGET_EXCEEDED` error — no reservation ID is issued and nothing is spent. A hallucinated or prompt-injected oversized reserve cannot make Cycles grant more authority than policy allows.\n- **A reservation by itself spends nothing.** Budget only moves on `cycles_commit` (or `cycles_create_event`), and commits are bounded by the reservation plus the configured overage policy.\n\n### Cooperative (inside the agent's tool loop)\n\nThis MCP server exposes budget tools *alongside* the host's other tools — it does not sit between the model and those tools. When a reservation is denied, the agent is instructed not to proceed, but nothing in the MCP protocol forces it to. A prompt-injected or misbehaving agent could skip `cycles_reserve` entirely and invoke a consequential tool directly.\n\n### Making enforcement non-bypassable\n\nFor the budget check to be a hard gate rather than a convention, put Cycles in the actual dispatch path so the downstream operation cannot execute without a valid reservation:\n\n- **Gate in the host application** — before executing a consequential operation, require a reservation ID and verify it with `cycles_get_reservation`.\n- **Use a dispatch-path integration** — framework middleware that wraps tool execution (e.g. the Cycles Spring Boot starter or LangChain integration) enforces reserve-before-execute in code the model cannot skip.\n- **Meter server-side as a backstop** — where gating isn't possible, record actual usage with `cycles_create_event` so overruns are at least detected and budgets stay accurate.\n\n### Mock mode enforces nothing\n\nWith `CYCLES_MOCK=true`, every call returns a synthetic `ALLOW` — it exists for development and demos only. The server refuses to start in mock mode when `NODE_ENV=production` (unless explicitly overridden) precisely so a synthetic `ALLOW` is never mistaken for a real one.\n\n## Resources\n\n| URI | Description |\n|-----|-------------|\n| `cycles://balances/{tenant}` | Current budget balance for a tenant |\n| `cycles://reservations/{reservation_id}` | Reservation details |\n| `cycles://docs/quickstart` | Getting started guide |\n| `cycles://docs/patterns` | Integration patterns |\n\n## Prompts\n\n| Prompt | Description |\n|--------|-------------|\n| `integrate_cycles` | Generate Cycles integration code |\n| `diagnose_overrun` | Analyze budget exhaustion |\n| `design_budget_strategy` | Recommend scope hierarchy and limits |\n\n## Development\n\n```bash\nnpm install\nnpm run dev              # stdio transport with tsx\nnpm run dev:http         # HTTP transport with tsx\nnpm run build            # TypeScript build\nnpm run lint             # ESLint\nnpm test                 # Run tests\nnpm run test:coverage    # Run with coverage (95%+ lines, 85%+ branches)\nnpm run typecheck        # Type check without emitting\n```\n\n## Publishing\n\nThe server is published to two registries:\n\n| Registry | Identifier | How |\n|----------|-----------|-----|\n| **npm** | `@runcycles/mcp-server` | CI publishes on `v*` tag push with provenance |\n| **MCP Registry** | `io.github.runcycles/cycles-mcp-server` | CI publishes the `server.json` manifest after npm |\n\nReleases are automated with [release-please](https://github.com/googleapis/release-please). PRs are **squash-merged** (repo enforces squash-only) with **conventional PR titles** (`feat:`, `fix:`, …) — the PR title becomes the single commit on `main` that release-please reads. It maintains a release PR that accumulates the changelog and bumps the version in `package.json`, `server.json` (both fields), and the `AUDIT.md` header. **Merging the release PR** creates the tag and GitHub release, then dispatches the publish pipeline.\n\nCI runs on the tag: test (Node 20+22) → npm publish (Trusted Publishing/OIDC, with provenance) → smoke test against the published tarball → MCP Registry publish → MCPB desktop-extension bundle attached to the GitHub release.\n\nManual fallback (works unchanged): bump versions yourself, then tag and push:\n\n```bash\ngit tag v0.5.0\ngit push origin v0.5.0\n```\n\n## Documentation\n\n- [Cycles Documentation](https://runcycles.io) — full docs site\n- [MCP Server Quickstart](https://runcycles.io/quickstart/getting-started-with-the-mcp-server) — getting started guide\n- [Integrating Cycles with MCP](https://runcycles.io/how-to/integrating-cycles-with-mcp) — detailed MCP integration guide\n\n## Protocol Conformance\n\nThis MCP server is audited against the Cycles Protocol v0.1.24 OpenAPI spec. See [AUDIT.md](AUDIT.md) for the full conformance report.\n\n## Privacy Policy\n\nFull policy: **[runcycles.io/privacy](https://runcycles.io/privacy)**\n\nThe short version: this server connects only to the Cycles server URL you configure and sends it budget requests (subject identifiers, amounts, usage metrics) — Cycles is self-hosted, so that data stays in your infrastructure and never reaches runcycles. No LLM prompts or responses are stored. The server contains no telemetry, phone-home, or update checks. In mock mode, no network requests are made at all. Your API key lives in your local configuration and is sent only to your configured Cycles server.\n\n## License\n\nApache-2.0\n",
  "bytes": 18812,
  "sha": "2ded14e2c157366f2d6a6b6e93cc22678b10a3d83b1dfbbad8c66b8959e5b675",
  "repo_slug": "runcycles/cycles-mcp-server",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_runcycles_cycles_mcp_server_8b46a9d5/readme"
}