Skip to content

scale_forecasting.mcp

Built-in, zero-extra JSON-RPC 2.0 Model Context Protocol (MCP) server over stdio (python -m scale_forecasting.mcp) exposing 7 resources and 13 tools across offline model benchmarking, RunConfig validation, multi-family DAG planning, Airflow DAG emission, prescriptive clearance & contract volume optimization, and live BigQuery registry inspection/review/repair.

See the AI Agents, Portable Skills & Built-in MCP Server guide for client configuration and tool examples.

mcp

Built-in Model Context Protocol (MCP) server for scale-forecasting over stdio.

Exposes the platform's configuration schema, canonical catalogs (37 models, 21 metrics, 7 runtimes, 4 GPU types, 13 extras, 5 views, 62 shipped configs), environment readiness probe, offline model playground, RunConfig validator and DAG planner, Airflow DAG emitter, and live BigQuery registry inspection/review/repair tools to any MCP-compatible AI coding agent (Google Antigravity agy CLI & IDE, Claude Code, Cursor, VS Code GitHub Copilot, Windsurf, OpenAI Codex CLI).

Zero extra dependencies are required: the server runs on a bare pip install scale-forecasting core installation using the Python standard library and Pydantic. Tools that query or mutate Google Cloud (inspect_registry, review_run, launch_or_repair_run, and cloud modes of plan_execution) check for [gcp] and SF_* environment variables first and return structured remediation steps if either is absent. Cloud job submission and mutating repair verbs are gated behind the explicit --allow-launch CLI flag.

CLI usage::

# Start stdio MCP server (read/plan/playground enabled; cloud launches safety-locked)
python -m scale_forecasting.mcp

# Start stdio MCP server with cloud job launch & repair unlocked
python -m scale_forecasting.mcp --allow-launch

# Print environment readiness JSON and exit
python -m scale_forecasting.mcp --probe-env

McpServer

McpServer(*, allow_launch=False, repo_root=None)

JSON-RPC 2.0 Model Context Protocol server for scale-forecasting.

Source code in src/scale_forecasting/mcp.py
def __init__(self, *, allow_launch: bool = False, repo_root: Path | None = None) -> None:
    self.allow_launch = allow_launch
    self.repo_root = repo_root or Path(__file__).resolve().parents[2]

call_tool

call_tool(name, arguments=None)

Dispatch a tool call and wrap the result in an MCP tool response.

Source code in src/scale_forecasting/mcp.py
def call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> dict[str, Any]:
    """Dispatch a tool call and wrap the result in an MCP tool response."""
    args = arguments or {}
    try:
        payload = self._dispatch_tool(name, args)
        return {
            "content": [{"type": "text", "text": _dumps(payload)}],
            "isError": False,
        }
    except (ScaleForecastError, ValueError, KeyError, FileNotFoundError) as exc:
        err_payload = {
            "error": type(exc).__name__,
            "message": str(exc),
            "environment": probe_environment(self.repo_root),
        }
        return {
            "content": [{"type": "text", "text": _dumps(err_payload)}],
            "isError": True,
        }
    except Exception as exc:  # noqa: BLE001 - MCP tool boundary must return structured JSON-RPC result
        err_payload = {
            "error": type(exc).__name__,
            "message": str(exc),
        }
        return {
            "content": [{"type": "text", "text": _dumps(err_payload)}],
            "isError": True,
        }

handle_message

handle_message(message)

Process one JSON-RPC 2.0 request or notification and return a response dict (or None).

Source code in src/scale_forecasting/mcp.py
def handle_message(self, message: dict[str, Any]) -> dict[str, Any] | None:
    """Process one JSON-RPC 2.0 request or notification and return a response dict (or None)."""
    method = message.get("method", "")
    msg_id = message.get("id")
    params = message.get("params") or {}

    # Notifications have no `id` and expect no response.
    if msg_id is None:
        return None

    try:
        if method == "initialize":
            client_version = params.get("protocolVersion") or MCP_PROTOCOL_VERSION
            result: dict[str, Any] = {
                "protocolVersion": client_version,
                "capabilities": {
                    "resources": {"subscribe": False, "listChanged": False},
                    "tools": {"listChanged": False},
                },
                "serverInfo": {
                    "name": "scale-forecasting",
                    "version": _pkg_version("scale-forecasting"),
                },
            }
        elif method == "ping":
            result = {}
        elif method == "resources/list":
            result = {"resources": self.list_resources()}
        elif method == "resources/read":
            uri = str(params.get("uri", ""))
            result = self.read_resource(uri)
        elif method == "tools/list":
            result = {"tools": self.list_tools()}
        elif method == "tools/call":
            tool_name = str(params.get("name", ""))
            tool_args = params.get("arguments") or {}
            result = self.call_tool(tool_name, tool_args)
        elif method == "prompts/list":
            result = {"prompts": []}
        else:
            return {
                "jsonrpc": "2.0",
                "id": msg_id,
                "error": {
                    "code": -32601,
                    "message": f"Method not found: {method}",
                },
            }
        return {"jsonrpc": "2.0", "id": msg_id, "result": result}
    except Exception as exc:  # noqa: BLE001 - JSON-RPC protocol handler must return structured error object
        return {
            "jsonrpc": "2.0",
            "id": msg_id,
            "error": {
                "code": -32602,
                "message": str(exc),
            },
        }

list_resources

list_resources()

Return the 7 MCP resources exposed by this server.

Source code in src/scale_forecasting/mcp.py
def list_resources(self) -> list[dict[str, str]]:
    """Return the 7 MCP resources exposed by this server."""
    return [
        {
            "uri": "forecast://environment",
            "name": "Active Environment & Readiness Report",
            "description": (
                "Installed extras (13), available vs. missing models (37), SF_* environment "
                "variables, ADC status, and readiness across all 5 execution paths."
            ),
            "mimeType": "application/json",
        },
        {
            "uri": "forecast://schema/run-config",
            "name": "RunConfig JSON Schema (Draft 2020-12)",
            "description": "Complete JSON Schema for RunConfig and all nested blocks.",
            "mimeType": "application/schema+json",
        },
        {
            "uri": "forecast://catalog/models",
            "name": "Forecasting Models Catalog (37 Models)",
            "description": (
                "All 37 registered models across 5 families with runtime, package, extra, "
                "covariate flags, explainability, and local availability."
            ),
            "mimeType": "application/json",
        },
        {
            "uri": "forecast://catalog/metrics",
            "name": "Evaluation Metrics Catalog (21 Metrics)",
            "description": (
                "All 16 point and 5 interval evaluation metrics with direction and "
                "requirements."
            ),
            "mimeType": "application/json",
        },
        {
            "uri": "forecast://catalog/runtimes",
            "name": "Compute Runtimes & GPU Catalog (7 Runtimes, 4 GPUs)",
            "description": (
                "All 7 Google Cloud runtimes, sub-modes, scaling models, and 4 GPU types."
            ),
            "mimeType": "application/json",
        },
        {
            "uri": "forecast://catalog/configs",
            "name": "Shipped Demo & Smoke Configurations (62 Configs)",
            "description": (
                "All 20 root demo configs and 42 smoke configs with run_ids and models."
            ),
            "mimeType": "application/json",
        },
        {
            "uri": "forecast://catalog/views",
            "name": "BigQuery Source Tables, Registry Tables & Views",
            "description": (
                "The 4 source tables, 5 registry tables, and 5 analytical SQL views."
            ),
            "mimeType": "application/json",
        },
    ]

list_tools

list_tools()

Return the 13 MCP tools exposed by this server.

Source code in src/scale_forecasting/mcp.py
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
def list_tools(self) -> list[dict[str, Any]]:
    """Return the 13 MCP tools exposed by this server."""
    from .benchmarks import list_benchmarks

    return [
        {
            "name": "probe_environment",
            "description": (
                "Inspect the active Python environment: installed optional extras (out of 13), "
                "locally available vs. missing-extra models (out of 37), SF_* environment "
                "variables, .env.infra presence, ADC credentials, and readiness across all 5 "
                "execution paths. Call this first to adapt recommendations to the machine."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {},
                "additionalProperties": False,
            },
        },
        {
            "name": "list_catalog",
            "description": (
                "Query the canonical catalogs of models (37), metrics (21), runtimes (7), "
                "GPUs (4), dependency extras (13), BigQuery views (5), shipped configs (62), "
                "synthetic DGP benchmarks (20), or Auto-Forecaster exposure tiers & scale "
                "regimes."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "category": {
                        "type": "string",
                        "enum": [
                            "all",
                            "models",
                            "metrics",
                            "runtimes",
                            "gpus",
                            "extras",
                            "views",
                            "configs",
                            "benchmarks",
                            "auto_tiers",
                        ],
                        "default": "all",
                    },
                    "family": {
                        "type": "string",
                        "description": (
                            "Optional model family filter "
                            "(statistical, ml, deep_learning, automl, native)."
                        ),
                    },
                    "available_only": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, filter models to those installed in the active "
                            "environment."
                        ),
                    },
                },
                "additionalProperties": False,
            },
        },
        {
            "name": "inspect_config_schema",
            "description": (
                "Inspect the JSON Schema and validation rules for RunConfig or a specific "
                "nested config block (DataConfig, FeaturesConfig, BacktestConfig, "
                "OutputConfig, CalibrationConfig, HpoConfig, EnsembleConfig, HierarchyConfig, "
                "ComputeConfig, FamilyCompute, EnsembleCompute, ProfileConfig, CapacityConfig, "
                "CapacityServicePolicy, RetryResources)."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "section": {
                        "type": "string",
                        "description": (
                            "Optional section or Pydantic class name to inspect (e.g., "
                            "'compute', 'backtest', 'CalibrationConfig', 'FamilyCompute'). "
                            "Omit for overview."
                        ),
                    }
                },
                "additionalProperties": False,
            },
        },
        {
            "name": "validate_and_dry_run",
            "description": (
                "Validate a RunConfig (dict, JSON string, or file path) offline, compute its "
                "deterministic content-addressed run_id, estimate cell/fit workload, resolve "
                "per-family compute placement and DAG nodes, and check whether any requested "
                "models require an uninstalled optional extra."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "config": {
                        "description": (
                            "RunConfig dict, JSON string, or relative/absolute file path."
                        ),
                    },
                    "n_series": {
                        "type": "integer",
                        "description": "Optional series_limit override.",
                    },
                    "ignore_unavailable_models": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "Filter models to those installed locally before planning."
                        ),
                    },
                },
                "required": ["config"],
                "additionalProperties": False,
            },
        },
        {
            "name": "run_playground",
            "description": (
                "Run a real forecasting model offline on deterministic synthetic time-series "
                "panel data (`worker.run_cell`), optionally with expanding-window backtesting, "
                "and return per-series evaluation metrics and sample forecast rows."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "model": {
                        "type": "string",
                        "default": "holtwinters",
                        "description": (
                            "Registered Python model name "
                            "(e.g., 'holtwinters', 'theta', 'naive_seasonal')."
                        ),
                    },
                    "models": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": (
                            "Optional list of model names for playground or bake-off runs."
                        ),
                    },
                    "horizon": {
                        "type": "integer",
                        "default": 14,
                    },
                    "n_series": {
                        "type": "integer",
                        "default": 3,
                    },
                    "backtest": {
                        "type": "boolean",
                        "default": True,
                    },
                    "n_folds": {
                        "type": "integer",
                        "default": 3,
                    },
                    "include_fva": {
                        "type": "boolean",
                        "default": False,
                        "description": "When true, include Forecast Value Added (FVA) summary.",
                    },
                    "scenarios": {
                        "type": "object",
                        "description": (
                            "Optional counterfactual covariate shock map "
                            "(e.g., {'promo_week': {'price_index': '*0.85'}})."
                        ),
                    },
                    "price_col": {
                        "type": "string",
                        "description": (
                            "Optional price column name for revenue impact simulation."
                        ),
                    },
                    "unit_cost": {
                        "type": ["number", "string"],
                        "description": (
                            "Optional unit cost (COGS) scalar or column name for gross-margin "
                            "counterfactual simulation."
                        ),
                    },
                    "include_inventory_impact": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute operational inventory policy shifts "
                            "(delta_reorder_point, delta_safety_stock, delta_order_qty) for "
                            "each scenario."
                        ),
                    },
                    "include_promo_elasticity": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute cross-fitted Double-ML promo & price "
                            "elasticity decomposition on the series."
                        ),
                    },
                    "include_inventory_policy": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute operational (s, S) / (R, S) inventory & "
                            "replenishment policy (ROP, safety_stock, order_up_to_level, "
                            "recommended_order_qty, Newsvendor cost) from the forward "
                            "forecast and backtest residuals."
                        ),
                    },
                    "inventory_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword overrides for compute_inventory_policy "
                            "(lead_time, lead_time_std, review_period, service_level, "
                            "fill_rate, on_hand, on_order, backorders, holding_cost, "
                            "stockout_cost, min_order_qty, order_multiple)."
                        ),
                    },
                    "include_goal_seek": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, solve top-down constrained QP goal-seek target "
                            "allocation on the forward forecast."
                        ),
                    },
                    "target_total": {
                        "description": (
                            "Optional executive top-down target total (scalar or date map) "
                            "for goal-seek allocation."
                        ),
                    },
                    "reconcile_temporal": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, apply THieF temporal hierarchy reconciliation across "
                            "aggregated calendar horizons."
                        ),
                    },
                    "temporal_reconciliation_method": {
                        "type": "string",
                        "enum": [
                            "ols",
                            "wls_struct",
                            "wls_var",
                            "mint_shrink",
                            "mint_nonneg",
                            "cross_temporal_mint",
                        ],
                        "default": "wls_struct",
                        "description": (
                            "Temporal reconciliation estimator when reconcile_temporal=True."
                        ),
                    },
                    "include_cold_start": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute cold-start & NPI analog donor shrinkage or "
                            "Bass/Gompertz diffusion forecast."
                        ),
                    },
                    "cold_start_archetype": {
                        "type": "string",
                        "enum": [
                            "auto",
                            "analog_transfer",
                            "bass_diffusion",
                            "weibull_lifecycle",
                            "arps_decline",
                        ],
                        "default": "auto",
                        "description": "Cold-start NPI launch archetype.",
                    },
                    "include_aci": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute online Adaptive Conformal Inference (ACI) "
                            "intervals and rolling empirical coverage tracking."
                        ),
                    },
                    "include_trajectories": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, simulate joint multi-horizon copula sample "
                            "trajectories."
                        ),
                    },
                    "include_tail_risk": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute portfolio Value-at-Risk (VaR) and Expected "
                            "Shortfall (CVaR) from joint copula trajectories."
                        ),
                    },
                    "copula_type": {
                        "type": "string",
                        "enum": [
                            "auto",
                            "gaussian",
                            "student_t",
                            "iman_conover",
                            "empirical",
                        ],
                        "default": "gaussian",
                        "description": "Copula family for joint trajectory sampling.",
                    },
                    "n_trajectories": {
                        "type": "integer",
                        "default": 50,
                        "description": "Number of joint copula trajectories to draw.",
                    },
                    "optimize_inventory_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for portfolio-constrained inventory "
                            "optimization (max_budget, max_volume, max_total_units, "
                            "target_portfolio_fill_rate, vendor_moq, uncertainty_source)."
                        ),
                    },
                    "optimize_scenario_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for prescriptive price & promo "
                            "calendar optimization (objective, price_bounds, "
                            "price_grid_steps, max_promo_periods, min_margin_pct)."
                        ),
                    },
                    "export_report_path": {
                        "type": "string",
                        "description": (
                            "Optional file path (.html) to export a self-contained "
                            "interactive HTML report."
                        ),
                    },
                    "include_similarity": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute pairwise time-series similarity, digital-twin "
                            "pairs, and behavioral clusters across the playground panel."
                        ),
                    },
                    "similarity_method": {
                        "type": "string",
                        "default": "hybrid",
                        "description": "Similarity kernel lens when include_similarity=true.",
                    },
                    "include_substitutes": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute inventory-aware SKU substitute / "
                            "cannibalization recommendations (recommend_substitutes_df)."
                        ),
                    },
                    "include_emerging_trends": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute breakout velocity, acceleration, and "
                            "bellwether merchandising actions (detect_emerging_trends_df)."
                        ),
                    },
                    "text_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional text columns for multi-modal similarity.",
                    },
                    "attribute_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional attribute columns for multi-modal similarity.",
                    },
                    "hierarchy_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional hierarchy columns for multi-modal similarity.",
                    },
                    "within_hierarchy_level": {
                        "type": "string",
                        "description": (
                            "Optional hierarchy column restricting substitute search."
                        ),
                    },
                    "inventory_records": {
                        "type": "array",
                        "items": {"type": "object"},
                        "description": (
                            "Optional inventory records for recommend_substitutes_df."
                        ),
                    },
                    "include_clearance": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, solve lifecycle markdown & perishable clearance MILP "
                            "(optimize_clearance_df)."
                        ),
                    },
                    "optimize_clearance_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for optimize_clearance "
                            "(initial_inventory, expiry_step, target_space_freed, "
                            "reclaim_by_step, salvage_value, target_sell_through_pct, "
                            "covariate_cols, hierarchy_cols)."
                        ),
                    },
                    "include_contract_volume": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, solve vendor contract volume & tiered rebate / "
                            "Take-or-Pay MILP (optimize_contract_volume_df)."
                        ),
                    },
                    "optimize_contract_volume_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for optimize_contract_volume "
                            "(contract_tiers, min_contract_volume, shortfall_penalty_per_unit, "
                            "risk_aversion_lambda, cvar_alpha, covariate_cols, hierarchy_cols)."
                        ),
                    },
                },
                "additionalProperties": False,
            },
        },
        {
            "name": "plan_execution",
            "description": (
                "Plan or emit execution artifacts across the platform's execution paths: "
                "'dry_run' (offline plan + CLI/gcloud launch commands + idempotency check when "
                "SF_* is configured), 'emit_airflow' (render Cloud Composer 3 / Airflow DAG "
                "Python source offline), 'feasibility' (query live BigQuery series lengths vs. "
                "backtest geometry), 'quota' (query regional CPU/GPU quota meters), or "
                "'stage_only' (upload config + code archive to GCS; requires --allow-launch)."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "config": {
                        "description": "RunConfig dict, JSON string, or file path.",
                    },
                    "mode": {
                        "type": "string",
                        "enum": [
                            "dry_run",
                            "emit_airflow",
                            "feasibility",
                            "quota",
                            "stage_only",
                        ],
                        "default": "dry_run",
                    },
                    "force": {
                        "type": "boolean",
                        "default": False,
                    },
                    "with_retry": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "For mode='emit_airflow': include the surgical retry node before "
                            "barrier ensembling."
                        ),
                    },
                    "emit_out": {
                        "type": "string",
                        "description": (
                            "Optional file path to write the rendered Airflow DAG when "
                            "mode='emit_airflow'."
                        ),
                    },
                },
                "required": ["config"],
                "additionalProperties": False,
            },
        },
        {
            "name": "inspect_registry",
            "description": (
                "Read-only inspection of the live BigQuery run registry (`[gcp]` + `SF_*`): "
                "'doctor' (table row counts, stuck RUNNING runs, orphaned GCS artifacts), "
                "'recent_runs' (latest runs from v_run_summary with time ledger and "
                "overhead_seconds), 'probe_run' (reconcile live runtime status for a run_id), "
                "or 'retry_preview' (preview surgical cell-repair decision table)."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["doctor", "recent_runs", "probe_run", "retry_preview"],
                        "default": "doctor",
                    },
                    "run_id": {
                        "type": "string",
                        "description": (
                            "Target run_id (required for 'probe_run' and 'retry_preview')."
                        ),
                    },
                    "limit": {
                        "type": "integer",
                        "default": 20,
                        "description": "Maximum rows for 'recent_runs'.",
                    },
                    "job": {
                        "type": "string",
                        "description": "Optional family filter for 'probe_run'.",
                    },
                },
                "additionalProperties": False,
            },
        },
        {
            "name": "review_run",
            "description": (
                "Read-only data-science evaluation of a completed or partial run in BigQuery "
                "(`review.review_run` + `review.calibration_report`): best model overall and "
                "per family, ensemble lift over best base model, leaderboard metrics, and "
                "point-forecast arm / prediction interval coverage calibration."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "run_id": {
                        "type": "string",
                        "description": "Content-addressed run_id (<slug>-<12hex>) to review.",
                    },
                    "include_calibration": {
                        "type": "boolean",
                        "default": True,
                    },
                    "include_leaderboard": {
                        "type": "boolean",
                        "default": True,
                    },
                    "include_fva": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, include Forecast Value Added (FVA) & Diebold-Mariano "
                            "statistical significance table."
                        ),
                    },
                    "include_horizon_decay": {
                        "type": "boolean",
                        "default": False,
                        "description": "When true, include lead-time horizon accuracy decay.",
                    },
                    "include_bias_report": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, include directional bias & Tracking Signal audit."
                        ),
                    },
                    "include_exceptions": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, include Top-N operational exception triage queue."
                        ),
                    },
                    "include_promo_elasticity": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, include Double-ML promotional & price elasticity "
                            "decomposition."
                        ),
                    },
                    "include_inventory_policy": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, include operational (s, S) / (R, S) inventory & "
                            "replenishment policy table (ROP, safety_stock, "
                            "order_up_to_level, recommended_order_qty, Newsvendor cost)."
                        ),
                    },
                    "inventory_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword overrides for compute_inventory_policy "
                            "(lead_time, lead_time_std, review_period, service_level, "
                            "fill_rate, on_hand, on_order, backorders, holding_cost, "
                            "stockout_cost, min_order_qty, order_multiple, model_type)."
                        ),
                    },
                    "include_goal_seek": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, solve top-down constrained QP goal-seek target "
                            "allocation on the run's forward predictions."
                        ),
                    },
                    "target_total": {
                        "description": (
                            "Optional executive top-down target total (scalar or date map) "
                            "for goal-seek allocation."
                        ),
                    },
                    "reconcile_temporal": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, apply THieF temporal hierarchy reconciliation across "
                            "the run's forward predictions."
                        ),
                    },
                    "temporal_reconciliation_method": {
                        "type": "string",
                        "enum": [
                            "ols",
                            "wls_struct",
                            "wls_var",
                            "mint_shrink",
                            "mint_nonneg",
                            "cross_temporal_mint",
                        ],
                        "default": "wls_struct",
                        "description": (
                            "Temporal reconciliation estimator when reconcile_temporal=True."
                        ),
                    },
                    "include_cold_start": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, include cold-start NPI donor transfer / diffusion "
                            "forecast."
                        ),
                    },
                    "include_aci": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute online Adaptive Conformal Inference (ACI) "
                            "intervals and rolling empirical coverage tracking."
                        ),
                    },
                    "include_trajectories": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, include joint copula trajectory sample paths."
                        ),
                    },
                    "include_tail_risk": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute portfolio Value-at-Risk (VaR) and Expected "
                            "Shortfall (CVaR) from joint copula trajectories."
                        ),
                    },
                    "copula_type": {
                        "type": "string",
                        "enum": [
                            "auto",
                            "gaussian",
                            "student_t",
                            "iman_conover",
                            "empirical",
                        ],
                        "default": "gaussian",
                        "description": "Copula family for joint trajectory sampling.",
                    },
                    "optimize_inventory_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for portfolio-constrained inventory "
                            "optimization (max_budget, max_volume, max_total_units, "
                            "target_portfolio_fill_rate, vendor_moq, uncertainty_source)."
                        ),
                    },
                    "optimize_scenario_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for prescriptive price & promo "
                            "calendar optimization."
                        ),
                    },
                    "export_report_path": {
                        "type": "string",
                        "description": (
                            "Optional file path (.html) to export a self-contained "
                            "interactive HTML report."
                        ),
                    },
                    "include_similarity": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute pairwise time-series similarity and behavioral "
                            "clusters across the run's series."
                        ),
                    },
                    "similarity_method": {
                        "type": "string",
                        "default": "hybrid",
                        "description": "Similarity kernel lens when include_similarity=true.",
                    },
                    "include_substitutes": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute inventory-aware SKU substitute recommendations "
                            "(recommend_substitutes_df)."
                        ),
                    },
                    "include_emerging_trends": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute breakout velocity, acceleration, and "
                            "bellwether merchandising actions (detect_emerging_trends_df)."
                        ),
                    },
                    "text_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional text columns for multi-modal similarity.",
                    },
                    "attribute_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional attribute columns for multi-modal similarity.",
                    },
                    "hierarchy_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional hierarchy columns for multi-modal similarity.",
                    },
                    "within_hierarchy_level": {
                        "type": "string",
                        "description": (
                            "Optional hierarchy column restricting substitute search."
                        ),
                    },
                    "inventory_records": {
                        "type": "array",
                        "items": {"type": "object"},
                        "description": (
                            "Optional inventory records for recommend_substitutes_df."
                        ),
                    },
                    "include_clearance": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, solve lifecycle markdown & perishable clearance MILP "
                            "(optimize_clearance_df)."
                        ),
                    },
                    "optimize_clearance_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for optimize_clearance "
                            "(initial_inventory, expiry_step, target_space_freed, "
                            "reclaim_by_step, salvage_value, target_sell_through_pct, "
                            "covariate_cols, hierarchy_cols)."
                        ),
                    },
                    "include_contract_volume": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, solve vendor contract volume & tiered rebate / "
                            "Take-or-Pay MILP (optimize_contract_volume_df)."
                        ),
                    },
                    "optimize_contract_volume_params": {
                        "type": "object",
                        "description": (
                            "Optional keyword arguments for optimize_contract_volume "
                            "(contract_tiers, min_contract_volume, shortfall_penalty_per_unit, "
                            "risk_aversion_lambda, cvar_alpha, covariate_cols, hierarchy_cols)."
                        ),
                    },
                },
                "required": ["run_id"],
                "additionalProperties": False,
            },
        },
        {
            "name": "launch_or_repair_run",
            "description": (
                "Safety-gated cloud execution and repair tool (requires the MCP server to be "
                "started with `--allow-launch`). Actions: 'run' (launch multi-family DAG), "
                "'retry' (submit surgical repair of failed/missing cells), 'settle' (repair "
                "stale job status rows from runtime probes), 'cancel' (stop in-flight cloud "
                "jobs), 'close_runs' (finalize abandoned RUNNING headers with terminal jobs)."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["run", "retry", "settle", "cancel", "close_runs"],
                    },
                    "config": {
                        "description": (
                            "RunConfig dict, JSON string, or file path (for 'run', or for "
                            "'retry'/'settle'/'cancel' when run_id is not passed)."
                        ),
                    },
                    "run_id": {
                        "type": "string",
                        "description": "Target run_id (for 'retry', 'settle', or 'cancel').",
                    },
                    "force": {
                        "type": "boolean",
                        "default": False,
                    },
                    "reason": {
                        "type": "string",
                        "default": "",
                    },
                    "n_series": {
                        "type": "integer",
                    },
                    "job": {
                        "type": "string",
                    },
                },
                "required": ["action"],
                "additionalProperties": False,
            },
        },
        {
            "name": "build_auto_config",
            "description": (
                "Synthesize a glass-box RunConfig and ConfigBlueprint via the Auto-Forecaster "
                "(`Forecaster.build_config`) across the 4 observational exposure tiers "
                "('first_light', 'wide_field', 'deep_sky', 'deep_field') and 5 n_series "
                f"scale regimes ('micro' to 'hyperscale'). Accepts any of the "
                f"{len(list_benchmarks())} synthetic DGP benchmark names "
                "('dgp_01_smooth_seasonal' .. 'dgp_20_monthly_regime_drift_damped'), "
                "'playground' sample data, a local CSV/Parquet path, or a BigQuery table name. "
                "Returns the Step 0 7-dimension data profile (`profile_table`), validated "
                "RunConfig JSON, deterministic run_id, field-by-field rationale table, "
                "4-anchor baseline ladder, and parametric wall-clock duration estimate."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "source": {
                        "type": "string",
                        "default": "playground",
                        "description": (
                            "Data source: 'playground', a synthetic benchmark name "
                            "('dgp_01_smooth_seasonal' .. "
                            "'dgp_20_monthly_regime_drift_damped'), a local CSV/Parquet file "
                            "path, or a BigQuery table name."
                        ),
                    },
                    "benchmark": {
                        "type": "string",
                        "description": (
                            "Optional alias for source when selecting a DGP benchmark."
                        ),
                    },
                    "source_table": {
                        "type": "string",
                        "description": "Optional BigQuery source table name.",
                    },
                    "n_series": {
                        "type": "integer",
                        "default": 4,
                        "description": (
                            "Series count when generating sample or DGP benchmark data."
                        ),
                    },
                    "horizon": {
                        "type": "integer",
                        "default": 14,
                        "description": "Forecast horizon H in native frequency steps.",
                    },
                    "tier": {
                        "type": "string",
                        "enum": [
                            "first_light",
                            "wide_field",
                            "deep_sky",
                            "deep_field",
                            "glimpse",
                            "starlight",
                            "survey",
                        ],
                        "default": "wide_field",
                        "description": "Observational exposure tier.",
                    },
                    "where": {
                        "type": "string",
                        "enum": ["auto", "local", "bigquery", "cloud_cpu", "cloud_all"],
                        "default": "auto",
                        "description": "Execution sandbox envelope.",
                    },
                    "goal": {
                        "type": "string",
                        "enum": ["accuracy", "probabilistic", "service_level", "fast"],
                        "default": "accuracy",
                        "description": "Optimization objective.",
                    },
                    "max_minutes": {
                        "type": "number",
                        "description": "Optional hard wall-clock budget in minutes.",
                    },
                    "max_wall_clock_minutes": {
                        "type": "number",
                        "description": "Optional hard wall-clock budget in minutes.",
                    },
                    "max_usd": {
                        "type": "number",
                        "description": "Optional cloud cost budget in USD.",
                    },
                    "only_available_models": {
                        "type": "boolean",
                        "default": True,
                        "description": (
                            "Filter synthesized models to those installed in the active "
                            "environment."
                        ),
                    },
                    "baselines": {
                        "description": (
                            "Baseline anchor policy ('auto', 'none', or array of model names)."
                        ),
                    },
                    "holidays": {
                        "description": (
                            "Optional ISO country code or array of country codes (e.g. ['US'])."
                        ),
                    },
                    "decision_metric": {
                        "type": "string",
                        "description": "Optional pinned decision metric (e.g. 'wape', 'mase').",
                    },
                    "n_folds": {
                        "type": "integer",
                        "description": "Optional pinned expanding-window backtest fold count.",
                    },
                    "allowed_families": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional list of allowed model families.",
                    },
                    "models": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional exact model shortlist to pin.",
                    },
                    "include_models": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional models to union into the tier shortlist.",
                    },
                    "exclude_models": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional models to remove from the tier shortlist.",
                    },
                    "write_config_path": {
                        "type": "string",
                        "description": (
                            "Optional file path (.json) to write the synthesized RunConfig."
                        ),
                    },
                    "emit_airflow_path": {
                        "type": "string",
                        "description": (
                            "Optional file path (.py) to write an Airflow / Composer 3 DAG."
                        ),
                    },
                    "autofocus": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "With emit_airflow_path: emit a multi-pass autofocus Airflow DAG."
                        ),
                    },
                },
                "additionalProperties": False,
            },
        },
        {
            "name": "run_auto_forecast",
            "description": (
                "Run the Glass-Box Auto-Forecaster (`auto_forecast` / `Forecaster.auto`) "
                f"on any of the {len(list_benchmarks())} synthetic DGP benchmarks "
                "('dgp_01_smooth_seasonal' .. 'dgp_20_monthly_regime_drift_damped'), "
                "'playground' sample panel, local CSV/Parquet file, or BigQuery table "
                "(with --allow-launch), with multi-branch autofocus refinement "
                "(`autofocus=True`, `autofocus_mode='dag'`). Returns the Step 0 data profile "
                "(`profile_table`), pass-by-pass `autofocus_ledger`, 4-anchor `baseline_value` "
                "ladder (plus beaten complex challengers when a univariate model wins), "
                "per-level `hierarchy_value`, head-to-head `model_comparison`, and the "
                "7-Question `practitioner_assessment`."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "source": {
                        "type": "string",
                        "default": "playground",
                        "description": (
                            "Offline data source: 'playground', a synthetic benchmark name "
                            "('dgp_01_smooth_seasonal' .. "
                            "'dgp_20_monthly_regime_drift_damped'), or a local CSV/Parquet "
                            "file path."
                        ),
                    },
                    "benchmark": {
                        "type": "string",
                        "description": (
                            "Optional DGP benchmark name ('dgp_01_smooth_seasonal' ..)."
                        ),
                    },
                    "source_table": {
                        "type": "string",
                        "description": (
                            "Optional BigQuery source table name (requires --allow-launch)."
                        ),
                    },
                    "horizon": {
                        "type": "integer",
                        "default": 14,
                        "description": "Forecast horizon H in native frequency steps.",
                    },
                    "tier": {
                        "type": "string",
                        "enum": [
                            "first_light",
                            "wide_field",
                            "deep_sky",
                            "deep_field",
                            "glimpse",
                            "starlight",
                            "survey",
                        ],
                        "default": "wide_field",
                        "description": "Initial observational exposure tier.",
                    },
                    "where": {
                        "type": "string",
                        "enum": ["auto", "local", "bigquery", "cloud_cpu", "cloud_all"],
                        "default": "local",
                        "description": "Execution sandbox envelope.",
                    },
                    "goal": {
                        "type": "string",
                        "enum": ["accuracy", "probabilistic", "service_level", "fast"],
                        "default": "accuracy",
                        "description": "Optimization objective.",
                    },
                    "autofocus": {
                        "type": "boolean",
                        "default": True,
                        "description": (
                            "When true, run bounded residual-driven autofocus refinement "
                            "(reusing passing cells from Pass 0)."
                        ),
                    },
                    "autofocus_mode": {
                        "type": "string",
                        "enum": ["dag", "linear"],
                        "default": "dag",
                        "description": "Multi-branch 'dag' or single-path 'linear' autofocus.",
                    },
                    "max_passes": {
                        "type": "integer",
                        "description": "Maximum total passes (including Pass 1).",
                    },
                    "max_autofocus_passes": {
                        "type": "integer",
                        "default": 1,
                        "description": "Maximum refinement passes after Pass 0.",
                    },
                    "baselines": {
                        "description": (
                            "Baseline anchor policy ('auto', 'none', or array of model names)."
                        ),
                    },
                    "holidays": {
                        "description": (
                            "Optional ISO country code or array of country codes (e.g. ['US'])."
                        ),
                    },
                    "decision_metric": {
                        "type": "string",
                        "description": "Optional pinned decision metric (e.g. 'wape', 'mase').",
                    },
                    "n_folds": {
                        "type": "integer",
                        "description": "Optional pinned expanding-window backtest fold count.",
                    },
                    "allowed_families": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional list of allowed model families.",
                    },
                    "models": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional exact model shortlist to pin.",
                    },
                    "include_models": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional models to union into the tier shortlist.",
                    },
                    "exclude_models": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional models to remove from the tier shortlist.",
                    },
                    "n_series": {
                        "type": "integer",
                        "default": 3,
                        "description": "Series count when source='playground' or benchmark.",
                    },
                    "export_report_path": {
                        "type": "string",
                        "description": (
                            "Optional file path (.html) to export a self-contained "
                            "interactive HTML report including the Autofocus & Blueprint tab."
                        ),
                    },
                    "evolve_target": {
                        "type": ["string", "null"],
                        "enum": [
                            "features",
                            "ensemble",
                            "model",
                            "policy",
                            "similarity_kernel",
                            None,
                        ],
                        "default": None,
                        "description": (
                            "Optional # EVOLVE-BLOCK target ('features', 'ensemble', 'model', "
                            "'policy', 'similarity_kernel') to trigger Forecaster.evolve(...) "
                            "with the 3-Gate Anti-Overfitting Ratchet."
                        ),
                    },
                    "evolve_backend": {
                        "type": "string",
                        "enum": ["alphaevolve", "vertex_gemini", "mock"],
                        "default": "alphaevolve",
                        "description": (
                            "Evolution backend when evolve_target is set: 'alphaevolve' "
                            "(default, Gemini Enterprise Discovery Engine), 'vertex_gemini' "
                            "(backup Vertex AI Gemini mutator), or 'mock' (offline test)."
                        ),
                    },
                    "evolve_max_evaluations": {
                        "type": "integer",
                        "default": 10,
                        "description": (
                            "Maximum candidate evaluations when evolve_target is set."
                        ),
                    },
                    "evolve_model_name": {
                        "type": "string",
                        "default": "gemini-3.8-flash",
                        "description": (
                            "Gemini / Vertex AI model identifier for code evolution "
                            "(default: 'gemini-3.8-flash')."
                        ),
                    },
                    "evolve_from_run_ids": {
                        "type": ["array", "null"],
                        "items": {"type": "string"},
                        "default": None,
                        "description": (
                            "Optional list of completed BigQuery run_ids to pool for "
                            "post-run super-ensembling via Forecaster.evolve(from_run_ids=...)."
                        ),
                    },
                },
                "additionalProperties": False,
            },
        },
        {
            "name": "compute_time_series_similarity",
            "description": (
                "Compute multi-lens and multi-modal time-series similarity (`hybrid`, "
                "`physics_attractor`, `spectral_phase`, `elastic_dtw`, `minirocket`, "
                "`structural_signature`, `foundation_latent`), Takens phase-space / dynamical "
                "invariants, Ward behavioral clusters, digital-twin analog matches "
                "(`full_history`, `launch_prefix`, `recent_window`), stockout-aware assortment "
                "substitutes (`substitutes`), and emerging trend breakouts (`emerging_trends`)."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "source": {
                        "type": ["string", "null"],
                        "default": "playground",
                        "description": (
                            "Data source: 'playground', a DGP benchmark name, or a local "
                            "CSV/Parquet/JSON path."
                        ),
                    },
                    "source_path_or_table": {
                        "type": ["string", "null"],
                        "default": None,
                        "description": (
                            "Optional alias for source path, benchmark name, or BigQuery table."
                        ),
                    },
                    "preset": {
                        "type": "string",
                        "default": "retail_daily",
                        "description": "Playground preset when source='playground'.",
                    },
                    "records": {
                        "type": ["array", "null"],
                        "items": {"type": "object"},
                        "default": None,
                        "description": (
                            "Optional inline panel records (each with ts_id, ds, y)."
                        ),
                    },
                    "method": {
                        "type": "string",
                        "enum": [
                            "hybrid",
                            "physics_attractor",
                            "spectral_phase",
                            "elastic_dtw",
                            "minirocket",
                            "structural_signature",
                            "foundation_latent",
                        ],
                        "default": "hybrid",
                        "description": "Similarity kernel lens.",
                    },
                    "mode": {
                        "type": "string",
                        "enum": [
                            "full_history",
                            "launch_prefix",
                            "recent_window",
                            "substitutes",
                            "emerging_trends",
                        ],
                        "default": "full_history",
                        "description": (
                            "Digital-twin matching or retail sensing mode "
                            "('full_history', 'launch_prefix', 'recent_window', "
                            "'substitutes', 'emerging_trends')."
                        ),
                    },
                    "query_ts_id": {
                        "type": ["string", "null"],
                        "default": None,
                        "description": (
                            "Optional query series ID for targeted k-NN digital-twin or "
                            "substitute search."
                        ),
                    },
                    "top_k": {
                        "type": "integer",
                        "default": 5,
                        "description": "Number of top neighbor or substitute pairs per series.",
                    },
                    "n_clusters": {
                        "type": ["integer", "string"],
                        "default": "auto",
                        "description": (
                            "Target cluster count K >= 2 or 'auto' for silhouette-optimal K*."
                        ),
                    },
                    "max_lag": {
                        "type": "integer",
                        "default": 0,
                        "description": "Maximum lead-lag cross-correlation shift tau.",
                    },
                    "window": {
                        "type": "integer",
                        "default": 14,
                        "description": (
                            "Recent observation window for emerging trend velocity and "
                            "acceleration sensing."
                        ),
                    },
                    "include_substitutes": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, compute stockout-aware assortment substitutes "
                            "(`recommend_substitutes_df`)."
                        ),
                    },
                    "include_emerging_trends": {
                        "type": "boolean",
                        "default": False,
                        "description": (
                            "When true, detect emerging trend breakouts and bellwether "
                            "lead-lag propagation (`detect_emerging_trends_df`)."
                        ),
                    },
                    "text_cols": {
                        "type": ["array", "string", "null"],
                        "default": None,
                        "description": (
                            "Optional text columns for N-gram TF-IDF + SVD semantic similarity."
                        ),
                    },
                    "attribute_cols": {
                        "type": ["array", "null"],
                        "items": {"type": "string"},
                        "default": None,
                        "description": (
                            "Optional categorical/numeric attribute columns for Gower "
                            "similarity."
                        ),
                    },
                    "hierarchy_cols": {
                        "type": ["array", "null"],
                        "items": {"type": "string"},
                        "default": None,
                        "description": (
                            "Optional ordered hierarchy columns for Wu-Palmer LCA tree "
                            "proximity."
                        ),
                    },
                    "within_hierarchy_level": {
                        "type": ["string", "array", "null"],
                        "default": None,
                        "description": (
                            "Optional hierarchy column(s) restricting matches to the same "
                            "taxonomy node."
                        ),
                    },
                    "inventory_records": {
                        "type": ["array", "null"],
                        "items": {"type": "object"},
                        "default": None,
                        "description": (
                            "Optional inline inventory records (ts_id, on_hand, safety_stock) "
                            "for assortment substitution."
                        ),
                    },
                    "require_in_stock": {
                        "type": "boolean",
                        "default": True,
                        "description": (
                            "When true, exclude out-of-stock candidates in substitute "
                            "recommendations."
                        ),
                    },
                    "n_series": {
                        "type": "integer",
                        "default": 4,
                        "description": "Series count when generating playground data.",
                    },
                    "ts_id_col": {"type": "string", "default": "ts_id"},
                    "date_col": {"type": "string", "default": "ds"},
                    "target_col": {"type": "string", "default": "y"},
                    "freq": {"type": "string", "default": "D"},
                    "project_id": {"type": ["string", "null"], "default": None},
                },
                "additionalProperties": False,
            },
        },
        {
            "name": "optimize_inventory_clearance",
            "description": (
                "Solve lifecycle markdown & perishable expiry clearance MILP "
                "(`mode='clearance'`, `clearance_optimizer.optimize_clearance`), warehouse & "
                "shelf space reclamation (`target_space_freed`, `unit_volume`, "
                "`reclaim_by_step`), multi-SKU vendor contract volume & tiered rebate / "
                "Take-or-Pay commitment optimization (`mode='contract_volume'`, "
                "`clearance_optimizer.optimize_contract_volume`), assortment rationalization "
                "& delisting demand transference (`mode='assortment'`, "
                "`clearance_optimizer.optimize_assortment`), simplex size-curve & integer "
                "pre-pack allocation (`mode='prepacks'`, "
                "`inventory_optimizer.optimize_prepacks`), or lateral store-to-store / depot "
                "rebalancing LP (`mode='rebalancing'`, "
                "`inventory_optimizer.optimize_rebalancing`)."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "mode": {
                        "type": "string",
                        "enum": [
                            "clearance",
                            "contract_volume",
                            "assortment",
                            "prepacks",
                            "rebalancing",
                        ],
                        "default": "clearance",
                        "description": (
                            "'clearance' for lifecycle markdown & space reclamation MILP; "
                            "'contract_volume' for vendor tiered rebate / Take-or-Pay MILP; "
                            "'assortment' for assortment rationalization & delisting "
                            "walk_rate; 'prepacks' for simplex size-curve & integer pre-packs; "
                            "'rebalancing' for lateral store-to-store transshipment LP."
                        ),
                    },
                    "records": {
                        "type": "array",
                        "items": {"type": "object"},
                        "description": (
                            "Optional forecast or historical panel rows "
                            "(ts_id, ds, yhat or y). "
                            "When omitted, runs offline on sample playground data."
                        ),
                    },
                    "history": {
                        "type": "array",
                        "items": {"type": "object"},
                        "description": (
                            "Optional historical panel rows for own-price elasticity and "
                            "digital-twin similarity estimation."
                        ),
                    },
                    "initial_inventory": {
                        "description": (
                            "Starting on-hand inventory (scalar float or {ts_id: units} map)."
                        ),
                    },
                    "expiry_step": {
                        "description": (
                            "Perishable shelf-life or end-of-season deadline step (int or "
                            "{ts_id: step} map)."
                        ),
                    },
                    "discount_ladder": {
                        "type": "array",
                        "items": {"type": "number"},
                        "description": (
                            "Allowed markdown discount rungs in [0, 0.95], e.g. "
                            "[0.0, 0.10, 0.20, 0.30, 0.50]."
                        ),
                    },
                    "monotone_markdown": {
                        "type": "boolean",
                        "default": True,
                        "description": (
                            "Enforce non-decreasing markdowns over time (d_{i,t} <= d_{i,t+1})."
                        ),
                    },
                    "base_price": {
                        "description": "Baseline unit selling price (float or {ts_id: price}).",
                    },
                    "unit_cost": {
                        "description": "Unit cost of goods sold (float or {ts_id: cost}).",
                    },
                    "salvage_value": {
                        "description": "Terminal salvage value per unsold unit at expiry.",
                    },
                    "spoilage_cost": {
                        "description": "Terminal disposal/spoilage cost per unsold unit.",
                    },
                    "target_sell_through_pct": {
                        "description": (
                            "Optional minimum sell-through fraction in [0, 1] by expiry_step."
                        ),
                    },
                    "unit_volume": {
                        "description": (
                            "Cubic volume / pallet / shelf-facing footprint per unit."
                        ),
                    },
                    "target_space_freed": {
                        "type": "number",
                        "description": (
                            "Minimum total warehouse/shelf space to free by reclaim_by_step."
                        ),
                    },
                    "reclaim_by_step": {
                        "type": "integer",
                        "description": (
                            "Horizon step by which target_space_freed must be reclaimed."
                        ),
                    },
                    "contract_tiers": {
                        "description": (
                            "For mode='contract_volume': array of [target_units, rebate_usd] "
                            "pairs or {target_units: rebate_usd} map."
                        ),
                    },
                    "min_contract_volume": {
                        "type": "number",
                        "description": (
                            "For mode='contract_volume': minimum Take-or-Pay portfolio volume."
                        ),
                    },
                    "shortfall_penalty_per_unit": {
                        "type": "number",
                        "default": 5.0,
                        "description": (
                            "Per-unit penalty for shortfall below min_contract_volume."
                        ),
                    },
                    "price_elasticity": {
                        "description": (
                            "Optional explicit own-price elasticity (float or {ts_id: float})."
                        ),
                    },
                    "use_digital_twin_elasticity": {
                        "type": "boolean",
                        "default": True,
                        "description": (
                            "Borrow deep-discount price elasticity from Track P digital-twin "
                            "neighbors when a SKU lacks markdown history."
                        ),
                    },
                    "cannibalization_penalty": {
                        "type": "number",
                        "default": 0.15,
                        "description": "Cross-SKU substitute cannibalization penalty weight.",
                    },
                    "oof": {
                        "type": "array",
                        "items": {"type": "object"},
                        "description": (
                            "Optional out-of-fold backtest rows (ts_id, y_true, yhat, "
                            "model_type) for per-SKU OOF champion selection and empirical "
                            "CVaR shortfall."
                        ),
                    },
                    "trajectories": {
                        "type": "array",
                        "items": {"type": "object"},
                        "description": (
                            "Optional joint copula trajectory rows (ts_id, trajectory_id, "
                            "yhat_traj) for mode='contract_volume' CVaR shortfall."
                        ),
                    },
                    "covariate_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": (
                            "Optional exogenous covariate columns (e.g. promo_flag, holiday, "
                            "temperature) to partial out via Frisch-Waugh-Lovell (FWL) when "
                            "estimating own-price elasticity."
                        ),
                    },
                    "elasticity_records": {
                        "type": "array",
                        "items": {"type": "object"},
                        "description": (
                            "Optional precomputed Double-ML promo_elasticity_df rows."
                        ),
                    },
                    "model_type": {
                        "type": "string",
                        "description": "Optional model_type filter when records spans models.",
                    },
                    "reconciliation_method": {
                        "type": "string",
                        "description": (
                            "Optional spatial/temporal reconciliation_method filter."
                        ),
                    },
                    "prefer_reconciled": {
                        "type": "boolean",
                        "default": True,
                        "description": (
                            "When true, prefer reconciled leaf forecasts over base forecasts."
                        ),
                    },
                    "hierarchy_cols": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": (
                            "Optional hierarchy columns (e.g. ['category', 'store']) for "
                            "bottom-up hierarchy_rollup aggregation."
                        ),
                    },
                    "risk_aversion_lambda": {
                        "type": "number",
                        "default": 0.25,
                        "description": (
                            "For mode='contract_volume': weight in [0, 1] blending expected "
                            "shortfall and CVaR tail shortfall."
                        ),
                    },
                    "cvar_alpha": {
                        "type": "number",
                        "default": 0.90,
                        "description": (
                            "For mode='contract_volume': tail confidence level in (0.5, 0.999) "
                            "for CVaR volume shortfall."
                        ),
                    },
                    "horizon": {
                        "type": "integer",
                        "default": 14,
                    },
                    "n_series": {
                        "type": "integer",
                        "default": 3,
                    },
                    "max_skus": {
                        "type": "integer",
                        "description": (
                            "For mode='assortment': maximum retained SKUs after delisting."
                        ),
                    },
                    "max_shelf_space": {
                        "type": "number",
                        "description": "For mode='assortment': maximum shelf space / facings.",
                    },
                    "walk_rate": {
                        "description": (
                            "For mode='assortment': optional explicit shopper walk-away rate."
                        ),
                    },
                    "prepacks": {
                        "type": "object",
                        "description": (
                            "For mode='prepacks': map of {pack_id: {size_id: units}} bundles."
                        ),
                    },
                    "transfer_cost": {
                        "description": (
                            "For mode='rebalancing': unit lateral transfer cost between nodes."
                        ),
                    },
                    "max_transfer_lead_time": {
                        "type": "number",
                        "default": 5.0,
                        "description": (
                            "For mode='rebalancing': maximum eligible transfer transit time."
                        ),
                    },
                },
                "additionalProperties": False,
            },
        },
    ]

read_resource

read_resource(uri)

Read one MCP resource by URI.

Source code in src/scale_forecasting/mcp.py
def read_resource(self, uri: str) -> dict[str, Any]:
    """Read one MCP resource by URI."""
    if uri == "forecast://environment":
        text = _dumps(probe_environment(self.repo_root))
        mime = "application/json"
    elif uri == "forecast://schema/run-config":
        text = render_run_config_json_schema()
        mime = "application/schema+json"
    elif uri == "forecast://catalog/models":
        text = _dumps(_build_models_catalog())
        mime = "application/json"
    elif uri == "forecast://catalog/metrics":
        text = _dumps(_build_metrics_catalog())
        mime = "application/json"
    elif uri == "forecast://catalog/runtimes":
        text = _dumps({"runtimes": list(RUNTIME_CATALOG), "gpus": list(GPU_CATALOG)})
        mime = "application/json"
    elif uri == "forecast://catalog/configs":
        text = _dumps(_build_configs_catalog(self.repo_root))
        mime = "application/json"
    elif uri == "forecast://catalog/views":
        text = _dumps(_build_views_catalog())
        mime = "application/json"
    else:
        raise ValueError(f"Unknown resource URI: {uri!r}")

    return {
        "contents": [
            {
                "uri": uri,
                "mimeType": mime,
                "text": text,
            }
        ]
    }

serve_stdio

serve_stdio(stdin=None, stdout=None)

Serve MCP JSON-RPC 2.0 requests over stdio (newline-delimited or Content-Length).

Source code in src/scale_forecasting/mcp.py
def serve_stdio(
    self,
    stdin: BinaryIO | None = None,
    stdout: BinaryIO | None = None,
) -> None:
    """Serve MCP JSON-RPC 2.0 requests over `stdio` (newline-delimited or Content-Length)."""
    in_stream: BinaryIO = stdin if stdin is not None else sys.stdin.buffer
    out_stream: BinaryIO = stdout if stdout is not None else sys.stdout.buffer

    while True:
        line_bytes = in_stream.readline()
        if not line_bytes:
            break
        stripped = line_bytes.strip()
        if not stripped:
            continue

        use_content_length = False
        if stripped.lower().startswith(b"content-length:"):
            use_content_length = True
            length = int(stripped.split(b":", 1)[1].strip())
            while True:
                hdr_bytes = in_stream.readline()
                if not hdr_bytes or not hdr_bytes.strip():
                    break
            body_bytes = in_stream.read(length)
        else:
            body_bytes = stripped

        try:
            request = json.loads(body_bytes.decode("utf-8"))
        except json.JSONDecodeError as exc:
            err_resp = {
                "jsonrpc": "2.0",
                "id": None,
                "error": {"code": -32700, "message": f"Parse error: {exc}"},
            }
            _write_frame(out_stream, err_resp, use_content_length=use_content_length)
            continue

        response = self.handle_message(request)
        if response is not None:
            _write_frame(out_stream, response, use_content_length=use_content_length)

compute_time_series_similarity

compute_time_series_similarity(
    source_path_or_table=None,
    *,
    preset="retail_daily",
    method="hybrid",
    query_ts_id=None,
    mode="full_history",
    n_clusters="auto",
    top_k=5,
    max_lag=0,
    window=14,
    include_substitutes=False,
    include_emerging_trends=False,
    text_cols=None,
    attribute_cols=None,
    hierarchy_cols=None,
    within_hierarchy_level=None,
    inventory_records=None,
    require_in_stock=True,
    ts_id_col="ts_id",
    date_col="ds",
    target_col="y",
    freq="D",
    project_id=None,
    records=None,
    n_series=4,
    repo_root=None,
)

Compute time-series similarity, embeddings, behavioral clusters, analog matches, stockout-aware substitutes, and emerging trend breakouts.

Source code in src/scale_forecasting/mcp.py
def compute_time_series_similarity(
    source_path_or_table: str | None = None,
    *,
    preset: str = "retail_daily",
    method: str = "hybrid",
    query_ts_id: str | None = None,
    mode: str = "full_history",
    n_clusters: int | str = "auto",
    top_k: int = 5,
    max_lag: int = 0,
    window: int = 14,
    include_substitutes: bool = False,
    include_emerging_trends: bool = False,
    text_cols: Sequence[str] | str | None = None,
    attribute_cols: Sequence[str] | None = None,
    hierarchy_cols: Sequence[str] | None = None,
    within_hierarchy_level: str | Sequence[str] | None = None,
    inventory_records: list[dict[str, Any]] | None = None,
    require_in_stock: bool = True,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
    target_col: str = "y",
    freq: str = "D",
    project_id: str | None = None,
    records: list[dict[str, Any]] | None = None,
    n_series: int = 4,
    repo_root: Path | None = None,
) -> dict[str, Any]:
    """Compute time-series similarity, embeddings, behavioral clusters, analog matches,
    stockout-aware substitutes, and emerging trend breakouts."""
    import pandas as pd

    from . import playground
    from .benchmarks import BENCHMARK_NAMES, load_benchmark
    from .similarity import (
        cluster_by_similarity_df,
        compute_similarity_matrix,
        detect_emerging_trends_df,
        find_similar_series_df,
        recommend_substitutes_df,
    )

    _ = (preset, freq, project_id)
    if isinstance(records, list) and records:
        panel_df = pd.DataFrame.from_records(records)
    elif source_path_or_table and str(source_path_or_table).strip().lower() not in (
        "playground",
        "none",
        "",
    ):
        src_str = str(source_path_or_table).strip()
        if src_str in BENCHMARK_NAMES:
            panel_df = load_benchmark(src_str).df.copy()
        else:
            cand_p = Path(src_str)
            if not cand_p.is_file() and repo_root is not None:
                cand_p = repo_root / src_str
            if cand_p.is_file():
                sfx = cand_p.suffix.lower()
                if sfx == ".parquet":
                    panel_df = pd.read_parquet(cand_p)
                elif sfx == ".json":
                    panel_df = pd.read_json(cand_p)
                else:
                    panel_df = pd.read_csv(cand_p)
            else:
                panel_df = playground.sample_data(n_series=max(2, int(n_series)))
    else:
        panel_df = playground.sample_data(n_series=max(2, int(n_series)))

    sim_res = compute_similarity_matrix(
        panel_df,
        method=method,
        top_k=max(1, int(top_k)),
        max_lag=max(0, int(max_lag)),
        text_cols=text_cols,
        attribute_cols=attribute_cols,
        hierarchy_cols=hierarchy_cols,
        within_hierarchy_level=within_hierarchy_level,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
    )
    eff_n_clusters: Any = (
        "auto"
        if isinstance(n_clusters, str) and n_clusters.strip().lower() == "auto"
        else int(n_clusters)
    )
    clusters_df = cluster_by_similarity_df(
        panel_df,
        n_clusters=eff_n_clusters,
        method=method,
        text_cols=text_cols,
        attribute_cols=attribute_cols,
        hierarchy_cols=hierarchy_cols,
        ts_id_col=ts_id_col,
        date_col=date_col,
        target_col=target_col,
        similarity_result=sim_res,
    )
    canon_mode = str(mode).strip().lower()
    inv_df = (
        pd.DataFrame.from_records(inventory_records)
        if isinstance(inventory_records, list) and inventory_records
        else None
    )
    subs_df: pd.DataFrame | None = None
    trends_df: pd.DataFrame | None = None

    if canon_mode == "substitutes" or include_substitutes:
        subs_df = recommend_substitutes_df(
            panel_df,
            inventory_df=inv_df,
            query_ts_id=query_ts_id,
            top_k=max(1, int(top_k)),
            text_cols=text_cols,
            attribute_cols=attribute_cols,
            hierarchy_cols=hierarchy_cols,
            within_hierarchy_level=within_hierarchy_level,
            require_in_stock=require_in_stock,
            method=method,
            ts_id_col=ts_id_col,
            date_col=date_col,
            target_col=target_col,
        )
    if canon_mode == "emerging_trends" or include_emerging_trends:
        trends_df = detect_emerging_trends_df(
            panel_df,
            window=max(3, int(window)),
            top_k_related=max(1, int(top_k)),
            text_cols=text_cols,
            attribute_cols=attribute_cols,
            hierarchy_cols=hierarchy_cols,
            max_lag=max(1, int(max_lag)) if int(max_lag) > 0 else 7,
            method=method,
            ts_id_col=ts_id_col,
            date_col=date_col,
            target_col=target_col,
        )

    if canon_mode == "substitutes" and subs_df is not None:
        matches_df = subs_df
    elif canon_mode == "emerging_trends" and trends_df is not None:
        matches_df = trends_df
    elif query_ts_id is not None or canon_mode != "full_history":
        matches_df = find_similar_series_df(
            panel_df,
            query_ts_id=query_ts_id,
            method=method,
            top_k=max(1, int(top_k)),
            mode=canon_mode,
            max_lag=max(0, int(max_lag)),
            text_cols=text_cols,
            attribute_cols=attribute_cols,
            hierarchy_cols=hierarchy_cols,
            within_hierarchy_level=within_hierarchy_level,
            ts_id_col=ts_id_col,
            date_col=date_col,
            target_col=target_col,
        )
    else:
        matches_df = sim_res.pairs_df

    opt_k = (
        int(clusters_df["similarity_cluster_id"].nunique())
        if not clusters_df.empty and "similarity_cluster_id" in clusters_df.columns
        else 1
    )
    sil_val = (
        float(clusters_df["silhouette_score"].mean())
        if not clusters_df.empty and "silhouette_score" in clusters_df.columns
        else 0.0
    )
    out_dict: dict[str, Any] = {
        "status": "ok",
        "method": sim_res.method,
        "mode": str(mode),
        "n_series": len(sim_res.matrix_df),
        "optimal_n_clusters": opt_k,
        "silhouette_score": round(sil_val, 6),
        "mean_similarity": round(
            float(sim_res.diagnostics.get("mean_pairwise_similarity", 1.0)), 6
        ),
        "top_pairs": sim_res.pairs_df.head(
            max(1, int(top_k) * max(1, len(sim_res.matrix_df)))
        ).to_dict(orient="records"),
        "clusters": clusters_df.to_dict(orient="records"),
        "embeddings": sim_res.embeddings_df.to_dict(orient="records"),
        "analog_matches": matches_df.to_dict(orient="records"),
        "diagnostics": dict(sim_res.diagnostics),
    }
    if subs_df is not None:
        out_dict["substitutes"] = subs_df.to_dict(orient="records")
    if trends_df is not None:
        out_dict["emerging_trends"] = trends_df.to_dict(orient="records")
    return out_dict

main

main(argv=None)

CLI entry point for python -m scale_forecasting.mcp.

Source code in src/scale_forecasting/mcp.py
def main(argv: list[str] | None = None) -> int:
    """CLI entry point for ``python -m scale_forecasting.mcp``."""
    _configure_stderr_logging()
    parser = argparse.ArgumentParser(
        prog="scale_forecasting.mcp",
        description="Run the scale-forecasting Model Context Protocol (MCP) server over stdio.",
    )
    parser.add_argument(
        "--allow-launch",
        action="store_true",
        help=(
            "Unlock cloud job submission and mutating registry repair tools "
            "(`launch_or_repair_run` and `stage_only`)."
        ),
    )
    parser.add_argument(
        "--probe-env",
        action="store_true",
        help="Print the environment readiness JSON report to stdout and exit.",
    )
    args = parser.parse_args(argv)

    if args.probe_env:
        print(_dumps(probe_environment()))
        return 0

    server = McpServer(allow_launch=args.allow_launch)
    server.serve_stdio()
    return 0