#!/usr/bin/env python3
"""Stockonomy figure check as MCP tools (stdio, newline-delimited JSON-RPC 2.0). Standard library only, Python 3.9+.

Env: STOCKONOMY_API_URL (the API base, default the public API) and STOCKONOMY_API_KEY (sent as X-Api-Key; point_in_time works without one for AAPL, MSFT, AMZN, TSLA, GOOGL and NVDA).
A verdict compares a stated figure with a filing and names it; it never says a figure is sound or correct.
Schemas mirror https://stockonomy.net/openapi.json. Logs go to stderr; stdout carries protocol frames only.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

__version__ = "1.1.0"
PROTOCOL = "2025-06-18"
MAX_CLAIMS = 20
PERIODS = ["year", "quarter", "six_months", "nine_months"]
CLAIM_ITEMS = json.loads('{"oneOf": [{"type": "object", "required": ["type", "concept", "value"], "properties": {"type": {"const": "figure"}, "concept": {"type": "string", "description": "One of the line items, or segment_revenue with member. Others are answered refused.", "examples": ["buybacks", "capex", "cost_of_revenue"]}, "value": {"type": "number", "description": "US dollars (shares for diluted_shares), at most 1e15"}, "fiscal_year": {"type": "integer", "minimum": 1990, "maximum": 2100}, "period": {"enum": ["year", "quarter", "six_months", "nine_months"]}, "period_end": {"type": "string", "format": "date"}, "rounded_to": {"type": "number", "minimum": 1, "maximum": 1000000000000.0}, "member": {"type": "string"}, "as_of": {"type": "string", "format": "date"}}, "additionalProperties": true}, {"type": "object", "required": ["type", "concept", "fiscal_year", "value"], "properties": {"type": {"enum": ["growth", "margin"]}, "concept": {"type": "string", "description": "Growth takes any listed line item. Margin takes a dollar flow other than revenue. Neither takes segment_revenue, a member or a period; both name fiscal_year."}, "fiscal_year": {"type": "integer", "minimum": 1990, "maximum": 2100}, "value": {"type": "number", "description": "A percentage"}, "period_end": {"type": "string", "format": "date"}, "prior_period_end": {"type": "string", "format": "date"}, "as_of": {"type": "string", "format": "date"}}, "additionalProperties": true}, {"type": "object", "required": ["type", "since_year"], "properties": {"type": {"enum": ["no_restatement", "no_auditor_change", "no_bankruptcy", "no_delisting_notice", "no_late_filing"]}, "since_year": {"type": "integer", "minimum": 1990, "maximum": 2100, "description": "Events are read for the last 7 calendar years only; an earlier since_year is answered refused."}, "as_of": {"type": "string", "format": "date"}}, "additionalProperties": true}]}')
# BEGIN PIT_FIELDS (generated from pit_dataset.fields() by scripts/build_mcp_fields.py; tests/test_the_mcp_server_described_fields_by_hand.py fails when it drifts)
CONCEPTS = ['accounts_payable', 'accrued_liabilities', 'accumulated_oci', 'acquisitions', 'additional_paid_in_capital', 'amortization_of_intangibles', 'asset_impairment', 'basic_shares', 'buyback_authorized', 'buyback_remaining', 'buybacks', 'capex', 'cash', 'cash_change', 'change_inventory', 'change_payables', 'change_receivables', 'commercial_paper', 'common_stock_value', 'comprehensive_income', 'cost_of_revenue', 'current_assets', 'current_liabilities', 'debt_due_after_year5', 'debt_due_year1', 'debt_due_year2', 'debt_due_year3', 'debt_due_year4', 'debt_due_year5', 'debt_issued', 'debt_repaid', 'deferred_income_tax_expense', 'deferred_revenue', 'deferred_revenue_noncurrent', 'deferred_tax_assets', 'deferred_tax_liabilities', 'depreciation_amortization', 'diluted_shares', 'dividends_declared', 'dividends_paid', 'dividends_per_share', 'eps_basic', 'eps_diluted', 'finance_lease_liability', 'financing_cash_flow', 'fx_effect_on_cash', 'general_admin_expense', 'goodwill', 'goodwill_impairment', 'gross_profit', 'income_discontinued', 'income_tax', 'income_taxes_paid', 'intangibles', 'intangibles_purchased', 'interest_and_dividend_income', 'interest_expense', 'interest_income', 'interest_paid', 'inventory', 'investing_cash_flow', 'investments_purchased', 'investments_sold', 'liabilities_and_equity', 'long_term_debt', 'long_term_investments', 'net_income', 'net_income_to_common', 'net_interest_income', 'net_investment_income', 'noncontrolling_income', 'noncontrolling_interest', 'noninterest_expense', 'noninterest_income', 'operating_cash_flow', 'operating_expenses', 'operating_income', 'operating_lease_liability', 'operating_lease_liability_current', 'operating_lease_liability_noncurrent', 'operating_lease_rou_asset', 'other_assets_noncurrent', 'other_liabilities_noncurrent', 'other_nonoperating', 'policyholder_benefits', 'ppe_net', 'preferred_stock', 'premiums_earned', 'pretax_income', 'pretax_income_domestic', 'pretax_income_foreign', 'provision_for_credit_losses', 'rd_expense', 'real_estate_net', 'receivables', 'remaining_performance_obligation', 'restructuring_charges', 'retained_earnings', 'revenue', 'selling_marketing_expense', 'sga_expense', 'share_withholding_payments', 'shareholders_equity', 'shares_issued', 'shares_outstanding', 'shares_repurchased', 'short_term_borrowings', 'short_term_debt', 'short_term_investments', 'stock_based_compensation', 'stock_issued', 'temporary_equity', 'total_assets', 'total_costs', 'total_liabilities', 'treasury_stock']
PIT_FIELDS = json.loads('[{"name": "accounts_payable", "definition": "Trade payables due within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "accrued_liabilities", "definition": "Expenses incurred and not yet paid, due within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "accumulated_oci", "definition": "Cumulative gains and losses booked straight to equity.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "acquisitions", "definition": "Cash paid for businesses acquired, net of the cash they held.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "additional_paid_in_capital", "definition": "Capital paid in by shareholders above the par value of shares.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "amortization_of_intangibles", "definition": "Amortization of acquired intangible assets for the period.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "asset_impairment", "definition": "Write-downs of long-lived assets charged in the period (goodwill impairment is its own line).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "basic_shares", "definition": "Weighted-average basic shares over the period.", "unit": "shares", "period_type": "duration", "formula": null}, {"name": "buyback_authorized", "definition": "Size of the board\'s share repurchase authorization as the equity note states it (a program\'s size, not cash spent).", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "buyback_remaining", "definition": "Amount still available under the share repurchase authorization at the date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "buybacks", "definition": "Cash paid to repurchase the filer\'s own shares.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "capex", "definition": "Cash paid for property and equipment.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "cash", "definition": "Cash and cash equivalents at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "cash_change", "definition": "Net increase or decrease in cash for the period, restricted cash included, as the cash-flow statement states it.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "change_inventory", "definition": "Cash-flow adjustment for the change in inventory (a positive number is an increase in inventory, which used cash).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "change_payables", "definition": "Cash-flow adjustment for the change in accounts payable (a positive number is an increase in payables, which provided cash).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "change_receivables", "definition": "Cash-flow adjustment for the change in receivables (a positive number is an increase in receivables, which used cash).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "commercial_paper", "definition": "Short-term unsecured notes outstanding at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "common_stock_value", "definition": "Par value of common shares issued, as carried on the balance sheet.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "comprehensive_income", "definition": "Net income plus gains and losses booked straight to equity (currency, pension, securities).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "cost_of_revenue", "definition": "Direct cost of the goods and services sold in the period.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "current_assets", "definition": "Assets expected to turn to cash within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "current_liabilities", "definition": "Obligations due within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "debt_due_after_year5", "definition": "Debt principal due more than five years after the balance-sheet date, from the debt note\'s maturity table.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "debt_due_year1", "definition": "Debt principal due in the twelve months after the balance-sheet date, from the maturity table in the debt note.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "debt_due_year2", "definition": "Debt principal due in the second year after the balance-sheet date, from the debt note\'s maturity table.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "debt_due_year3", "definition": "Debt principal due in the third year after the balance-sheet date, from the debt note\'s maturity table.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "debt_due_year4", "definition": "Debt principal due in the fourth year after the balance-sheet date, from the debt note\'s maturity table.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "debt_due_year5", "definition": "Debt principal due in the fifth year after the balance-sheet date, from the debt note\'s maturity table.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "debt_issued", "definition": "Cash received from issuing debt.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "debt_repaid", "definition": "Cash paid to repay debt.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "deferred_income_tax_expense", "definition": "The deferred part of income tax expense (benefit), a non-cash add-back in the cash-flow statement.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "deferred_revenue", "definition": "Customer payments received for service or product not yet delivered, due within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "deferred_revenue_noncurrent", "definition": "Customer payments received for service or product not yet delivered, due after a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "deferred_tax_assets", "definition": "Income tax the filer expects to recover later.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "deferred_tax_liabilities", "definition": "Income tax the filer will owe later on income already booked.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "depreciation_amortization", "definition": "Depreciation and amortization added back in the cash-flow statement; on one filing date the widest scope the filer tagged is used, and plant depreciation alone is excluded because it would understate EBITDA.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "diluted_shares", "definition": "Weighted-average diluted shares over the period.", "unit": "shares", "period_type": "duration", "formula": null}, {"name": "dividends_declared", "definition": "Total common dividends declared in the period (the amount, not the cash paid).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "dividends_paid", "definition": "Cash paid as common dividends.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "dividends_per_share", "definition": "Common dividends declared (or paid) per share.", "unit": "USD/shares", "period_type": "duration", "formula": null}, {"name": "eps_basic", "definition": "Net income per share on the basic weighted-average share count.", "unit": "USD/shares", "period_type": "duration", "formula": null}, {"name": "eps_diluted", "definition": "Net income per share on the diluted weighted-average share count.", "unit": "USD/shares", "period_type": "duration", "formula": null}, {"name": "finance_lease_liability", "definition": "Finance-lease obligation on the balance sheet.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "financing_cash_flow", "definition": "Net cash from financing activities.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "fx_effect_on_cash", "definition": "Effect of exchange-rate changes on cash for the period.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "general_admin_expense", "definition": "General and administrative expense, for filers that report it apart from selling and marketing.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "goodwill", "definition": "Goodwill from acquisitions.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "goodwill_impairment", "definition": "Write-down of goodwill charged in the period; only filers that took a charge tag it.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "gross_profit", "definition": "Revenue less cost of revenue, as the filer reports it.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "income_discontinued", "definition": "After-tax result of operations the filer has discontinued or sold.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "income_tax", "definition": "Income tax expense (benefit) for the period.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "income_taxes_paid", "definition": "Cash paid for income tax in the period (a cash-flow disclosure, not the expense).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "intangibles", "definition": "Intangible assets other than goodwill, net of amortization.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "intangibles_purchased", "definition": "Cash paid to acquire intangible assets (software, licences, patents).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "interest_and_dividend_income", "definition": "Interest and dividends earned on loans, securities and other assets, before interest expense (the gross line, not net_interest_income).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "interest_expense", "definition": "Interest cost on debt for the period.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "interest_income", "definition": "Interest and investment income earned in the period.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "interest_paid", "definition": "Cash paid for interest in the period (a cash-flow disclosure, not the expense).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "inventory", "definition": "Net inventory.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "investing_cash_flow", "definition": "Net cash from investing activities (negative when cash was spent).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "investments_purchased", "definition": "Cash paid to buy investments (marketable securities, deposits).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "investments_sold", "definition": "Cash received from selling, or from the maturity of, investments.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "liabilities_and_equity", "definition": "Total liabilities and equity as the filer tags it: the balance sheet\'s own total, which total assets must equal.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "long_term_debt", "definition": "Debt due after a year (the noncurrent portion).", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "long_term_investments", "definition": "Investments held for longer than a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "net_income", "definition": "Profit after all expenses, interest and tax, attributable to the filer.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "net_income_to_common", "definition": "Net income available to common stockholders on the diluted basis, after preferred dividends and similar claims.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "net_interest_income", "definition": "Interest earned less interest paid, on the filer\'s own net interest income line: a lender\'s spread income, and for any other filer its small interest income (expense), net.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "net_investment_income", "definition": "Income from the insurer\'s investment portfolio in the period, after investment expenses.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "noncontrolling_income", "definition": "The share of net income that belongs to minority holders of subsidiaries.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "noncontrolling_interest", "definition": "Equity in subsidiaries held by outside owners, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "noninterest_expense", "definition": "Compensation, occupancy, technology and other operating costs apart from interest, as the lender states them.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "noninterest_income", "definition": "Fee, trading, servicing and other income apart from interest, as the lender states it.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "operating_cash_flow", "definition": "Net cash from operating activities.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "operating_expenses", "definition": "Total operating expenses as the filer states them (selling, administrative, research and other operating costs).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "operating_income", "definition": "Profit from operations before interest and income tax.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "operating_lease_liability", "definition": "Total operating-lease obligation on the balance sheet.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "operating_lease_liability_current", "definition": "Operating-lease obligation due within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "operating_lease_liability_noncurrent", "definition": "Operating-lease obligation due after a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "operating_lease_rou_asset", "definition": "Right-of-use asset recognized for operating leases, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "other_assets_noncurrent", "definition": "Other long-term assets not shown on a line of their own.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "other_liabilities_noncurrent", "definition": "Other long-term liabilities not shown on a line of their own.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "other_nonoperating", "definition": "Income or expense outside operations, net.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "policyholder_benefits", "definition": "Claims, benefits and losses incurred in the period, net of reinsurance: the numerator of a loss ratio (a health plan\'s medical costs).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "ppe_net", "definition": "Property, plant and equipment, net of depreciation.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "preferred_stock", "definition": "Carrying value of preferred stock.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "premiums_earned", "definition": "Insurance premiums earned in the period, net of reinsurance (a health plan\'s premium revenue).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "pretax_income", "definition": "Profit from continuing operations before income tax.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "pretax_income_domestic", "definition": "Pretax profit from continuing operations earned in the filer\'s home country.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "pretax_income_foreign", "definition": "Pretax profit from continuing operations earned outside the filer\'s home country.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "provision_for_credit_losses", "definition": "Expense booked in the period to build the allowance for credit losses (negative for a release), on the lender\'s own provision line; a filer that files it under another tag is read from that tag only if listed here.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "rd_expense", "definition": "Research and development expense; on one filing date the widest scope the filer tagged is used.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "real_estate_net", "definition": "Real estate held for investment, net of accumulated depreciation, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "receivables", "definition": "Net trade receivables due within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "remaining_performance_obligation", "definition": "Contracted revenue not yet recognized (backlog), as the revenue note states it at the date; only filers that disclose it carry it.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "restructuring_charges", "definition": "Cost of restructuring programs charged in the period (severance, closures); only filers with a program tag it.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "retained_earnings", "definition": "Cumulative earnings kept in the business (negative for an accumulated deficit).", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "revenue", "definition": "Total revenue from sales and services for the period.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "selling_marketing_expense", "definition": "Selling and marketing expense, for filers that report it apart from general and administrative.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "sga_expense", "definition": "Selling, general and administrative expense.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "share_withholding_payments", "definition": "Cash paid to tax authorities for employees\' taxes on shares withheld at vesting (it shrinks the share count like a buyback).", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "shareholders_equity", "definition": "Total shareholders\' equity at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "shares_issued", "definition": "Common shares issued at the balance-sheet date, treasury shares included (a count of shares).", "unit": "shares", "period_type": "instant", "formula": null}, {"name": "shares_outstanding", "definition": "Common shares outstanding at the balance-sheet date.", "unit": "shares", "period_type": "instant", "formula": null}, {"name": "shares_repurchased", "definition": "Number of shares bought back in the period (a count of shares, left out of derived Q4 and TTM sums).", "unit": "shares", "period_type": "duration", "formula": null}, {"name": "short_term_borrowings", "definition": "Short-term borrowings (bank loans, notes) outstanding at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "short_term_debt", "definition": "Debt due within a year.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "short_term_investments", "definition": "Marketable securities and short-term investments held beside cash.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "stock_based_compensation", "definition": "Non-cash share-based compensation expense.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "stock_issued", "definition": "Cash received from issuing shares, including the exercise of options.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "temporary_equity", "definition": "Redeemable (mezzanine) equity that sits between liabilities and shareholders\' equity, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "total_assets", "definition": "Everything the filer owns, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "total_costs", "definition": "Total costs and expenses as the filer states them: cost of revenue plus operating expenses, for filers that show one combined line.", "unit": "USD", "period_type": "duration", "formula": null}, {"name": "total_liabilities", "definition": "Everything the filer owes, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "treasury_stock", "definition": "Cost of the filer\'s own shares it holds in treasury (shown as a deduction from equity).", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "allowance_for_credit_losses", "definition": "Allowance held against loan and financing-receivable losses at the balance-sheet date; stored as filed, so a filer that tags it as a negative contra-asset reads negative.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "claims_reserves", "definition": "Reserve for claims reported and not yet paid, plus claim adjustment expense, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "deferred_acquisition_costs", "definition": "Costs of writing policies (commissions, underwriting) carried as an asset and expensed over the policies\' lives, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "deposits", "definition": "Total deposits held at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "future_policy_benefits", "definition": "Reserve for benefits owed on life, annuity and other long-duration contracts, at the balance-sheet date.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "loans_gross", "definition": "Loans and leases held for investment before the allowance for credit losses (net of deferred fees), at the balance-sheet date: a lender\'s loan book, or any filer\'s financing receivables.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "loans_net", "definition": "Loans and leases net of the allowance for credit losses, at the balance-sheet date, as the filer\'s balance sheet tags them. A filer that also carries loans held for sale or at fair value in this line (JPM, 2020-2022) can read above loans_gross.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "property_count", "definition": "Number of real estate properties the filer reports at the date, under the standard NumberOfRealEstateProperties tag.", "unit": "count", "period_type": "instant", "formula": null}, {"name": "public_float", "definition": "Market value of shares held by non-affiliates, from the 10-K cover page; dated the last business day of the second fiscal quarter, not the fiscal year-end.", "unit": "USD", "period_type": "instant", "formula": null}, {"name": "restaurant_count", "definition": "Number of restaurants the filer reports at the date, under the standard NumberOfRestaurants tag.", "unit": "count", "period_type": "instant", "formula": null}, {"name": "store_count", "definition": "Number of stores the filer reports at the date, under the standard NumberOfStores tag.", "unit": "count", "period_type": "instant", "formula": null}, {"name": "free_cash_flow", "definition": "Cash left after capital spending; a filer\'s capex sign is ignored.", "unit": "USD", "period_type": "derived", "formula": "operating_cash_flow - abs(capex)"}, {"name": "ebitda", "definition": "Operating profit before depreciation and amortization.", "unit": "USD", "period_type": "derived", "formula": "operating_income + depreciation_amortization"}, {"name": "gross_margin", "definition": "Share of revenue left after the direct cost of sales (0.25 is 25%).", "unit": "ratio", "period_type": "derived", "formula": "gross_profit / revenue"}, {"name": "operating_margin", "definition": "Share of revenue left as operating profit.", "unit": "ratio", "period_type": "derived", "formula": "operating_income / revenue"}, {"name": "net_margin", "definition": "Share of revenue left as net income.", "unit": "ratio", "period_type": "derived", "formula": "net_income / revenue"}, {"name": "current_ratio", "definition": "Short-term assets per dollar of short-term obligations.", "unit": "ratio", "period_type": "derived", "formula": "current_assets / current_liabilities"}, {"name": "working_capital", "definition": "Short-term assets left after short-term obligations.", "unit": "USD", "period_type": "derived", "formula": "current_assets - current_liabilities"}, {"name": "effective_tax_rate", "definition": "Income tax expense per dollar of pretax profit (0.21 is 21%), struck only on positive pretax profit.", "unit": "ratio", "period_type": "derived", "formula": "income_tax / pretax_income"}, {"name": "book_value_per_share", "definition": "Shareholders\' equity per common share outstanding.", "unit": "USD/shares", "period_type": "derived", "formula": "shareholders_equity / shares_outstanding"}, {"name": "liabilities_to_equity", "definition": "Total obligations per dollar of shareholders\' equity. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "total_liabilities / shareholders_equity"}, {"name": "long_term_debt_to_equity", "definition": "Long-term borrowings per dollar of shareholders\' equity. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "long_term_debt / shareholders_equity"}, {"name": "cash_ratio", "definition": "Cash per dollar of short-term obligations. Unrestricted cash only: computed only where the filer\'s cash line excludes restricted cash. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "cash / current_liabilities"}, {"name": "interest_coverage", "definition": "Operating profit per dollar of interest expense. Returned only for a positive denominator.", "unit": "times", "period_type": "derived", "formula": "operating_income / interest_expense"}, {"name": "cash_conversion", "definition": "Operating cash flow per dollar of net income. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "operating_cash_flow / net_income"}, {"name": "payout_ratio", "definition": "Cash dividends paid per dollar of net income. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "dividends_paid / net_income"}, {"name": "rd_intensity", "definition": "Share of revenue spent on research and development. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "rd_expense / revenue"}, {"name": "sga_ratio", "definition": "Share of revenue spent on selling, general and administrative costs. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "sga_expense / revenue"}, {"name": "ocf_margin", "definition": "Operating cash flow per dollar of revenue. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "operating_cash_flow / revenue"}, {"name": "capex_intensity", "definition": "Capital spending per dollar of revenue; a filer\'s capex sign is ignored. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "abs(capex) / revenue"}, {"name": "sbc_intensity", "definition": "Share-based compensation per dollar of revenue. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "stock_based_compensation / revenue"}, {"name": "liabilities_to_assets", "definition": "Total obligations per dollar of total assets. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "total_liabilities / total_assets"}, {"name": "revenue_per_share", "definition": "Revenue per diluted weighted-average share. Returned only for a positive share count.", "unit": "USD/shares", "period_type": "derived", "formula": "revenue / diluted_shares"}, {"name": "goodwill_to_assets", "definition": "Share of total assets that is goodwill, the premium paid above the fair value of net assets acquired. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "goodwill / total_assets"}, {"name": "intangibles_to_assets", "definition": "Share of total assets held as intangibles other than goodwill. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "intangibles / total_assets"}, {"name": "capex_to_da", "definition": "Capital spending per dollar of the filer\'s total depreciation and amortization, which for an acquirer includes amortization of acquired intangibles, so for an acquirer the denominator overstates plant wear and the ratio reads lower than capex against plant alone would. A filer\'s capex sign is ignored. Returned only for a positive denominator.", "unit": "times", "period_type": "derived", "formula": "abs(capex) / depreciation_amortization"}, {"name": "buybacks_to_ocf", "definition": "Cash spent repurchasing shares per dollar of operating cash flow; a filer\'s sign is ignored. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "abs(buybacks) / operating_cash_flow"}, {"name": "dividends_to_ocf", "definition": "Cash dividends paid per dollar of operating cash flow; a filer\'s sign is ignored, and where the filer reports only total dividends paid, preferred dividends are included. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "abs(dividends_paid) / operating_cash_flow"}, {"name": "opex_ratio", "definition": "Share of revenue spent on operating expenses as the filer reports that line; some filers include cost of revenue in it, and most banks and insurers use other expense lines. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "operating_expenses / revenue"}, {"name": "benefits_to_premiums", "definition": "Claims and benefits incurred per dollar of premiums earned: a property insurer\'s loss ratio, a health plan\'s medical care ratio. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "policyholder_benefits / premiums_earned"}, {"name": "loans_to_deposits", "definition": "Loans held per dollar of deposits, a lender\'s funding gap. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "loans_gross / deposits"}, {"name": "allowance_to_loans", "definition": "Allowance held per dollar of loans before it: the reserve cover of a loan book; a filer\'s allowance sign is ignored. Returned only for a positive denominator.", "unit": "ratio", "period_type": "derived", "formula": "abs(allowance_for_credit_losses) / loans_gross"}, {"name": "return_on_equity", "definition": "Annual periods only. Net income per dollar of average (opening and closing) shareholders\' equity. A first year uses its closing balance alone, and its form says derived (year-end).", "unit": "ratio", "period_type": "derived", "formula": "net_income / average(opening, closing) shareholders_equity"}, {"name": "return_on_assets", "definition": "Annual periods only. Net income per dollar of average (opening and closing) total assets. A first year uses its closing balance alone, and its form says derived (year-end).", "unit": "ratio", "period_type": "derived", "formula": "net_income / average(opening, closing) total_assets"}, {"name": "return_on_invested_capital", "definition": "Annual periods only. After-tax operating profit per dollar of operating capital, struck on the average (opening and closing) base. A first year uses its closing balance alone, and its form says derived (year-end).", "unit": "ratio", "period_type": "derived", "formula": "nopat / average(opening, closing) invested_capital; nopat = operating_income x (1 - tax rate), the filed effective rate clamped to 10-35% (21% when pretax_income is missing or not positive); invested_capital = total_assets - cash - current_liabilities + short_term_debt (xbrl_series.invested_capital for the fallbacks)"}, {"name": "asset_turnover", "definition": "Annual periods only. Revenue per dollar of average (opening and closing) total assets. A first year uses its closing balance alone, and its form says derived (year-end).", "unit": "times", "period_type": "derived", "formula": "revenue / average(opening, closing) total_assets"}]')
# END PIT_FIELDS
PIT_CONCEPTS = [f["name"] for f in PIT_FIELDS]
DEFAULT_BASE = "https://stockonomy.up.railway.app"
DEMO_KEY = "demo"
NOTE = ("A verdict compares the stated figure with the SEC filing it names and says nothing about whether the figure or the "
        "company is sound. Verdicts: matches_filing, first_filed_differently, contradicted, not_on_file, refused, absent_in_read.")

FREE_PARAMS = ("ticker", "concept", "fiscal_year", "value", "period", "period_end", "rounded_to", "member")
TOOLS = [
    {"name": "check_claims",
     "description": "Check up to %d claims about one ticker against the SEC filings, in one call that writes a receipt on the key owner's "
                    "hash chain. Needs STOCKONOMY_API_KEY. " % MAX_CLAIMS + NOTE,
     "inputSchema": {"type": "object", "required": ["ticker", "claims"], "properties": {
         "ticker": {"type": "string", "examples": ["AAPL"]},
         "claims": {"type": "array", "minItems": 1, "maxItems": MAX_CLAIMS, "items": CLAIM_ITEMS},
         "reference": {"type": "string", "maxLength": 80, "description": "Your own tag for the receipt, such as an adviser seat or a document id."}}}},
    {"name": "check_figure_free",
     "description": "Check one stated figure against its SEC filing with no account; writes no receipt. Limited per address. Same check in a browser (one figure, no account): https://stockonomy.net/check?src=mcp_check " + NOTE,
     "inputSchema": {"type": "object", "required": ["ticker", "concept", "value"], "properties": {
         "ticker": {"type": "string", "examples": ["AAPL"]},
         "concept": {"type": "string", "enum": CONCEPTS},
         "fiscal_year": {"type": "integer"},
         "value": {"type": "number", "description": "US dollars (shares for diluted_shares)"},
         "period": {"enum": PERIODS, "description": "A quarter or year to date; name period_end with it. Without it the figure is read as a fiscal year."},
         "period_end": {"type": "string", "format": "date"},
         "rounded_to": {"type": "number", "description": "The precision the writer rounded to, for example 1e7"},
         "member": {"type": "string", "description": "With concept segment_revenue: the XBRL member name as filed"}},
         "additionalProperties": False}},
    {"name": "point_in_time",
     "description": "What the 10-K and 10-Q filings dated on or before as_of showed for one filer, per line item and period, as rows (columns named in the answer). "
                    "recast=true returns only the figures whose value changed in a later filing, each vintage with the date it was first filed. "
                    "This tool compares nothing and says nothing about which value is right. Works without STOCKONOMY_API_KEY for AAPL, MSFT, AMZN, TSLA, GOOGL and NVDA (the demo key); any other filer needs a key.",
     "inputSchema": {"type": "object", "properties": {
         "ticker": {"type": "string", "examples": ["AAPL"], "description": "One filer; or give tickers for several."},
         "tickers": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 50, "description": "Several filers in one call, rows led by cik and ticker; each ticker counts against the rate limits."},
         "fields": {"type": "array", "items": {"type": "string", "enum": PIT_CONCEPTS}, "description": "Keep only these line items."},
         "as_of": {"type": "string", "description": "A date (the whole day) or an ISO timestamp such as 2020-02-01T21:00:00Z: only filings EDGAR had accepted by then. Default today."},
         "concept": {"type": "string", "enum": PIT_CONCEPTS, "description": "A line item; pit_fields lists each with its unit, period type and definition."},
         "period_type": {"enum": ["annual", "quarter", "instant", "ttm"]},
         "history": {"type": "boolean", "description": "Every value the SEC showed, each with the filing date it first appeared, its accession and the instant EDGAR accepted it."},
         "period_end": {"type": "string", "format": "date", "description": "Only the period ending on this date; with history, every revision of it filed on or before as_of."},
         "recast": {"type": "boolean"},
         "original": {"type": "boolean", "description": "Each period's first-filed value instead of the newest."}}, "additionalProperties": False}},
    {"name": "pit_changes",
     "description": "The daily update: every row filed after `since` across all filers, with the same columns as point_in_time plus `restated` (true when an earlier filing already stated that line item for that period, so the value is a restatement; false when the period is new). "
                    "`through` is the date to send as `since` next time. Needs STOCKONOMY_API_KEY. It compares nothing and does not say why a value changed.",
     "inputSchema": {"type": "object", "required": ["since"], "properties": {
         "since": {"type": "string", "format": "date", "description": "The `through` of your last pull, or latest_filed from the coverage record."}}, "additionalProperties": False}},
    {"name": "pit_fields",
     "description": "The data dictionary for point_in_time: every line item with its unit, period type (instant, duration or derived), definition and, for derived figures, the formula. It compares nothing; no account and no request.",
     "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
    {"name": "recasts_free",
     "description": "Annual figures a filer originally reported that a later filing reports differently by more than 2%, with both accession numbers; no account. "
                    "It compares the two filed values; rows also usually carry `cause` (the kind of change, e.g. amendment, non-reliance, split or reclassification; `unexplained` or `whole_statements` when the filings give no reason) and `why` (one line on that kind). A row has neither when no ticker is given or the record behind them cannot be read. Every filer's revisions, browsable: https://stockonomy.net/recast/filings?src=mcp_recast",
     "inputSchema": {"type": "object", "required": ["ticker"], "properties": {"ticker": {"type": "string", "examples": ["AAPL"]}}, "additionalProperties": False}},
    {"name": "filing_tripwires",
     "description": "The filings in the last year that a price cannot show, for up to 30 tickers: non-reliance, auditor change, late filing, listing notice, default acceleration, bankruptcy, going-concern language and SEC enforcement, each with its accession number and filing link. "
                    "status[T].as_of dates the record and status[T].not_read names the kinds not read, so absence of a row is not absence of a filing; tickers listed under failed were not read. A row's link can be null. It compares nothing and does not say what a filing means; no account.",
     "inputSchema": {"type": "object", "required": ["tickers"], "properties": {
         "tickers": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 30, "examples": [["AAPL", "TSLA"]], "description": "Up to 30; more are listed under failed, never dropped silently."}}, "additionalProperties": False}},
]


def log(msg):
    print("stockonomy_mcp: " + msg, file=sys.stderr, flush=True)


def _fail(text):
    return {"content": [{"type": "text", "text": text}], "isError": True}


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise urllib.error.URLError("the API answered with a redirect to %s; set STOCKONOMY_API_URL to that address" % newurl)


_OPEN = urllib.request.build_opener(_NoRedirect).open


def _call(req):
    try:
        with _OPEN(req, timeout=60) as r:
            return {"content": [{"type": "text", "text": r.read().decode("utf-8", "replace")}]}
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", "replace")
        wait = e.headers.get("Retry-After")
        return _fail("HTTP %d: %s" % (e.code, body) + (" (Retry-After: %s)" % wait if wait else ""))
    except Exception as e:  # network, timeout, bad URL: a tool error, never a crash
        return _fail("request failed: %s" % e)


def call_tool(name, args):
    base = os.environ.get("STOCKONOMY_API_URL", "").strip().rstrip("/") or DEFAULT_BASE
    host = urllib.parse.urlsplit(base)
    if host.scheme != "https" and not (host.scheme == "http" and host.hostname in ("localhost", "127.0.0.1")):
        return _fail("STOCKONOMY_API_URL must be an https address (http only for localhost).")
    if not isinstance(args, dict):
        return _fail("arguments must be an object")
    if name == "check_claims":
        key = os.environ.get("STOCKONOMY_API_KEY", "").strip()
        if not key:
            return _fail("STOCKONOMY_API_KEY is not set: make a key under Settings, API keys. check_figure_free needs none.")
        body = json.dumps({"ticker": args.get("ticker"), "claims": args.get("claims"),
                           **({"reference": args["reference"]} if args.get("reference") else {})}).encode()
        return _call(urllib.request.Request(base + "/v1/resolve", data=body, method="POST",
                                            headers={"X-Api-Key": key, "Content-Type": "application/json"}))
    if name == "check_figure_free":
        q = {k: args[k] for k in FREE_PARAMS if args.get(k) is not None}
        return _call(urllib.request.Request(base + "/check/public?" + urllib.parse.urlencode(q), method="GET"))
    if name == "point_in_time":
        key = os.environ.get("STOCKONOMY_API_KEY", "").strip() or DEMO_KEY
        q = {k: ("true" if args[k] is True else args[k]) for k in ("ticker", "as_of", "concept", "period_type", "period_end", "history", "recast", "original") if args.get(k) not in (None, False)}
        q.update({k: ",".join(args[k]) for k in ("tickers", "fields") if isinstance(args.get(k), list) and args[k]})
        if not (q.get("ticker") or q.get("tickers")):
            return _fail("Give ticker or tickers.")
        return _call(urllib.request.Request(base + "/v1/pit?" + urllib.parse.urlencode(q), method="GET", headers={"X-Api-Key": key}))
    if name == "pit_changes":
        key = os.environ.get("STOCKONOMY_API_KEY", "").strip()
        if not key:
            return _fail("STOCKONOMY_API_KEY is not set: make a key under Settings, API keys. The demo key covers point_in_time only.")
        return _call(urllib.request.Request(base + "/v1/pit/changes?" + urllib.parse.urlencode({"since": args.get("since")}), method="GET", headers={"X-Api-Key": key}))
    if name == "pit_fields":
        return {"content": [{"type": "text", "text": json.dumps(PIT_FIELDS)}]}
    if name == "recasts_free":
        return _call(urllib.request.Request(base + "/public/recasts?" + urllib.parse.urlencode({"ticker": args.get("ticker") or ""}), method="GET"))
    if name == "filing_tripwires":
        t = args.get("tickers")
        if not isinstance(t, list) or not t:
            return _fail("Give tickers, a list of up to 30.")
        return _call(urllib.request.Request(base + "/tripwires", data=json.dumps({"tickers": t}).encode(), method="POST", headers={"Content-Type": "application/json"}))
    return None


def handle(msg):
    method, mid = msg.get("method"), msg.get("id")
    if mid is None:
        return None  # notifications (notifications/initialized) get no reply
    p = msg.get("params") or {}
    if method == "initialize":
        res = {"protocolVersion": p.get("protocolVersion") or PROTOCOL, "capabilities": {"tools": {}},
               "serverInfo": {"name": "stockonomy", "version": __version__}}
    elif method == "ping":
        res = {}
    elif method == "tools/list":
        res = {"tools": TOOLS}
    elif method == "tools/call":
        res = call_tool(p.get("name"), p.get("arguments") or {})
        if res is None:
            return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": "unknown tool: %s" % p.get("name")}}
    else:
        return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "method not found: %s" % method}}
    return {"jsonrpc": "2.0", "id": mid, "result": res}


def main():
    for line in sys.stdin:
        if not line.strip():
            continue
        msg = None
        try:
            msg = json.loads(line)
            out = handle(msg) if isinstance(msg, dict) else {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "invalid request"}}
        except (json.JSONDecodeError, RecursionError):
            out = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}
        except Exception as e:
            log("internal error: %s" % e)
            out = {"jsonrpc": "2.0", "id": msg.get("id") if isinstance(msg, dict) else None, "error": {"code": -32603, "message": "internal error"}}
        if out is not None:
            sys.stdout.write(json.dumps(out) + "\n")
            sys.stdout.flush()


if __name__ == "__main__":
    main()
