Skip to main content
Glama
gralliry

opencode-balance-mcp

by gralliry

opencode-balance-mcp

MCP-сервер (stdio), который предоставляет данные вашей подписки OpenCode в виде инструментов — вашу квоту Go и предоплаченный баланс Zen — любому MCP-совместимому клиенту (pi, Claude Desktop, opencode, Cursor и другим).

  • query_go_usage — квота OpenCode Go в скользящем (5 ч), недельном и месячном окнах. Загружает страницу /workspace/{id}/go и разбирает встроенную полезную нагрузку RSC.

  • query_zen_balance — предоплаченный баланс OpenCode Zen. Загружает страницу панели управления рабочей областью и разбирает встроенные скаляры SolidJS SSR.

Запросы повторяются с экспоненциальной задержкой при временных сбоях (5xx, 429 — с учётом Retry-After) и завершаются по таймауту через 15 секунд.

Ноль зависимостей. Node.js ≥ 18.

Установка и запуск

npx -y opencode-balance-mcp \
  --workspace-id wrk_xxx \
  --auth-cookie "Fe26.2**..."

Related MCP server: kitepass-mcp

Учётные данные

Серверу нужны ваш ID рабочей области OpenCode и auth cookie. Приоритет:

  1. Аргументы CLI: --workspace-id / --auth-cookie

  2. Переменные окружения: OPENCODE_GO_WORKSPACE_ID / OPENCODE_GO_AUTH_COOKIE

⚠️ authCookie — это ваша сессионная cookie OpenCode (начинается с Fe26.2**). Она истекает — обновите её, войдя на https://opencode.ai → DevTools → Application → Cookies → auth.

Инструменты

query_go_usage

Без аргументов. Возвращает квоту подписки Go для всех трёх окон:

{
  "timestamp": "...",
  "workspaceId": "wrk_...",
  "rolling":  { "status": "ok", "usagePercent": 1, "limitUsd": 12, "estSpentUsdLow": 0.12, "estSpentUsdHigh": 0.24, "resetsInSeconds": 8660, "resetsIn": "2h 24m" },
  "weekly":   { "status": "ok", "usagePercent": 1, "limitUsd": 30, "...": "..." },
  "monthly":  { "status": "ok", "usagePercent": 0, "limitUsd": 60, "...": "..." }
}
  • usagePercent — целое число: 0% означает, что использовано менее 1% лимита окна (5 ч $12 / неделя $30 / месяц $60). См. opencode.ai/docs/go.

  • estSpentUsdLow/High — диапазон предполагаемых расходов для текущего процента использования.

  • resetsIn — понятный человеку обратный отсчёт от resetsInSeconds.

query_zen_balance

Без аргументов. Читает страницу панели управления рабочей областью и разбирает баланс Zen (данные гидратации SolidJS SSR):

{
  "timestamp": "...",
  "workspaceId": "wrk_...",
  "plan": "pay-as-you-go",
  "balanceRaw": 0,
  "balanceUsd": 0,
  "balanceFormatted": "$0.00",
  "autoReload": { "triggerUsd": 5, "triggerMinUsd": 5, "reloadUsd": 20, "reloadMinUsd": 10 },
  "reloadAmount": 20,
  "reloadTrigger": 5
}
  • balanceRaw — целое число в единицах 1e-8 USD (та же единица, которую использует клиент панели: formatBalance = amount / 1e8). Отрицательное = предоплаченный кредит, положительное = сумма к оплате.

  • balanceUsd / balanceFormatted — производные от него; знак отображается как (credit) / (owed) в метке.

  • autoReload — отражает автоматическое пополнение Zen: когда баланс опускается ниже triggerUsd, добавляется reloadUsd.

Официального API баланса Zen нет, поэтому сервер парсит панель так же, как проверяет квоту Go. Парсер находится в src/parse.mjs и может потребовать обновления, если структура страницы изменится.

Настройка в MCP-клиентах

opencode (~/.config/opencode/opencode.json)

{
  "mcp": {
    "opencode-balance": {
      "type": "local",
      "command": ["npx", "-y", "opencode-balance-mcp"],
      "environment": {
        "OPENCODE_GO_WORKSPACE_ID": "wrk_xxx",
        "OPENCODE_GO_AUTH_COOKIE": "Fe26.2**..."
      }
    }
  }
}

Стандартный MCP (stdio) — любой клиент

{
  "mcpServers": {
    "opencode-balance": {
      "command": "npx",
      "args": ["-y", "opencode-balance-mcp"],
      "env": {
        "OPENCODE_GO_WORKSPACE_ID": "wrk_xxx",
        "OPENCODE_GO_AUTH_COOKIE": "Fe26.2**..."
      }
    }
  }
}

Claude Code (.mcp.json в корне проекта)

{
  "mcpServers": {
    "opencode-balance": {
      "command": "npx",
      "args": ["-y", "opencode-balance-mcp"],
      "env": {
        "OPENCODE_GO_WORKSPACE_ID": "wrk_xxx",
        "OPENCODE_GO_AUTH_COOKIE": "Fe26.2**..."
      }
    }
  }
}

Или через CLI: claude mcp add opencode-balance -e OPENCODE_GO_WORKSPACE_ID=wrk_xxx -e OPENCODE_GO_AUTH_COOKIE="Fe26.2**..." -- npx -y opencode-balance-mcp

Codex (~/.codex/config.toml)

[mcp_servers.opencode-balance]
command = "npx"
args = ["-y", "opencode-balance-mcp"]
enabled = true

[mcp_servers.opencode-balance.env]
OPENCODE_GO_WORKSPACE_ID = "wrk_xxx"
OPENCODE_GO_AUTH_COOKIE = "Fe26.2**..."

pi (~/.pi/agent/mcp.json)

{
  "mcpServers": {
    "opencode-balance": {
      "command": "npx",
      "args": ["-y", "opencode-balance-mcp"],
      "env": {
        "OPENCODE_GO_WORKSPACE_ID": "wrk_xxx",
        "OPENCODE_GO_AUTH_COOKIE": "Fe26.2**..."
      }
    }
  }
}

Разработка

npm start      # run the server directly
npm test       # unit tests (parser, zen formatting, HTTP retry policy) + a protocol smoke test

Смоук-тест протокола (test/test.mjs) запускает сервер через stdio и проверяет initialize, tools/list, tools/call и обработку ошибок tools/call. Без учётных данных он ожидаемо завершает два вызова инструментов с результатом isError.

Архитектура

  • src/index.mjs — протокол MCP stdio, учётные данные (CLI/окружение), склейка загрузки страниц

  • src/http.mjs — сетевая политика: таймаут, повтор с экспоненциальной задержкой, обработка 429/Retry-After

  • src/parse.mjs — чистые функции разбора и форматирования (без ввода-вывода, тестируются напрямую)

Публикация

npm publish

Лицензия

MIT

Available Tools

2 tools
query_go_usageA

Query OpenCode Go subscription quota: rolling (5h) / weekly / monthly usage percent, estimated USD spent and reset countdown. No arguments needed; credentials are provided at startup via CLI args (--workspace-id / --auth-cookie) or env vars.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.2/5.0
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It adds value by disclosing that credentials are pre-configured via CLI args or env vars, which prevents unnecessary auth handling. However, it does not mention potential error conditions, whether the action is read-only (though implied by 'query'), or any rate limits. It neither contradicts nor fully discloses behavior.

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?

Two sentences with no wasted words. The first sentence states purpose and outputs; the second clarifies argument and credential requirements. Information is front-loaded and every word serves a purpose.

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?

For a zero-parameter query tool with no output schema, the description covers the essential details: what it returns and that no arguments are needed. It does not specify the exact format of the reset countdown (e.g., seconds, minutes), which could cause minor ambiguity, but overall the tool is simple enough that the description is nearly complete.

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 tool has zero parameters, so baseline is 4. The description reinforces this by explicitly stating 'No arguments needed,' which adds clarity beyond the empty schema. Since there are no parameters to document, this is fully adequate.

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

Purpose5/5

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

The description clearly states the tool queries OpenCode Go subscription quota and enumerates specific outputs (usage percent, estimated USD spent, reset countdown). It uses a specific verb 'query' and resource 'Go subscription quota,' making it distinguishable from the sibling tool query_zen_balance.

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

Usage Guidelines4/5

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

It explicitly states 'No arguments needed' and explains how credentials are provided, which tells the agent it doesn't need to pass authentication. It does not explicitly name the sibling or contrast usage, but the purpose is clear enough that the agent can infer when to use it. Lacks an explicit 'when not to use' but provides sufficient context.

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

query_zen_balanceA

Query OpenCode Zen prepaid balance (pay-as-you-go): balance in 1e-8 USD units (negative = credit), formatted USD, and auto-reload settings. No arguments needed; credentials are provided at startup via CLI args (--workspace-id / --auth-cookie) or env vars.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.5/5.0
Behavior4/5

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

With no annotations, the description carries the full burden and discloses useful behavioral details: balance units in 1e-8 USD, negative values meaning credit, formatted USD output, and auto-reload settings. It also clarifies credential sourcing, which is important operational behavior.

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?

Two efficiently written sentences convey the purpose, output, required arguments, and credential mechanism with no filler. Every clause earns its place and the core subject is front-loaded.

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

Completeness5/5

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

For a zero-parameter read-only query tool with no output schema, the description is complete: it names the resource, details the returned data, explains the unit semantics, states no arguments are needed, and tells where credentials come from. Nothing necessary for correct invocation is missing.

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?

There are zero parameters and schema coverage is 100%, so the baseline is 4. The description reinforces that no arguments are needed and goes further by explaining how authentication is already handled, which adds meaning beyond the empty schema.

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

Purpose5/5

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

The description names a specific verb (Query), a specific resource (OpenCode Zen prepaid balance), and the scope (pay-as-you-go balance). It lists the exact data returned, which distinguishes it from the sibling query_go_usage without needing to compare schemas.

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

Usage Guidelines4/5

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

The description clearly states that no arguments are needed and explains how credentials are supplied, which is essential contextual guidance for invoking the tool. It does not explicitly name the sibling as an alternative, but the resource and data scope make the intended use clear.

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

TDQS

A4.4/5.0
Disambiguation5/5

The two tools query distinct resources: one for Go subscription quota and one for Zen prepaid balance. Their descriptions clearly differentiate the data returned (usage percentages vs. balance in USD units), making confusion unlikely.

Naming Consistency5/5

Both tool names follow the exact same pattern: 'query_' prefix followed by the resource type ('go_usage' and 'zen_balance'). This is fully consistent and predictable.

Tool Count4/5

With only two tools, the surface is minimal, but the server's scope is narrowly defined as querying two distinct balance types. The count feels appropriate given the focused purpose, though slightly thin if broadenability was expected.

Completeness4/5

The server covers the two core balance query operations for its domain. Missing a combined query or historical data are minor gaps that agents can work around, but the essential read operations are present.

Maintenance

ActivityMaintained
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

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/gralliry/opencode-balance-mcp'

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