Skip to main content
Glama
comtechai

counterparty-credit

by comtechai

Counterparty Credit

Открытый, прозрачный MCP-сервер, который оценивает кредитное здоровье публичных энергетических компаний на основе публичных данных. Спросите агента, насколько надёжен коммунальный оператор, генератор, оператор midstream или трейдер электроэнергией/газом; Counterparty Credit отвечает оценкой от 0 до 100, разбивкой по факторам и публичным источником за каждым числом.

Это инструмент поддержки решений, а не кредитный рейтинг — каждый результат имеет источник, объясним и предназначен для проверки человеком. Смысл в оценке, с которой можно спорить, а не в чёрном ящике.

Создано ComtechAI. Версия методологии: ccr-ref-1.3.

Статус: v1, намеренно стабильный

Этот репозиторий — эталонная реализация с зафиксированным объёмом. Он остаётся опубликованным и рабочим; приветствуются исправления ошибок и патчи для устранения поломок из-за изменений в зависимостях, но новые возможности выходят за рамки. См. DEVELOPMENT.md для настройки, тестов и правил внесения вклада.

Related MCP server: Pulse MCP Server

Как это работает

Один MCP-инструмент, counterparty.health, принимает название компании или тикер. Он определяет эмитента SEC, получает публичные финансовые данные и рыночные данные, оценивает четыре фактора и объединяет их в композитный показатель с описательным диапазоном (Strong / Stable / Watch / Stressed / Distressed).

Фактор

Что анализирует

Источник

F1 — Прочность баланса

Леверидж, процентное покрытие, коэффициент текущей ликвидности

SEC EDGAR (XBRL)

F3 — Рыночный риск

Дистанция до дефолта (наивный Мертон) + волатильность акций

Tiingo daily prices + EDGAR

F4 — Бизнес-микс / товарная экспозиция

Структурная изоляция денежных потоков по типу бизнеса

Классификационная вселенная (27 имён)

F5 — События / новости

Рейтинговые действия, события по ковенантам/ликвидности, внеплановые отключения

Google News RSS

Композитный показатель — это перенормированное взвешенное сочетание тех факторов, которые реально вычисляются в данном запуске. Эталонные веса: F1 0.20 · F3 0.15 · F4 0.25 · F5 0.15. Когда входные данные фактора отсутствуют — нет рыночного потока для F3, неклассифицированное имя для F4 — этот фактор исключается, а его вес перераспределяется между остальными. Ничего не подставляется; фактор либо вычисляется на основе реальных данных, либо отсутствует.

Каждый результат содержит methodology_version и дату as_of, и каждый фактор указывает на документ или поток данных, лежащий в его основе. Если показатель является прокси (см. ограничения), строка источника это отмечает.

Установка

Требуется Python 3.10–3.14.

python3 -m venv venv && source venv/bin/activate   # Windows: venv\Scripts\activate
pip install -e .

Использование

Из командной строки

export SEC_USER_AGENT="Your Name you@example.com"   # SEC requires a contact User-Agent
export TIINGO_TOKEN="your_tiingo_key"               # optional; F3 is skipped without it
python3 -m counterparty_credit.cli "NextEra Energy"
python3 -m counterparty_credit.cli DUK

SEC возвращает HTTP 403 без описательного User-Agent. Бесплатный токен Tiingo включает F3; если его опустить, инструмент оценивает по F1/F4/F5 и сообщает об этом. Документы и карта тикеров кэшируются в ~/.cache/counterparty-credit на 24 часа.

Из Claude Desktop

Скопируйте claude_desktop_config.example.json в конфигурацию Claude Desktop, укажите command на Python из виртуального окружения этого репозитория (абсолютный путь) и свои ключи в env, затем перезапустите Claude и спросите "Насколько финансово устойчива NextEra как контрагент?" Claude вызовет инструмент и прочитает оценку, разбивку и источники.

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

Если компанию не удаётся определить или её данные не могут быть получены, инструмент возвращает ошибку, а не число. Оценка возвращается только тогда, когда она действительно была вычислена.

Методология

Оценка считывается из конфигурационного объекта Methodology, а не из захардкоженных констант. Methodology.default() — это открытый эталон, зафиксированный на ccr-ref-1.3. Зафиксированная запись:

  • src/counterparty_credit/methodology.py — источник истины для всех кривых, весов, порогов

  • docs/methodology-c0.md — человекочитаемая методология записи

  • docs/methodology-c0.json — машинная спецификация (тест защищает от дрейфа)

Пользовательская методология указывает только свои переопределения и наследует остальное из эталона:

CCR_METHODOLOGY=/path/to/methodology.json python3 -m counterparty_credit.cli "NextEra Energy"

Поскольку каждый результат помечен своей версией, пользовательская конфигурация явно не является эталонной. Зафиксированные числа — это стартовая гипотеза, уточняемая на реальных именах; перекалибровка — это новая версия, а не тихое переписывание.

Ограничения

Они намеренны и изложены прямо. Честный объём — это суть эталонного инструмента.

  • Не кредитный рейтинг. Поддержка решений на основе публичных данных. Никакого взаимодействия с эмитентом, никакой непубличной информации, никакой методологии рейтинговых агентств.

  • F2 (ликвидность / обеспечение) исключён из живого сочетания. Его прокси-показатель v0 на основе денежных средств возвращал почти одинаковые оценки независимо от кредитного качества, поэтому он не добавляет различительной способности. Он определён в методологии, но исключён, пока реальная модель стресса по обеспечению не заменит прокси.

  • F3 требует рыночного потока. Без токена Tiingo или для имени без чистых данных о ценах F3 исключается, а его вес перераспределяется.

  • F4 охватывает фиксированную вселенную из 27 имён североамериканских энергетических эмитентов. Имена вне неё оцениваются без фактора бизнес-микса, а не угадываются.

  • F5 опирается на фиксированный словарь. Он обнаруживает рейтинговые действия, сформулированные как upgrade / downgrade (с ограничением, требующим контекста рейтингового агентства), и набор кредитных событий; он пропустит рейтинговые действия, сформулированные другими глаголами, а тональность заголовков грубая.

  • Покрытие может использовать прокси на основе выплаченных денежных средств. Некоторые крупные эмитенты не помечают концепцию процентных расходов; для них покрытие вычисляется из выплаченных денежных процентов, что исключает капитализированные проценты. Строка источника отмечает это для каждого имени.

  • Точечные публичные данные. Показатели приведены по состоянию на последний документ; устаревший документ помечается, а не молча используется.

Структура

src/counterparty_credit/
  schema.py          # locked I/O contract (HealthResult)
  methodology.py     # config object — reference default + worksheet loader
  resolve.py         # name/ticker → CIK + ticker (SEC company_tickers.json)
  edgar.py           # XBRL companyfacts → financials (recency-aware tag selection)
  ratios.py          # leverage / coverage / liquidity
  market.py          # daily prices → price + annualized vol (Tiingo)
  dtd.py             # naive-Merton distance-to-default
  news.py            # recent headlines (Google News RSS)
  scoring.py         # F1, F3, F5 scorers
  f4_business_mix.py # F4 business-mix lookup over the universe
  universe.json      # 27-name classification universe
  score.py           # orchestration → weighted composite → HealthResult
  server.py          # MCP tool
  cli.py             # one-command live scoring
tests/

Отказ от ответственности

Counterparty Credit предоставляет поддержку решений на основе публичных данных. Это не кредитный рейтинг, не инвестиционный совет и не аффилировано с каким-либо рейтинговым агентством или оцениваемыми эмитентами. Результаты имеют источники и предназначены для проверки человеком.

Available Tools

1 tool
counterparty.healthA

Assess the credit health of a public energy company from public data.

Use this when asked how financially sound or risky an energy counterparty is — a regulated utility, merchant generator/IPP, midstream operator, or power/gas marketer. Accepts a company name or ticker.

Returns a 0-100 health score and descriptive band (Strong/Stable/Watch/Stressed/ Distressed), a factor-by-factor breakdown with the public source behind each factor, a plain-language summary, the methodology version, and an as-of date. This is transparent decision-support, not a credit rating.

Raises rather than guessing when the company cannot be resolved or its public data cannot be retrieved. A score is only ever returned when it was actually computed.

ParametersJSON Schema
NameRequiredDescriptionDefault
nameYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
bandYesDescriptive band derived from the score
nameYesThe query as the caller sent it
as_ofYesAs-of date for the underlying data (YYYY-MM-DD)
scoreYesComposite 0–100 health score
tickerNoEquity ticker, if resolved
factorsYesFactor-by-factor breakdown, each independently sourced
summaryYesPlain-language read a desk could act on
disclaimerNoNon-negotiable framing — this is not a rating.
resolved_nameYesCanonical entity name after resolution
methodology_versionYesVersioned methodology id, e.g. 'tenor-0.1.0-stub'

TDQS

A4.7/5.0
Behavior5/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure, and it does so thoroughly. It explains the return contents (health score, band, factor breakdown, sources, summary, methodology version, as-of date), frames the output as 'transparent decision-support, not a credit rating,' and explicitly states it 'raises rather than guessing' when resolution or data retrieval fails.

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?

The description is front-loaded with the main action, immediately followed by usage context, output details, and an explicit failure behavior. Every sentence contributes necessary information without redundancy, and the structure makes it easy for an agent to quickly determine purpose and call behavior.

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?

Given the tool's single parameter, no annotations, no siblings, and an output schema that can carry return structure, the description covers all key contextual needs: input type, applicable domain, output semantics, methodological transparency, and error behavior. An agent has enough information to invoke the tool correctly and interpret its result.

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 input schema only provides a required string property 'name' with 0% description coverage, so the description must compensate. It does by adding that the tool 'Accepts a company name or ticker.' This is meaningful semantic guidance for the single parameter, though slightly more detail about accepted formats would push it higher.

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 starts with a specific verb and resource: 'Assess the credit health of a public energy company from public data.' It further clarifies the exact scope by listing company types (regulated utility, merchant generator/IPP, midstream operator, marketer) and the accepted inputs (company name or ticker). Even without siblings, the purpose is unambiguous.

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 explicitly states when to use the tool: 'Use this when asked how financially sound or risky an energy counterparty is.' It gives clear context and enumerates the applicable counterparty types, but it does not explicitly state when not to use it or name alternatives. Since there are no sibling tools, this is a clear and sufficient usage guideline.

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

Tool Schema Changelog

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

  1. 1 tool updatev0.1.0
    • First observedcounterparty.health

TDQS

A4.6/5.0

Scored across 1 tool

Disambiguation5/5

With only one tool, there is no possibility of confusion or overlap with other tools. The tool's purpose is clearly defined and unique within this server.

Naming Consistency5/5

A single tool name naturally presents no inconsistencies. The dotted notation 'counterparty.health' is descriptive and suggests a clear action/domain pattern.

Tool Count3/5

One tool feels thin for a server, even when narrowly scoped. The functionality is focused, but a server with a single tool offers little flexibility or breadth for an agent.

Completeness4/5

The tool covers the core domain of assessing counterparty credit health thoroughly, returning scores, factors, sources, and methodology. It lacks supplementary operations like historical comparisons or bulk screening, but these are not essential for the stated purpose.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    MCP server for Axonn, enabling access to US energy regulatory filings, real-time ISO prices, and market data.
    MIT
  • F
    license
    Not graded
    quality
    C
    maintenance
    An MCP server that exposes Moody's Pulse (Cortera) trade-credit data with grounded knowledge-base context, enabling search, report retrieval, and explanation of metrics and use cases.
    -
  • F
    license
    Not graded
    quality
    B
    maintenance
    MCP server that exposes the credit scoring model's deterministic tools (probability of default, SHAP explanations, typicality check, financial ratios) to AI agents, enabling natural language credit risk assessment.
    -
  • A
    license
    Not graded
    quality
    C
    maintenance
    Provides complete credit dossiers for individuals or companies, including registration data, risk score, and pending issues, via a hosted MCP server with a single read-only tool.
    MIT