Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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 1967 1968 1969 1970 1971 1972 1973 1974 1975 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 116x 116x 1x 115x 1x 114x 114x 6x 108x 1x 107x 87x 76x 168x 168x 167x 167x 167x 166x 1x 125x 125x 123x 122x 122x 122x 2x 120x 4x 4x 4x 4x 21x 21x 21x 4x 3x 3x 3x 22x 22x 29x 20x 20x 20x 2x 25x 24x 25x 25x 14x 14x 22x 22x 22x 20x 19x 284x 284x 284x 284x 284x 99x 99x 99x 99x 202x 202x 202x 202x 123x 2x 121x 2x 119x 119x 79x 79x 42x 11x 4x 4x 4x 4x 4x 52x 52x 52x 2x 50x 1x 49x 2x 2x 47x 47x 4x 4x 4x 4x 1x 3x 3x 5x 5x 5x 5x 1x 4x 3x 3x 3x 4x 4x 3x 7x 10x 7x 7x 6x 7x 3x 3x 1x 1x 2x 2x 3x 3x 1x 1x 2x 4x 2x 3x 4x 4x 3x 1x 1x 2x 4x 2x 2x 2x 2x 4x 2x 2x 2x 4x 2x 2x 2x 4x 2x 2x 2x 2x 2x 3x 1x 1x 2x 2x 2x 2x 15x 13x 13x 13x 13x 13x 13x 13x 13x 13x 14x 13x 14x 14x 14x 13x 13x 14x 12x 13x 13x 13x 11x 11x 11x 10x 13x 13x 13x 9x 4x 9x 9x 6x 9x 9x 5x 1x 1x 1x 1x 1x 1x 4x 4x 2x 2x 2x 2x 4x 4x 3x 3x 3x 3x 1x 1x 1x 1x 1x 2x 4x 2x 2x 2x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 2x 2x 2x 4x 2x 2x 2x 4x 2x 2x 2x 4x 2x 2x 2x 2x 2x 2x 4x 2x 2x 2x 2x 1x 1x 1x 4x 3x 5x 22x 22x 22x 5x 1x 1x 4x 1x 1x 3x 3x 3x 17x 17x 8x 8x 8x 8x 8x 9x 9x 15x 15x 15x 5x 5x 5x 5x 5x 5x 5x 5x 10x 11x 11x 11x 11x 8x 11x 11x 6x 7x 5x 2x 3x 3x 3x 3x 4x 11x 2x 5x 2x 2x 2x 2x 3x 2x 2x 6x 2x 2x 4x 1x 1x 3x 2x 3x 3x 2x 2x 3x 5x 2x 2x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module MCP/EPMCPClient
* @description European Parliament MCP client โ domain-specific tool wrappers
* built on top of the generic {@link MCPConnection} transport.
*/
import { MCPConnection } from './mcp-connection.js';
import { ProcedureSeenCache } from './procedure-seen-cache.js';
import {
recordPendingDocument,
markDocumentResolved,
getPendingDocumentsForReprobe,
escalateExpiredDocuments,
getPendingDocumentsSummary,
} from './pending-documents.js';
import type {
MCPClientOptions,
MCPToolResult,
MCPContentItem,
GetMEPsOptions,
GetPlenarySessionsOptions,
SearchDocumentsOptions,
GetParliamentaryQuestionsOptions,
GetCommitteeInfoOptions,
MonitorLegislativePipelineOptions,
AssessMEPInfluenceOptions,
AnalyzeCoalitionDynamicsOptions,
DetectVotingAnomaliesOptions,
ComparePoliticalGroupsOptions,
VotingRecordsOptions,
VotingPatternsOptions,
GenerateReportOptions,
AnalyzeLegislativeEffectivenessOptions,
AnalyzeCommitteeActivityOptions,
TrackMEPAttendanceOptions,
AnalyzeCountryDelegationOptions,
GeneratePoliticalLandscapeOptions,
GetCurrentMEPsOptions,
GetSpeechesOptions,
GetProceduresOptions,
GetAdoptedTextsOptions,
GetEventsOptions,
GetMeetingActivitiesOptions,
GetMeetingDecisionsOptions,
GetMEPDeclarationsOptions,
GetIncomingMEPsOptions,
GetOutgoingMEPsOptions,
GetHomonymMEPsOptions,
GetPlenaryDocumentsOptions,
GetCommitteeDocumentsOptions,
GetPlenarySessionDocumentsOptions,
GetPlenarySessionDocumentItemsOptions,
GetControlledVocabulariesOptions,
GetExternalDocumentsOptions,
GetMeetingForeseenActivitiesOptions,
GetProcedureEventsOptions,
GetMeetingPlenarySessionDocumentsOptions,
GetMeetingPlenarySessionDocumentItemsOptions,
NetworkAnalysisOptions,
SentimentTrackerOptions,
EarlyWarningSystemOptions,
ComparativeIntelligenceOptions,
CorrelateIntelligenceOptions,
GetAllGeneratedStatsOptions,
GetMEPsFeedOptions,
GetEventsFeedOptions,
GetProceduresFeedOptions,
GetAdoptedTextsFeedOptions,
GetMEPDeclarationsFeedOptions,
GetDocumentsFeedOptions,
GetPlenaryDocumentsFeedOptions,
GetCommitteeDocumentsFeedOptions,
GetPlenarySessionDocumentsFeedOptions,
GetExternalDocumentsFeedOptions,
GetParliamentaryQuestionsFeedOptions,
GetCorporateBodiesFeedOptions,
GetControlledVocabulariesFeedOptions,
GetProcedureEventByIdOptions,
GetFreshProceduresOptions,
} from '../types/index.js';
/**
* Canonical list of tools exposed by the European Parliament MCP gateway
* (`european-parliament-mcp-server@1.2.15`). The news workflows, prompt
* library (`.github/prompts/07-mcp-reference.md`), and the integration test
* suite all reference this list so a regression that adds/removes a tool
* fails a single drift guard
* (`test/integration/mcp/ep-mcp.test.js`) instead of silently breaking
* prompt/validator/probe coverage.
*
* Kept in sync with every `this.safeCallTool('<name>', ...)` call below.
*/
export const EP_MCP_TOOLS: readonly string[] = [
'analyze_coalition_dynamics',
'analyze_committee_activity',
'analyze_country_delegation',
'analyze_legislative_effectiveness',
'analyze_voting_patterns',
'assess_mep_influence',
'comparative_intelligence',
'compare_political_groups',
'correlate_intelligence',
'detect_voting_anomalies',
'early_warning_system',
'generate_political_landscape',
'generate_report',
'get_adopted_texts',
'get_adopted_texts_feed',
'get_all_generated_stats',
'get_committee_documents',
'get_committee_documents_feed',
'get_committee_info',
'get_controlled_vocabularies',
'get_controlled_vocabularies_feed',
'get_corporate_bodies_feed',
'get_current_meps',
'get_documents_feed',
'get_events',
'get_events_feed',
'get_external_documents',
'get_external_documents_feed',
'get_homonym_meps',
'get_incoming_meps',
'get_meeting_activities',
'get_meeting_decisions',
'get_meeting_foreseen_activities',
'get_meeting_plenary_session_document_items',
'get_meeting_plenary_session_documents',
'get_mep_declarations',
'get_mep_declarations_feed',
'get_mep_details',
'get_meps',
'get_meps_feed',
'get_outgoing_meps',
'get_parliamentary_questions',
'get_parliamentary_questions_feed',
'get_plenary_documents',
'get_plenary_documents_feed',
'get_plenary_session_document_items',
'get_plenary_session_documents',
'get_plenary_session_documents_feed',
'get_plenary_sessions',
'get_procedure_event_by_id',
'get_procedure_events',
'get_procedures',
'get_procedures_feed',
'get_server_health',
'get_speeches',
'get_voting_records',
'monitor_legislative_pipeline',
'network_analysis',
'search_documents',
'sentiment_tracker',
'track_legislation',
'track_mep_attendance',
];
/** Fallback payload for analyze_legislative_effectiveness when validation fails or tool is unavailable */
const EFFECTIVENESS_FALLBACK = '{"effectiveness": null}';
/** Fallback payload for MEP list tools */
const MEPS_FALLBACK = '{"meps": []}';
/** Fallback payload for document list tools */
const DOCUMENTS_FALLBACK = '{"documents": []}';
/** Fallback payload for event list tools */
const EVENTS_FALLBACK = '{"events": []}';
/** Fallback payload for activity list tools */
const ACTIVITIES_FALLBACK = '{"activities": []}';
/** Fallback payload for item list tools */
const ITEMS_FALLBACK = '{"items": []}';
/** Fallback payload for intelligence analysis tools */
const INTELLIGENCE_FALLBACK = '{"analysis": null}';
/** Fallback payload for precomputed statistics */
const STATS_FALLBACK = '{"stats": null}';
/** Fallback payload for single procedure event lookup */
const PROCEDURE_EVENT_FALLBACK = '{"event": null}';
/** Fallback payload for server health status */
const SERVER_HEALTH_FALLBACK = '{"server": null, "feeds": []}';
/** Fallback payload for adopted texts tools */
const ADOPTED_TEXTS_FALLBACK = '{"texts": []}';
/**
* Substring matched (case-insensitively) in error messages to identify the
* EP Open Data Portal indexing lag (5โ15 days between identifier publication
* and content availability). Must not be changed without updating tests.
*/
const CONTENT_NOT_YET_AVAILABLE_SUBSTRING = 'document indexed but content not yet available';
/**
* Classify an error message into a diagnostic error category.
*
* Maps EP MCP Server v1.2.15 structured error codes and generic HTTP/network
* errors into one of six broad categories used for logging and retry decisions:
*
* Returned categories (priority order):
* 1. `INTERNAL_ERROR` โ EP MCP `INTERNAL_ERROR` (catch-all for DNS, TLS, unclassified upstream failures)
* 2. `SERVER_ERROR` โ EP MCP `UPSTREAM_500`/`UPSTREAM_503`/`SERVER_ERROR`, or gateway 5xx patterns
* 3. `TIMEOUT` โ EP MCP `UPSTREAM_TIMEOUT`, or generic "timeout" strings
* 4. `RATE_LIMIT` โ EP MCP `RATE_LIMITED`, HTTP 429, or "rate limit"/"too many requests" strings
* 5. `NOT_FOUND` โ EP MCP `UPSTREAM_404`, or generic "404" strings
* 6. `UNKNOWN` โ everything else
*
* @param message - Raw error message
* @returns Diagnostic error category string
*/
function classifyToolError(message: string): string {
const lowerMsg = message.toLowerCase();
// EP MCP Server v1.2.15 structured error codes (matched case-insensitively)
if (lowerMsg.includes('internal_error')) {
return 'INTERNAL_ERROR';
}
if (
lowerMsg.includes('upstream_500') ||
lowerMsg.includes('upstream_503') ||
lowerMsg.includes('server_error')
) {
return 'SERVER_ERROR';
}
Iif (lowerMsg.includes('upstream_timeout')) {
return 'TIMEOUT';
}
if (
lowerMsg.includes('gateway timeout') ||
lowerMsg.includes('gateway error 500') ||
lowerMsg.includes('gateway error 502') ||
lowerMsg.includes('gateway error 503') ||
lowerMsg.includes('gateway error 504')
) {
return 'SERVER_ERROR';
}
if (
lowerMsg.includes('429') ||
lowerMsg.includes('rate limit') ||
lowerMsg.includes('too many requests') ||
lowerMsg.includes('rate_limited')
) {
return 'RATE_LIMIT';
}
if (lowerMsg.includes('404') || lowerMsg.includes('upstream_404')) return 'NOT_FOUND';
if (lowerMsg.includes('timeout')) return 'TIMEOUT';
return 'UNKNOWN';
}
/**
* Parse the text payload of an {@link MCPToolResult} as JSON, returning
* `undefined` when the payload is missing or malformed. Small helper used by
* the unavailable-envelope detectors below.
*
* @param result - Raw MCP tool result
* @returns Parsed JSON object, or `undefined` if the payload is not a JSON object
*/
function _parseResultPayload(
result: MCPToolResult | undefined
): Record<string, unknown> | undefined {
const text = result?.content?.[0]?.text;
if (typeof text !== 'string' || text.length === 0) return undefined;
try {
const parsed: unknown = JSON.parse(text);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
return undefined;
}
return undefined;
}
/**
* Detect whether an MCP feed result represents an "unavailable" response,
* covering the two shapes historically emitted by the EP MCP server.
*
* 1. **Uniform envelope** (all feeds as of
* `european-parliament-mcp-server@1.2.15`) โ
* `{status:"unavailable", items:[], generatedAt:"..."}` established by
* Hack23/European-Parliament-MCP-Server#301 and extended to
* `get_events_feed`/`get_procedures_feed` by
* Hack23/European-Parliament-MCP-Server#380 (which closed #378).
* 2. **Legacy raw upstream 404 shape** (historically emitted pre-v1.2.13 by
* `get_events_feed` / `get_procedures_feed`, fixed upstream in PR #380) โ
* `{"@id":"https://data.europarl.europa.eu/eli/dl/...","error":"404 N..."}`.
* Retained purely as defense-in-depth for older pinned server versions or
* any future regression of #378, so such payloads do not silently poison
* downstream analysis.
*
* Returning `true` from this helper lets callers treat both shapes as
* "known-empty" rather than "success with garbage payload".
*
* @param result - Raw MCP tool result
* @returns `true` when the payload matches either unavailable envelope
*/
export function isFeedUnavailable(result: MCPToolResult | undefined): boolean {
const envelope = _parseResultPayload(result);
if (!envelope) return false;
// Shape 1 โ uniform {status:"unavailable"} envelope (#301 / #380).
if (envelope['status'] === 'unavailable') return true;
// Shape 2 โ legacy raw upstream 404 leak (historically pre-v1.2.13, #378).
const error = envelope['error'];
const idField = envelope['@id'];
if (
typeof error === 'string' &&
typeof idField === 'string' &&
idField.startsWith('https://data.europarl.europa.eu/') &&
error.includes('404')
) {
return true;
}
return false;
}
/**
* Detect the "all string fields empty" sentinel emitted by
* `get_adopted_texts({docId})` for documents that are indexed but whose
* content has not yet been populated by the EP Open Data Portal. The server
* returns a JSON-schema-valid response in which every string field is the
* empty string, which bypasses standard error handling โ see upstream issue
* Hack23/European-Parliament-MCP-Server#369.
*
* Only treats a payload as a sentinel when it has at least three string
* fields (to avoid false positives on intentionally sparse payloads) AND
* all string fields are the empty string.
*
* @param payload - Parsed JSON payload object (or `undefined`)
* @returns `true` when the payload matches the CONTENT_PENDING sentinel
*/
function _isEmptyStringSentinel(payload: Record<string, unknown> | undefined): boolean {
Iif (!payload) return false;
let totalStringFields = 0;
let emptyStringFields = 0;
for (const value of Object.values(payload)) {
Eif (typeof value === 'string') {
totalStringFields++;
if (value.length === 0) emptyStringFields++;
}
}
return totalStringFields >= 3 && totalStringFields === emptyStringFields;
}
/**
* Year threshold for detecting historical-only (recess-mode) procedures feed responses.
* Any response where ALL dated items are from this year or earlier is considered recess mode.
* See `.github/prompts/07-mcp-reference.md` ยง11 row #5.
*/
const PROCEDURES_RECESS_YEAR_THRESHOLD = 1995;
/**
* Minimum plausible year for EP procedure dates.
* The European Parliament was established in 1952; anything earlier is malformed.
*/
const MIN_VALID_PROCEDURE_YEAR = 1952;
/**
* Maximum plausible year for EP procedure dates.
* Used as an upper sanity bound to reject obviously malformed 4-digit strings.
*/
const MAX_VALID_PROCEDURE_YEAR = 2100;
/**
* Extract the first valid 4-digit year from an EP procedure item.
* Checks `dateInitiated`, then `dateLastActivity`, then the first 4 characters
* of `reference` (e.g. `"1972/0001(SYN)"`), returning `NaN` when none found.
*
* @param obj - Procedure item as a plain record
* @returns 4-digit year number, or `NaN` if no valid year field exists
*/
function extractProcedureItemYear(obj: Record<string, unknown>): number {
const dateFields = [obj['dateInitiated'], obj['dateLastActivity'], obj['reference']];
for (const field of dateFields) {
if (typeof field !== 'string' || field.length < 4) continue;
const year = Number(field.slice(0, 4));
Eif (
!Number.isNaN(year) &&
year >= MIN_VALID_PROCEDURE_YEAR &&
year <= MAX_VALID_PROCEDURE_YEAR
) {
return year;
}
}
return NaN;
}
/**
* Detect whether a procedures feed response is in "recess mode" โ i.e., all items
* have dates from {@link PROCEDURES_RECESS_YEAR_THRESHOLD} or earlier (historical archive).
*
* During parliamentary recesses the EP procedures/feed endpoint may return historical
* archive data in ID order rather than current procedures. This function detects that
* condition so callers can emit a `๐ก procedures-feed: recess mode` audit row instead
* of treating the response as usable current data.
*
* Date extraction order per item: `dateInitiated`, then `dateLastActivity`, then
* `reference` (first four characters). The first valid 4-digit year found in the
* range `[1952, 2100]` is used.
*
* Returns `false` when the payload is `undefined`, contains no items, or any item
* yields a year later than the threshold (the feed has current data).
*
* @param payload - Parsed procedures feed payload
* @returns `true` when all dated items are from {@link PROCEDURES_RECESS_YEAR_THRESHOLD} or earlier
*/
export function detectProceduresFeedRecessMode(
payload: Record<string, unknown> | undefined
): boolean {
if (!payload) return false;
// Collect items from feed shape (`items[]`) or direct-endpoint shape (`procedures[]`)
const rawItems = payload['items'] ?? payload['procedures'];
const items = Array.isArray(rawItems) ? rawItems : [];
if (items.length === 0) return false;
const years: number[] = [];
for (const item of items) {
Iif (!item || typeof item !== 'object') continue;
const year = extractProcedureItemYear(item as Record<string, unknown>);
if (!Number.isNaN(year)) {
years.push(year);
}
}
// Recess mode: items exist but every dated item is from the historical-archive window
return years.length > 0 && years.every((y) => y <= PROCEDURES_RECESS_YEAR_THRESHOLD);
}
/**
* MCP Client for European Parliament data access.
* Extends {@link MCPConnection} with EP-specific tool wrapper methods.
*/
export class EuropeanParliamentMCPClient extends MCPConnection {
/** Tracks tools that returned fallback data in the current session */
private readonly _failedTools = new Map<string, string>();
/** Tracks tools that have been called (attempted) in the current session */
private readonly _calledTools = new Set<string>();
/**
* Tracks tools that experienced a timeout but the failure was downgraded to a warning.
* Unlike `_failedTools`, entries here are NOT counted against the reliability score.
* Currently used by {@link getEventsFeed} whose documented latency is 30โ120 s+.
*/
private readonly _slowFeedWarnings = new Map<string, string>();
/**
* Path to the pending-documents sidecar file.
* Undefined means "use the module-level default (`<cwd>/data/pending-documents.json`)".
*/
private readonly _pendingDocumentsStorePath: string | undefined;
constructor(options: MCPClientOptions = {}) {
super(options);
this._pendingDocumentsStorePath = options.pendingDocumentsStorePath;
}
/**
* Record a tool failure and log a warning.
*
* @param toolName - MCP tool name that failed
* @param errorText - Raw error text from the failure
* @param fallbackText - JSON text for the fallback result
* @returns Fallback MCPToolResult
*/
private _recordToolFailure(
toolName: string,
errorText: string,
fallbackText: string
): MCPToolResult {
const errorType = classifyToolError(errorText);
this._failedTools.set(toolName, `${errorType}: ${errorText.slice(0, 200)}`);
console.warn(`โ ๏ธ ${toolName} failed [${errorType}]:`, errorText.slice(0, 200));
return { content: [{ type: 'text', text: fallbackText }] };
}
/**
* Generic error-safe wrapper around {@link callToolWithRetry}.
* Retries transient failures (timeouts, connection drops) with a bounded
* back-off delay before falling back. Non-retriable errors (session expiry,
* rate limits, programmer errors) are caught immediately without additional delay.
* Catches any error thrown by the tool (or by the args factory), logs a warning,
* and returns a fallback payload.
*
* Also inspects the tool result for the MCP protocol `isError` flag. When
* `isError === true`, the first content item's text is passed through
* {@link classifyToolError} for diagnostic categorization, and the tool is
* recorded as failed via {@link _recordToolFailure}. This handles EP MCP
* Server error responses that are returned (not thrown) as structured results.
*
* Accepts either a plain args object or a factory function `() => object`.
* Using a factory ensures that options normalization/destructuring runs inside
* the try/catch so invalid runtime inputs fall back gracefully.
*
* @param toolName - MCP tool name
* @param args - Tool arguments or a factory that builds them
* @param fallbackText - JSON text to return when the tool is unavailable
* @returns Tool result or fallback
*/
private async safeCallTool(
toolName: string,
args: object | (() => object),
fallbackText: string
): Promise<MCPToolResult> {
this._calledTools.add(toolName);
try {
const resolvedArgs = typeof args === 'function' ? args() : args;
const result = await this.callToolWithRetry(toolName, resolvedArgs);
// Inspect the result for structured error responses from the EP MCP server.
// The server may return isError: true with JSON content containing errorCode
// (e.g., INTERNAL_ERROR, UPSTREAM_500) instead of throwing an exception.
if (result.isError === true) {
return this._recordToolFailure(toolName, result.content?.[0]?.text ?? '', fallbackText);
}
// Detect the unavailable-feed envelope โ uniform `{status:"unavailable"}`
// (all feeds as of v1.2.13, #301/#380) as well as the legacy raw upstream
// 404 shape `{"@id":..., "error":"404 ..."}` that pre-v1.2.13
// get_events_feed / get_procedures_feed emitted
// (Hack23/European-Parliament-MCP-Server#378, closed by PR #380). The
// server returns HTTP 200 with a payload that bypasses isError โ record
// it as a NOT_FOUND failure so it is visible in getFailedTools() and the
// error summary instead of silently passing through as garbage data.
if (isFeedUnavailable(result)) {
return this._recordToolFailure(
toolName,
`UPSTREAM_404: ${result.content?.[0]?.text?.slice(0, 200) ?? 'feed unavailable'}`,
fallbackText
);
}
// Clear from failed tools on success
this._failedTools.delete(toolName);
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return this._recordToolFailure(toolName, message, fallbackText);
}
}
/**
* Get a summary of tools that returned fallback data in the current session.
* Useful for diagnosing feed availability and data quality issues.
*
* @returns Map of tool name to error description
*/
getFailedTools(): ReadonlyMap<string, string> {
return new Map(this._failedTools);
}
/**
* Get tools that experienced a timeout but the failure was downgraded to a warning.
* Unlike {@link getFailedTools}, entries here are **not** counted against the
* reliability score โ they represent expected-slow tools whose timeouts are
* classified as ๐ข LIMITATION (see `.github/prompts/07-mcp-reference.md` ยง11 row #8).
*
* @returns Map of tool name to `"SLOW_FEED: <message>"` warning description
*/
getSlowFeedWarnings(): ReadonlyMap<string, string> {
return new Map(this._slowFeedWarnings);
}
/**
* Get a human-readable feed health summary for diagnostics.
*
* @returns Formatted summary of feed availability
*/
getFeedHealthSummary(): string {
const feedTools = [
'get_meps_feed',
'get_events_feed',
'get_procedures_feed',
'get_adopted_texts_feed',
'get_mep_declarations_feed',
'get_documents_feed',
'get_plenary_documents_feed',
'get_committee_documents_feed',
'get_plenary_session_documents_feed',
'get_external_documents_feed',
'get_parliamentary_questions_feed',
'get_corporate_bodies_feed',
'get_controlled_vocabularies_feed',
];
const lines: string[] = ['EP MCP Feed Health:'];
let operational = 0;
let unchecked = 0;
for (const tool of feedTools) {
const error = this._failedTools.get(tool);
const slowWarning = this._slowFeedWarnings.get(tool);
if (error) {
lines.push(` โ ${tool}: ${error}`);
} else if (slowWarning) {
// Slow-feed warning: timeout was downgraded โ not counted as a failure or success
lines.push(` ๐ก ${tool}: ${slowWarning}`);
} else if (this._calledTools.has(tool)) {
lines.push(` โ
${tool}`);
operational++;
} else {
lines.push(` โช ${tool} (not checked)`);
unchecked++;
}
}
const checked = feedTools.length - unchecked;
lines.push(
` Summary: ${operational}/${checked} checked feeds operational${unchecked > 0 ? `, ${unchecked} unchecked` : ''}`
);
return lines.join('\n');
}
/**
* Get a per-error-code breakdown of tool-level rejections recorded during the
* current session. Designed for end-of-run observability so regressions like
* Hack23/European-Parliament-MCP-Server#378 (raw upstream 404 leaking
* through as "successful" feed calls) surface in agent-stdio without needing
* to hand-comb the MCP gateway logs.
*
* Each entry in `_failedTools` is stored as `"${errorCode}: ${message}"` by
* {@link _recordToolFailure}. This method splits on the first colon to
* group tool names by error code.
*
* @returns Formatted summary: one line per error code, with affected tools,
* terminated by a final counts line. Returns a single "all operational"
* line when no failures have been recorded.
*/
getToolErrorSummary(): string {
if (this._failedTools.size === 0) {
return `EP MCP Tool Errors: 0 (all ${this._calledTools.size} invoked tools operational)`;
}
const byCode = new Map<string, string[]>();
for (const [tool, entry] of this._failedTools.entries()) {
const sepIdx = entry.indexOf(':');
const code = sepIdx > 0 ? entry.slice(0, sepIdx) : 'UNKNOWN';
const existing = byCode.get(code);
if (existing) {
existing.push(tool);
} else {
byCode.set(code, [tool]);
}
}
const lines: string[] = [
`EP MCP Tool Errors: ${this._failedTools.size} of ${this._calledTools.size} invoked tools rejected`,
];
const sortedCodes = [...byCode.keys()].sort();
for (const code of sortedCodes) {
const tools = byCode.get(code) ?? [];
lines.push(` ${code} (${tools.length}): ${tools.sort().join(', ')}`);
}
return lines.join('\n');
}
/**
* Get Members of European Parliament
*
* @param options - Filter options
* @returns List of MEPs
*/
async getMEPs(options: GetMEPsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_meps', options, MEPS_FALLBACK);
}
/**
* Get plenary sessions
*
* @param options - Filter options including dateFrom, dateTo, eventId, year, location
* @returns Plenary sessions data
*
* @remarks
* This repository is currently documented/configured against
* `european-parliament-mcp-server@1.2.15`.
*
* **Upstream date-filter contract (v1.2.14+, active on the pinned v1.2.15 server):** the upstream server
* applies a server-side post-filter on `dateFrom`/`dateTo` before serialisation, because the
* EP Open Data Portal `/meetings` endpoint silently ignores its `date-from`/`date-to` query
* parameters (Defect #5). Under this contract:
* - `data[]` contains only sessions within the requested window.
* - `total` reflects the **filtered** count, not the raw upstream count.
* - Per-window session counts are reproducible because the EP-side regression is masked by
* the upstream post-filter.
*
* No local post-filter is applied here. The repository is pinned to v1.2.15, so the
* date-filter guarantees above apply; consumers running against an older server image
* (pre-v1.2.14) must not assume them.
*/
async getPlenarySessions(options: GetPlenarySessionsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_plenary_sessions', options, '{"data": [], "total": 0}');
}
/**
* Search legislative documents
*
* @param options - Search options using v1.2.13 parameters: keyword, documentType, docId, etc.
* @returns Search results
*/
async searchDocuments(options: SearchDocumentsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('search_documents', options, DOCUMENTS_FALLBACK);
}
/**
* Get parliamentary questions
*
* @param options - Filter options including docId, type, author, topic, status, dateFrom, dateTo
* @returns Parliamentary questions data
*/
async getParliamentaryQuestions(
options: GetParliamentaryQuestionsOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('get_parliamentary_questions', options, '{"questions": []}');
}
/**
* Get committee information
*
* @param options - Filter options: id, abbreviation, showCurrent
* @returns Committee info data
*/
async getCommitteeInfo(options: GetCommitteeInfoOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_committee_info', options, '{"committees": []}');
}
/**
* Monitor legislative pipeline
*
* @param options - Filter options
* @returns Legislative pipeline data
*/
async monitorLegislativePipeline(
options: MonitorLegislativePipelineOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('monitor_legislative_pipeline', options, '{"procedures": []}');
}
/**
* Analyze legislative effectiveness of an MEP or committee
*
* @param options - Options including subjectType and subjectId
* @returns Legislative effectiveness data
*/
async analyzeLegislativeEffectiveness(
options: AnalyzeLegislativeEffectivenessOptions
): Promise<MCPToolResult> {
const { subjectType, subjectId } = options;
if (subjectId.trim().length === 0) {
console.warn(
'analyze_legislative_effectiveness called without valid subjectId (non-empty string required)'
);
return { content: [{ type: 'text', text: EFFECTIVENESS_FALLBACK }] };
}
const trimmedSubjectId = subjectId.trim();
return this.safeCallTool(
'analyze_legislative_effectiveness',
{ ...options, subjectType, subjectId: trimmedSubjectId },
EFFECTIVENESS_FALLBACK
);
}
/**
* Assess MEP influence using 5-dimension scoring model
*
* @param options - Options including required mepId and optional date range
* @returns MEP influence score and breakdown
*/
async assessMEPInfluence(options: AssessMEPInfluenceOptions): Promise<MCPToolResult> {
const trimmedMepId = options && typeof options.mepId === 'string' ? options.mepId.trim() : '';
if (trimmedMepId.length === 0) {
console.warn('assess_mep_influence called without valid mepId (non-empty string required)');
return { content: [{ type: 'text', text: '{"influence": {}}' }] };
}
return this.safeCallTool(
'assess_mep_influence',
{ ...options, mepId: trimmedMepId },
'{"influence": {}}'
);
}
/**
* Analyze coalition dynamics and cohesion
*
* @param options - Options including optional groupIds and date range
* @returns Coalition cohesion and stress analysis
*/
async analyzeCoalitionDynamics(
options: AnalyzeCoalitionDynamicsOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('analyze_coalition_dynamics', options, '{"coalitions": []}');
}
/**
* Detect voting anomalies and party defections
*
* @param options - Options including optional MEP id, groupId, and date range
* @returns Anomaly detection results
*/
async detectVotingAnomalies(options: DetectVotingAnomaliesOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('detect_voting_anomalies', options, '{"anomalies": []}');
}
/**
* Compare political groups across dimensions
*
* @param options - Options including required groupIds and optional dimensions and date range
* @returns Cross-group comparative analysis
*/
async comparePoliticalGroups(options: ComparePoliticalGroupsOptions): Promise<MCPToolResult> {
const groupIds = (Array.isArray(options.groupIds) ? options.groupIds : [])
.map((g) => (typeof g === 'string' ? g.trim() : ''))
.filter((g) => g.length > 0);
if (groupIds.length === 0) {
console.warn(
'compare_political_groups called without valid groupIds (non-empty string array required)'
);
return { content: [{ type: 'text', text: '{"comparison": {}}' }] };
}
return this.safeCallTool(
'compare_political_groups',
{ ...options, groupIds },
'{"comparison": {}}'
);
}
/**
* Get detailed information about a specific MEP
*
* @param id - MEP identifier (must be non-empty)
* @returns Detailed MEP information including biography, contact, and activities
*/
async getMEPDetails(id: string): Promise<MCPToolResult> {
if (typeof id !== 'string' || id.trim().length === 0) {
console.warn('get_mep_details called without valid id (non-empty string required)');
return { content: [{ type: 'text', text: '{"mep": null}' }] };
}
return this.safeCallTool('get_mep_details', { id: id.trim() }, '{"mep": null}');
}
/**
* Retrieve voting records with optional filters
*
* @param options - Filter options (sessionId, mepId, topic, dateFrom, dateTo, limit, offset)
* @returns Voting records data
*/
async getVotingRecords(options: VotingRecordsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_voting_records', options, '{"votes": []}');
}
/**
* Analyze voting behavior patterns for an MEP
*
* @param options - Analysis options (mepId required non-empty, dateFrom, compareWithGroup)
* @returns Voting pattern analysis
*/
async analyzeVotingPatterns(options: VotingPatternsOptions): Promise<MCPToolResult> {
if (typeof options.mepId !== 'string' || options.mepId.trim().length === 0) {
console.warn(
'analyze_voting_patterns called without valid mepId (non-empty string required)'
);
return { content: [{ type: 'text', text: '{"patterns": null}' }] };
}
return this.safeCallTool(
'analyze_voting_patterns',
{ ...options, mepId: options.mepId.trim() },
'{"patterns": null}'
);
}
/**
* Track a legislative procedure by its identifier
*
* @param procedureId - Legislative procedure identifier (must be non-empty)
* @returns Procedure status and timeline
*/
async trackLegislation(procedureId: string): Promise<MCPToolResult> {
if (typeof procedureId !== 'string' || procedureId.trim().length === 0) {
console.warn(
'track_legislation called without valid procedureId (non-empty string required)'
);
return { content: [{ type: 'text', text: '{"procedure": null}' }] };
}
return this.safeCallTool(
'track_legislation',
{ procedureId: procedureId.trim() },
'{"procedure": null}'
);
}
/**
* Generate an analytical report
*
* @param options - Report options (reportType required non-empty, subjectId, dateFrom)
* @returns Generated report data
*/
async generateReport(options: GenerateReportOptions): Promise<MCPToolResult> {
if (typeof options.reportType !== 'string' || options.reportType.trim().length === 0) {
console.warn('generate_report called without valid reportType (non-empty string required)');
return { content: [{ type: 'text', text: '{"report": null}' }] };
}
return this.safeCallTool(
'generate_report',
{ ...options, reportType: options.reportType.trim() },
'{"report": null}'
);
}
/**
* Analyze committee activity, workload, and engagement
*
* @param options - Options including optional committeeId and date range
* @returns Committee activity analysis data
*/
async analyzeCommitteeActivity(
options: AnalyzeCommitteeActivityOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('analyze_committee_activity', options, '{"activity": null}');
}
/**
* Track MEP attendance patterns and trends
*
* @param options - Options including optional mepId and date range
* @returns MEP attendance data
*/
async trackMEPAttendance(options: TrackMEPAttendanceOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('track_mep_attendance', options, '{"attendance": null}');
}
/**
* Analyze country delegation voting behavior and composition
*
* @param options - Options including required country code and optional date range
* @returns Country delegation analysis data
*/
async analyzeCountryDelegation(options: AnalyzeCountryDelegationOptions): Promise<MCPToolResult> {
if (typeof options.country !== 'string' || options.country.trim().length === 0) {
console.warn(
'analyze_country_delegation called without valid country (non-empty string required)'
);
return { content: [{ type: 'text', text: '{"delegation": null}' }] };
}
return this.safeCallTool(
'analyze_country_delegation',
{ ...options, country: options.country.trim() },
'{"delegation": null}'
);
}
/**
* Generate a parliament-wide political landscape overview
*
* @param options - Options including optional date range and detail level
* @returns Political landscape overview data
*/
async generatePoliticalLandscape(
options: GeneratePoliticalLandscapeOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('generate_political_landscape', options, '{"landscape": null}');
}
/**
* Get currently active Members of European Parliament
*
* @param options - Pagination options
* @returns Active MEPs data
*/
async getCurrentMEPs(options: GetCurrentMEPsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_current_meps', options, MEPS_FALLBACK);
}
/**
* Get plenary speeches and debate contributions
*
* @param options - Filter options including optional speechId, dateFrom/dateTo (v1.2.13: year removed)
* @returns Speeches data
*/
async getSpeeches(options: GetSpeechesOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_speeches', options, '{"speeches": []}');
}
/**
* Get legislative procedures
*
* @param options - Filter options including optional processId (v1.2.13: year removed)
* @returns Procedures data
*/
async getProcedures(options: GetProceduresOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_procedures', options, '{"procedures": []}');
}
/**
* Get fresh legislative procedures using client-side date filtering as a
* workaround for the broken EP `/procedures/feed` timeframe filter.
*
* **Background**: the EP Open Data Portal `/procedures/feed` endpoint stopped
* honouring the `timeframe` parameter on or around 2026-04-19 and began
* returning historical-tail pagination (oldest records first, all metadata
* empty). This regression is tracked as Defect #3 in
* `analysis/daily/2026-04-24/propositions/intelligence/mcp-reliability-audit.md`
* and has been reported to open-data-helpdesk@europarl.europa.eu.
*
* **Strategy**:
* 1. Call `get_procedures(limit=100, offset=0)` โ the stable non-feed endpoint.
* 2. Sort results client-side by `dateLastActivity` DESC, falling back to
* `dateInitiated` when `dateLastActivity` is empty.
* 3. Keep procedures where the effective date >= today minus `windowDays`
* (default 30 days). Apply optional `topN` cap.
* 4. Persist `(procedureId, dateLastActivity)` pairs to the seen-cache so
* subsequent runs can detect new/updated IDs without re-paginating.
*
* @param options - Discovery options (limit, windowDays, topN, seenCacheStorePath)
* @returns Sorted, filtered procedure list in `{"procedures": [...]}` envelope
*/
async getFreshProcedures(options: GetFreshProceduresOptions = {}): Promise<MCPToolResult> {
const { limit = 100, windowDays = 30, topN, seenCacheStorePath } = options;
// Step 1 โ fetch from stable (non-feed) endpoint
const raw = await this.getProcedures({ limit });
const payload = _parseResultPayload(raw);
const payloadProcedures = payload?.['procedures'];
const allProcedures: unknown[] = Array.isArray(payloadProcedures) ? payloadProcedures : [];
// Step 2 โ sort client-side by dateLastActivity DESC (fall back to dateInitiated)
const todayMinus = new Date();
todayMinus.setUTCDate(todayMinus.getUTCDate() - windowDays);
const cutoff = todayMinus.toISOString().slice(0, 10); // YYYY-MM-DD
const normalised = allProcedures.filter(
(p): p is Record<string, unknown> => p !== null && typeof p === 'object' && !Array.isArray(p)
);
const withSortKey = normalised.map((p) => {
const dla = typeof p['dateLastActivity'] === 'string' ? p['dateLastActivity'] : '';
const di = typeof p['dateInitiated'] === 'string' ? p['dateInitiated'] : '';
return { item: p, effectiveDate: dla.length > 0 ? dla : di };
});
withSortKey.sort((a, b) => b.effectiveDate.localeCompare(a.effectiveDate));
// Step 3 โ filter to window
const inWindow = withSortKey
.filter(({ effectiveDate }) => effectiveDate >= cutoff)
.map(({ item }) => item);
const result = topN !== undefined ? inWindow.slice(0, topN) : inWindow;
// Step 4 โ persist to seen-cache (new IDs and changed dateLastActivity)
const cache = new ProcedureSeenCache(seenCacheStorePath);
for (const p of result) {
const id = typeof p['id'] === 'string' ? p['id'] : '';
const dateLastActivity =
typeof p['dateLastActivity'] === 'string' ? p['dateLastActivity'] : '';
if (id.length > 0) {
cache.upsert(id, dateLastActivity);
}
}
cache.save();
return {
content: [{ type: 'text', text: JSON.stringify({ procedures: result }) }],
};
}
/**
* Get adopted texts (legislative resolutions, positions, non-legislative resolutions)
*
* When called with `options.docId` this method delegates to
* {@link _fetchAdoptedTextByDocId} which handles two CONTENT_PENDING conditions
* with the correct classification from the first log entry:
*
* 1. **UPSTREAM_404 indexing lag** (primary, v1.2.13+): The EP MCP Server
* throws `UPSTREAM_404: document indexed but content not yet available`
* when the EP Open Data Portal has indexed a document identifier but the
* content body has not yet been populated (typically 5โ15-day lag).
* The docId is recorded in the pending-documents sidecar with exponential
* back-off scheduling so subsequent runs can re-probe without over-reporting
* the lag as a reliability defect.
*
* 2. **Empty-string sentinel** (secondary, pre-v1.2.13 defence-in-depth):
* Every string field is `""` โ upstream issue
* Hack23/European-Parliament-MCP-Server#369.
*
* In both cases the method returns the empty `{"texts": []}` fallback so
* downstream consumers do not render blank title/reference/date fields.
*
* Year-range list queries (no `docId`) use the standard {@link safeCallTool}
* wrapper and are not affected by content-availability detection.
*
* @param options - Filter options including optional docId or year
* @returns Adopted texts data
*/
async getAdoptedTexts(options: GetAdoptedTextsOptions = {}): Promise<MCPToolResult> {
// docId lookups use a contextual wrapper so the initial log category is
// CONTENT_PENDING, not NOT_FOUND followed by a post-hoc reclassification.
if (typeof options.docId === 'string' && options.docId.trim().length > 0) {
return this._fetchAdoptedTextByDocId(options.docId.trim());
}
// Year-range list queries use the standard wrapper.
return this.safeCallTool('get_adopted_texts', options, ADOPTED_TEXTS_FALLBACK);
}
/**
* Contextual fetcher for single-document `get_adopted_texts` lookups.
*
* Wraps {@link callToolWithRetry} directly so content-availability lag is
* classified as `CONTENT_PENDING` from the first log entry โ not reclassified
* from `NOT_FOUND` after the fact. Two conditions are handled:
*
* 1. **UPSTREAM_404 indexing lag** (thrown exception or `isError:true` body):
* message contains {@link CONTENT_NOT_YET_AVAILABLE_SUBSTRING}.
*
* 2. **Empty-string sentinel** (`isError:false`, pre-v1.2.13 defence-in-depth):
* every string field is `""`.
*
* @param docId - Trimmed document identifier
* @returns Adopted texts data or `ADOPTED_TEXTS_FALLBACK`
*/
private async _fetchAdoptedTextByDocId(docId: string): Promise<MCPToolResult> {
this._calledTools.add('get_adopted_texts');
const persistPending = (label: string): Promise<void> =>
recordPendingDocument(docId, this._pendingDocumentsStorePath)
.then(() => undefined)
.catch((err) => {
console.warn(
`โ ๏ธ pending-documents: failed to record pending doc (${label}):`,
(err as Error).message
);
});
try {
const result = await this.callToolWithRetry('get_adopted_texts', { docId });
// โโ isError structured response โโ
if (result.isError === true) {
const text = result.content?.[0]?.text ?? '';
Eif (text.toLowerCase().includes(CONTENT_NOT_YET_AVAILABLE_SUBSTRING)) {
this._failedTools.set(
'get_adopted_texts',
`CONTENT_PENDING: ${docId} EP indexing lag (tracked in pending-documents sidecar)`
);
console.warn(`โ ๏ธ get_adopted_texts [CONTENT_PENDING]: ${docId} EP indexing lag`);
await persistPending('isError');
return { content: [{ type: 'text', text: ADOPTED_TEXTS_FALLBACK }] };
}
return this._recordToolFailure('get_adopted_texts', text, ADOPTED_TEXTS_FALLBACK);
}
// โโ Empty-string sentinel (pre-v1.2.13 defence-in-depth) โโ
const payload = _parseResultPayload(result);
if (_isEmptyStringSentinel(payload)) {
await persistPending('sentinel');
return this._recordToolFailure(
'get_adopted_texts',
`CONTENT_PENDING: docId=${docId} returned empty-string sentinel (upstream #369)`,
ADOPTED_TEXTS_FALLBACK
);
}
this._failedTools.delete('get_adopted_texts');
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
// โโ Primary: UPSTREAM_404 indexing lag (thrown exception) โโ
if (message.toLowerCase().includes(CONTENT_NOT_YET_AVAILABLE_SUBSTRING)) {
this._failedTools.set(
'get_adopted_texts',
`CONTENT_PENDING: ${docId} EP indexing lag (tracked in pending-documents sidecar)`
);
console.warn(`โ ๏ธ get_adopted_texts [CONTENT_PENDING]: ${docId} EP indexing lag`);
await persistPending('upstream_404');
return { content: [{ type: 'text', text: ADOPTED_TEXTS_FALLBACK }] };
}
return this._recordToolFailure('get_adopted_texts', message, ADOPTED_TEXTS_FALLBACK);
}
}
/**
* Return the docIds of pending adopted texts that are due for a re-probe
* according to their exponential back-off schedule.
*
* Call this at the start of each Stage B deep-fetch run to obtain the list
* of identifiers to re-probe. For each returned docId, call
* {@link getAdoptedTexts} with `{ docId }`. If the fetch succeeds (real
* content returned), call {@link resolveAdoptedText} to mark it resolved.
*
* @returns Array of docIds due for reprobe (may be empty)
*/
async getDueAdoptedTextsForReprobe(): Promise<string[]> {
return getPendingDocumentsForReprobe(this._pendingDocumentsStorePath);
}
/**
* Mark a previously-pending adopted text as resolved (content is now
* available and has been successfully retrieved).
*
* @param docId - Adopted-text identifier (e.g., "TA-10-2026-0104")
*/
async resolveAdoptedText(docId: string): Promise<void> {
await markDocumentResolved(docId, this._pendingDocumentsStorePath);
}
/**
* Escalate PENDING adopted texts that have exceeded the 14-day maximum
* tracking age. Escalated documents are excluded from future reprobes and
* should be handled by the wildcards-blackswans family.
*
* @returns Array of docIds that were escalated
*/
async escalateStalePendingDocuments(): Promise<string[]> {
return escalateExpiredDocuments(this._pendingDocumentsStorePath);
}
/**
* Return a human-readable summary of the pending-documents sidecar for
* Stage B observability logging.
*
* @returns Formatted summary string
*/
async getPendingDocumentsSummary(): Promise<string> {
return getPendingDocumentsSummary(this._pendingDocumentsStorePath);
}
/**
* Get European Parliament events (hearings, conferences, seminars)
*
* @param options - Filter options including optional eventId, pagination only (v1.2.13: year/dateFrom/dateTo removed โ EP API /events has no date filtering)
* @returns Events data
*/
async getEvents(options: GetEventsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_events', options, EVENTS_FALLBACK);
}
/**
* Get activities linked to a specific plenary sitting
*
* @param options - Options including required sittingId
* @returns Meeting activities data
*/
async getMeetingActivities(options: GetMeetingActivitiesOptions): Promise<MCPToolResult> {
if (typeof options.sittingId !== 'string' || options.sittingId.trim().length === 0) {
console.warn(
'get_meeting_activities called without valid sittingId (non-empty string required)'
);
return { content: [{ type: 'text', text: ACTIVITIES_FALLBACK }] };
}
return this.safeCallTool(
'get_meeting_activities',
{ ...options, sittingId: options.sittingId.trim() },
ACTIVITIES_FALLBACK
);
}
/**
* Get decisions made in a specific plenary sitting
*
* @param options - Options including required sittingId
* @returns Meeting decisions data
*/
async getMeetingDecisions(options: GetMeetingDecisionsOptions): Promise<MCPToolResult> {
if (typeof options.sittingId !== 'string' || options.sittingId.trim().length === 0) {
console.warn(
'get_meeting_decisions called without valid sittingId (non-empty string required)'
);
return { content: [{ type: 'text', text: '{"decisions": []}' }] };
}
return this.safeCallTool(
'get_meeting_decisions',
{ ...options, sittingId: options.sittingId.trim() },
'{"decisions": []}'
);
}
/**
* Get MEP declarations of financial interests
*
* @param options - Filter options including optional docId or year
* @returns MEP declarations data
*/
async getMEPDeclarations(options: GetMEPDeclarationsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_mep_declarations', options, '{"declarations": []}');
}
/**
* Get incoming Members of European Parliament
*
* @param options - Pagination options
* @returns Incoming MEPs data
*/
async getIncomingMEPs(options: GetIncomingMEPsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_incoming_meps', options, MEPS_FALLBACK);
}
/**
* Get outgoing Members of European Parliament
*
* @param options - Pagination options
* @returns Outgoing MEPs data
*/
async getOutgoingMEPs(options: GetOutgoingMEPsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_outgoing_meps', options, MEPS_FALLBACK);
}
/**
* Get homonym MEPs (MEPs with identical names)
*
* @param options - Pagination options
* @returns Homonym MEPs data
*/
async getHomonymMEPs(options: GetHomonymMEPsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_homonym_meps', options, MEPS_FALLBACK);
}
/**
* Get plenary documents
*
* @param options - Filter options including optional docId or year
* @returns Plenary documents data
*/
async getPlenaryDocuments(options: GetPlenaryDocumentsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_plenary_documents', options, DOCUMENTS_FALLBACK);
}
/**
* Get committee documents
*
* @param options - Filter options including optional docId (v1.2.13: year removed)
* @returns Committee documents data
*/
async getCommitteeDocuments(options: GetCommitteeDocumentsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_committee_documents', options, DOCUMENTS_FALLBACK);
}
/**
* Get plenary session documents (agendas, minutes, voting lists)
*
* @param options - Filter options including optional docId
* @returns Plenary session documents data
*/
async getPlenarySessionDocuments(
options: GetPlenarySessionDocumentsOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('get_plenary_session_documents', options, DOCUMENTS_FALLBACK);
}
/**
* Get plenary session document items
*
* @param options - Pagination options
* @returns Plenary session document items data
*/
async getPlenarySessionDocumentItems(
options: GetPlenarySessionDocumentItemsOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('get_plenary_session_document_items', options, ITEMS_FALLBACK);
}
/**
* Get controlled vocabularies (standardized classification terms)
*
* @param options - Filter options including optional vocId
* @returns Controlled vocabularies data
*/
async getControlledVocabularies(
options: GetControlledVocabulariesOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool('get_controlled_vocabularies', options, '{"vocabularies": []}');
}
/**
* Get external documents (non-EP documents such as Council positions)
*
* @param options - Filter options including optional docId (v1.2.13: year removed)
* @returns External documents data
*/
async getExternalDocuments(options: GetExternalDocumentsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_external_documents', options, DOCUMENTS_FALLBACK);
}
/**
* Get foreseen (planned) activities for a specific plenary sitting
*
* @param options - Options including required sittingId
* @returns Foreseen activities data
*/
async getMeetingForeseenActivities(
options: GetMeetingForeseenActivitiesOptions
): Promise<MCPToolResult> {
if (typeof options.sittingId !== 'string' || options.sittingId.trim().length === 0) {
console.warn(
'get_meeting_foreseen_activities called without valid sittingId (non-empty string required)'
);
return { content: [{ type: 'text', text: ACTIVITIES_FALLBACK }] };
}
return this.safeCallTool(
'get_meeting_foreseen_activities',
{ ...options, sittingId: options.sittingId.trim() },
ACTIVITIES_FALLBACK
);
}
/**
* Get events linked to a specific legislative procedure
*
* @param options - Options including required processId
* @returns Procedure events data
*/
async getProcedureEvents(options: GetProcedureEventsOptions): Promise<MCPToolResult> {
if (typeof options.processId !== 'string' || options.processId.trim().length === 0) {
console.warn(
'get_procedure_events called without valid processId (non-empty string required)'
);
return { content: [{ type: 'text', text: EVENTS_FALLBACK }] };
}
return this.safeCallTool(
'get_procedure_events',
{ ...options, processId: options.processId.trim() },
EVENTS_FALLBACK
);
}
/**
* Get plenary session documents linked to a specific meeting
*
* @param options - Options including required sittingId
* @returns Meeting plenary session documents data
*/
async getMeetingPlenarySessionDocuments(
options: GetMeetingPlenarySessionDocumentsOptions
): Promise<MCPToolResult> {
if (typeof options.sittingId !== 'string' || options.sittingId.trim().length === 0) {
console.warn(
'get_meeting_plenary_session_documents called without valid sittingId (non-empty string required)'
);
return { content: [{ type: 'text', text: DOCUMENTS_FALLBACK }] };
}
return this.safeCallTool(
'get_meeting_plenary_session_documents',
{ ...options, sittingId: options.sittingId.trim() },
DOCUMENTS_FALLBACK
);
}
/**
* Get plenary session document items linked to a specific meeting
*
* @param options - Options including required sittingId
* @returns Meeting plenary session document items data
*/
async getMeetingPlenarySessionDocumentItems(
options: GetMeetingPlenarySessionDocumentItemsOptions
): Promise<MCPToolResult> {
if (typeof options.sittingId !== 'string' || options.sittingId.trim().length === 0) {
console.warn(
'get_meeting_plenary_session_document_items called without valid sittingId (non-empty string required)'
);
return { content: [{ type: 'text', text: ITEMS_FALLBACK }] };
}
return this.safeCallTool(
'get_meeting_plenary_session_document_items',
{ ...options, sittingId: options.sittingId.trim() },
ITEMS_FALLBACK
);
}
/**
* MEP relationship network mapping using committee co-membership
*
* @param options - Options including optional mepId, analysisType, and depth
* @returns Network analysis with centrality scores and clusters
*/
async networkAnalysis(options: NetworkAnalysisOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('network_analysis', options, INTELLIGENCE_FALLBACK);
}
/**
* Track political group institutional positioning and sentiment
*
* @param options - Options including optional groupId and timeframe
* @returns Sentiment tracking data
*/
async sentimentTracker(options: SentimentTrackerOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('sentiment_tracker', options, INTELLIGENCE_FALLBACK);
}
/**
* Detect emerging political shifts and coalition fracture signals
*
* @param options - Options including optional sensitivity and focusArea
* @returns Early warning alerts and trend indicators
*/
async earlyWarningSystem(options: EarlyWarningSystemOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('early_warning_system', options, INTELLIGENCE_FALLBACK);
}
/**
* Cross-reference MEP activities for comparative multi-dimensional profiling
*
* @param options - Options including required mepIds array and optional dimensions
* @returns Comparative intelligence profiles
*/
async comparativeIntelligence(options: ComparativeIntelligenceOptions): Promise<MCPToolResult> {
if (!Array.isArray(options.mepIds) || options.mepIds.length < 2) {
console.warn(
'comparative_intelligence called without valid mepIds (array of at least 2 required)'
);
return { content: [{ type: 'text', text: INTELLIGENCE_FALLBACK }] };
}
return this.safeCallTool('comparative_intelligence', options, INTELLIGENCE_FALLBACK);
}
/**
* Cross-tool OSINT intelligence correlation engine
*
* @param options - Options including required mepIds, optional groups, sensitivityLevel, includeNetworkAnalysis
* @returns Correlated intelligence alerts and insights
*/
async correlateIntelligence(options: CorrelateIntelligenceOptions): Promise<MCPToolResult> {
if (!Array.isArray(options.mepIds) || options.mepIds.length === 0) {
console.warn(
'correlate_intelligence called without valid mepIds (non-empty string array required)'
);
return { content: [{ type: 'text', text: INTELLIGENCE_FALLBACK }] };
}
return this.safeCallTool('correlate_intelligence', options, INTELLIGENCE_FALLBACK);
}
/**
* Retrieve precomputed European Parliament activity statistics (EP6โEP10, 2004โ2025).
* Includes yearly stats, category rankings, political landscape history, and
* average-based predictions for 2026โ2030. Static data refreshed weekly โ no live API calls.
*
* @param options - Filter options including optional year range, category, and flags
* @returns Precomputed EP statistics data
*/
async getAllGeneratedStats(options: GetAllGeneratedStatsOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_all_generated_stats', options, STATS_FALLBACK);
}
// โโโ EP API v2 Feed Endpoint Methods โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/** Fallback payload for feed tools */
private static readonly FEED_FALLBACK = '{"feed": []}';
/**
* Get MEPs feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns MEPs feed data
*/
async getMEPsFeed(options: GetMEPsFeedOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool('get_meps_feed', options, EuropeanParliamentMCPClient.FEED_FALLBACK);
}
/**
* Get events feed (most recent updates via EP API v2)
*
* Implements special timeout-downgrade handling: when the call throws a timeout
* error, the failure is recorded in {@link _slowFeedWarnings} (not
* {@link _failedTools}) so it does **not** reduce the session reliability score.
* The events feed is documented as significantly slower than other feeds
* (30โ120 s+); timeouts during heavy EP API load are expected behaviour, classified
* as ๐ข LIMITATION in `.github/prompts/07-mcp-reference.md` ยง11 row #8.
*
* A fallback result with `slowFeedWarning: true` is returned so Stage A consumers
* can detect the condition and fall back to `get_plenary_sessions({ year })`.
*
* Non-timeout errors (404, 5xx, rate-limit, etc.) are still recorded as failures.
*
* @param options - Pagination options
* @returns Events feed data, or `{ "feed": [], "slowFeedWarning": true }` on timeout
*/
async getEventsFeed(options: GetEventsFeedOptions = {}): Promise<MCPToolResult> {
this._calledTools.add('get_events_feed');
try {
const result = await this.callToolWithRetry('get_events_feed', options);
// Inspect for structured error responses (isError flag) from the EP MCP server
if (result.isError === true) {
this._slowFeedWarnings.delete('get_events_feed');
return this._recordToolFailure(
'get_events_feed',
result.content?.[0]?.text ?? '',
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
// Detect unavailable-feed envelope (uniform {status:"unavailable"} or legacy 404)
if (isFeedUnavailable(result)) {
this._slowFeedWarnings.delete('get_events_feed');
return this._recordToolFailure(
'get_events_feed',
`UPSTREAM_404: ${result.content?.[0]?.text?.slice(0, 200) ?? 'feed unavailable'}`,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
// Success โ clear any prior failure or slow-feed warning so health summary stays accurate
this._failedTools.delete('get_events_feed');
this._slowFeedWarnings.delete('get_events_feed');
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
// Downgrade genuine TIMEOUT errors to slow-feed warnings โ not counted against success rate.
// The events feed latency is 30โ120 s+; timeouts are expected during EP API load
// and classified as ๐ข LIMITATION per 07-mcp-reference.md ยง11 row #8.
// Use classifyToolError so 504 "Gateway Timeout" stays in SERVER_ERROR, not slow-feed.
if (classifyToolError(message) === 'TIMEOUT') {
const warningMsg = `SLOW_FEED: ${message.slice(0, 200)}`;
// Clear any prior failure entry so health summary doesn't show โ alongside ๐ก
this._failedTools.delete('get_events_feed');
this._slowFeedWarnings.set('get_events_feed', warningMsg);
console.warn('๐ก get_events_feed slow-feed warning [SLOW_FEED]:', message.slice(0, 200));
return { content: [{ type: 'text', text: '{"feed":[],"slowFeedWarning":true}' }] };
}
// Non-timeout failure: clear any stale slow-feed warning so health summary reflects reality
this._slowFeedWarnings.delete('get_events_feed');
return this._recordToolFailure(
'get_events_feed',
message,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
}
/**
* Get procedures feed (most recent updates via EP API v2)
*
* Post-processes the response to detect "recess mode" โ when the EP procedures
* feed returns historical archive data (all items dated โค 1995) instead of
* current procedures. This happens during parliamentary recesses when the EP API
* serves its historical archive in ID order.
*
* When recess mode is detected:
* - `recessMode: true` is added to the payload
* - A `RECESS_MODE: โฆ` entry is appended to `dataQualityWarnings[]`
* - A `๐ก procedures-feed: recess mode` console warning is emitted
*
* The tool is **not** recorded as failed โ this is documented EP API behaviour
* classified as ๐ข LIMITATION in `.github/prompts/07-mcp-reference.md` ยง11 row #5.
* Downstream Stage A consumers should fall back to
* `get_adopted_texts({ year: $YEAR })` or `track_legislation({ procedureId })`.
*
* @param options - Pagination options
* @returns Procedures feed data, possibly with `recessMode: true` added to the payload
*/
async getProceduresFeed(options: GetProceduresFeedOptions = {}): Promise<MCPToolResult> {
const result = await this.safeCallTool(
'get_procedures_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
// Recess-mode detection: if all dated items are from โค1995, the feed returned
// historical archive data instead of current procedures (EP API recess behaviour).
// See .github/prompts/07-mcp-reference.md ยง11 row #5.
const payload = _parseResultPayload(result);
if (detectProceduresFeedRecessMode(payload)) {
console.warn(
'๐ก procedures-feed: recess mode โ response contains only historical procedures (โค1995); use get_adopted_texts({ year: $YEAR }) or track_legislation({ procedureId }) instead'
);
const existingWarnings = Array.isArray(payload?.['dataQualityWarnings'])
? (payload['dataQualityWarnings'] as string[])
: [];
const augmented: Record<string, unknown> = {
...(payload as Record<string, unknown>),
recessMode: true,
dataQualityWarnings: [
...existingWarnings,
'RECESS_MODE: procedures-feed returned historical archive (all items โค1995) โ likely parliamentary recess; fallback: get_adopted_texts({ year: $YEAR }) or track_legislation({ procedureId })',
],
};
const augmentedText = JSON.stringify(augmented);
const originalContent = result.content;
const updatedContent: MCPContentItem[] =
Array.isArray(originalContent) && originalContent.length > 0
? originalContent.map((item, index) =>
index === 0 ? { ...item, text: augmentedText } : item
)
: [{ type: 'text', text: augmentedText }];
return { ...result, content: updatedContent };
}
return result;
}
/**
* Get adopted texts feed (most recent updates via EP API v2)
*
* Post-processes the response to honour upstream freshness-fallback warnings
* added by `Hack23/European-Parliament-MCP-Server` when the feed payload
* contains no items from the current calendar year:
*
* - `FRESHNESS_FALLBACK: โฆ` in `dataQualityWarnings[]` indicates the server
* augmented the response with `GET /adopted-texts?year={currentYear}`.
* The result is kept (do NOT downgrade to C4 โ the augmented items are
* confirmable, current-year, EP-published documents) and two fields are
* added to the payload:
* - `freshness: "augmented"` โ callers can detect the augmentation
* - `dataFreshnessWarnings: string[]` โ the subset of `dataQualityWarnings`
* that starts with `FRESHNESS_FALLBACK`, forwarded for Stage-A consumers
*
* - `FRESHNESS_FALLBACK_FAILED: โฆ` indicates the feed was stale AND the
* fallback `GET /adopted-texts?year=โฆ` also returned no items. The tool
* is recorded as failed (escalated to `ANALYSIS_ONLY`) so downstream
* consumers do not treat an empty-year dataset as fresh evidence.
*
* @param options - Pagination options
* @returns Adopted texts feed data, possibly with augmented freshness fields
*/
async getAdoptedTextsFeed(options: GetAdoptedTextsFeedOptions = {}): Promise<MCPToolResult> {
const result = await this.safeCallTool(
'get_adopted_texts_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
const payload = _parseResultPayload(result);
const rawWarnings = payload?.['dataQualityWarnings'];
const warnings: string[] = Array.isArray(rawWarnings)
? rawWarnings.filter((w): w is string => typeof w === 'string')
: [];
const freshnessWarnings = warnings.filter((w) => w.startsWith('FRESHNESS_FALLBACK'));
if (freshnessWarnings.length === 0) {
return result;
}
// FRESHNESS_FALLBACK_FAILED: feed broken AND fallback also empty โ escalate.
// Pick the first FAILED warning specifically so the recorded reason is
// accurate even when both FAILED and non-FAILED FRESHNESS_FALLBACK entries
// co-exist in the same response.
const failedWarning = freshnessWarnings.find((w) => w.startsWith('FRESHNESS_FALLBACK_FAILED'));
if (failedWarning !== undefined) {
return this._recordToolFailure(
'get_adopted_texts_feed',
`ANALYSIS_ONLY: ${failedWarning.slice(0, 200)}`,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
// FRESHNESS_FALLBACK (non-FAILED): server augmented with current-year items.
// Keep the result but surface the freshness metadata so Stage-A consumers
// can detect augmentation without re-parsing raw dataQualityWarnings.
// Preserve the full MCPToolResult shape (isError, additional content items,
// etc.) โ only rewrite content[0].text with the augmented JSON.
const augmented: Record<string, unknown> = {
...(payload as Record<string, unknown>),
freshness: 'augmented',
dataFreshnessWarnings: freshnessWarnings,
};
const augmentedText = JSON.stringify(augmented);
const originalContent = result.content;
const updatedContent: MCPContentItem[] =
Array.isArray(originalContent) && originalContent.length > 0
? originalContent.map((item, index) =>
index === 0 ? { ...item, text: augmentedText } : item
)
: [{ type: 'text', text: augmentedText }];
return { ...result, content: updatedContent };
}
/**
* Get MEP declarations feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns MEP declarations feed data
*/
async getMEPDeclarationsFeed(
options: GetMEPDeclarationsFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_mep_declarations_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get documents feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns Documents feed data
*/
async getDocumentsFeed(options: GetDocumentsFeedOptions = {}): Promise<MCPToolResult> {
return this.safeCallTool(
'get_documents_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get plenary documents feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns Plenary documents feed data
*/
async getPlenaryDocumentsFeed(
options: GetPlenaryDocumentsFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_plenary_documents_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get committee documents feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns Committee documents feed data
*/
async getCommitteeDocumentsFeed(
options: GetCommitteeDocumentsFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_committee_documents_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get plenary session documents feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns Plenary session documents feed data
*/
async getPlenarySessionDocumentsFeed(
options: GetPlenarySessionDocumentsFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_plenary_session_documents_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get external documents feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns External documents feed data
*/
async getExternalDocumentsFeed(
options: GetExternalDocumentsFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_external_documents_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get parliamentary questions feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns Parliamentary questions feed data
*/
async getParliamentaryQuestionsFeed(
options: GetParliamentaryQuestionsFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_parliamentary_questions_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get corporate bodies feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns Corporate bodies feed data
*/
async getCorporateBodiesFeed(
options: GetCorporateBodiesFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_corporate_bodies_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get controlled vocabularies feed (most recent updates via EP API v2)
*
* @param options - Pagination options
* @returns Controlled vocabularies feed data
*/
async getControlledVocabulariesFeed(
options: GetControlledVocabulariesFeedOptions = {}
): Promise<MCPToolResult> {
return this.safeCallTool(
'get_controlled_vocabularies_feed',
options,
EuropeanParliamentMCPClient.FEED_FALLBACK
);
}
/**
* Get a specific event linked to a legislative procedure.
* Returns a single event for the specified procedure and event identifiers.
*
* @param options - Options including required processId and eventId
* @returns Procedure event data
*/
async getProcedureEventById(options: GetProcedureEventByIdOptions): Promise<MCPToolResult> {
if (typeof options.processId !== 'string' || options.processId.trim().length === 0) {
console.warn(
'get_procedure_event_by_id called without valid processId (non-empty string required)'
);
return { content: [{ type: 'text', text: PROCEDURE_EVENT_FALLBACK }] };
}
if (typeof options.eventId !== 'string' || options.eventId.trim().length === 0) {
console.warn(
'get_procedure_event_by_id called without valid eventId (non-empty string required)'
);
return { content: [{ type: 'text', text: PROCEDURE_EVENT_FALLBACK }] };
}
return this.safeCallTool(
'get_procedure_event_by_id',
{ processId: options.processId.trim(), eventId: options.eventId.trim() },
PROCEDURE_EVENT_FALLBACK
);
}
/**
* Check server health and feed availability status.
* Returns server version, uptime, per-feed health status, and overall availability.
* Does not make upstream API calls โ reports cached status from recent tool invocations.
*
* @returns Server health and feed availability data
*/
async getServerHealth(): Promise<MCPToolResult> {
return this.safeCallTool('get_server_health', {}, SERVER_HEALTH_FALLBACK);
}
}
let clientInstance: EuropeanParliamentMCPClient | null = null;
/**
* Get or create singleton MCP client instance
*
* @param options - Client options
* @returns Connected MCP client
*/
export async function getEPMCPClient(
options: MCPClientOptions = {}
): Promise<EuropeanParliamentMCPClient> {
if (!clientInstance) {
clientInstance = new EuropeanParliamentMCPClient(options);
await clientInstance.connect();
}
return clientInstance;
}
/**
* Close and cleanup singleton MCP client
*/
export async function closeEPMCPClient(): Promise<void> {
if (clientInstance) {
clientInstance.disconnect();
clientInstance = null;
}
}
|